Addition chains: Difference between revisions

Content added Content deleted
(→‎{{header|Haskell}}: added practical solution)
m (syntax highlighting fixup automation)
Line 26: Line 26:
{{trans|Python}}
{{trans|Python}}


<lang 11l>F bauer(n)
<syntaxhighlight lang=11l>F bauer(n)
V chain = [0] * n
V chain = [0] * n
V in_chain = [0B] * (n + 1)
V in_chain = [0B] * (n + 1)
Line 61: Line 61:
L(n) [7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379]
L(n) [7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379]
V (best, cnt) = bauer(n)
V (best, cnt) = bauer(n)
print("L(#.) = #., count of minimum chain: #.\ne.g.: #.\n".format(n, best.len - 1, cnt, best))</lang>
print("L(#.) = #., count of minimum chain: #.\ne.g.: #.\n".format(n, best.len - 1, cnt, best))</syntaxhighlight>


{{out}}
{{out}}
Line 105: Line 105:
=={{header|C}}==
=={{header|C}}==
{{trans|Kotlin}}
{{trans|Kotlin}}
<lang c>#include <stdio.h>
<syntaxhighlight lang=c>#include <stdio.h>
#include <stdlib.h>
#include <stdlib.h>
#include <string.h>
#include <string.h>
Line 300: Line 300:
for (i = 0; i < 12; ++i) findBrauer(nums[i], 12, 79);
for (i = 0; i < 12; ++i) findBrauer(nums[i], 12, 79);
return 0;
return 0;
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 386: Line 386:
=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==
{{trans|Java}}
{{trans|Java}}
<lang csharp>using System;
<syntaxhighlight lang=csharp>using System;


namespace AdditionChains {
namespace AdditionChains {
Line 433: Line 433:
}
}
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>N = 7
<pre>N = 7
Line 486: Line 486:
While this worked, something made it run extremely slow.
While this worked, something made it run extremely slow.
{{trans|D}}
{{trans|D}}
<lang cpp>#include <iostream>
<syntaxhighlight lang=cpp>#include <iostream>
#include <tuple>
#include <tuple>
#include <vector>
#include <vector>
Line 531: Line 531:


return 0;
return 0;
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 584: Line 584:
=={{header|D}}==
=={{header|D}}==
{{trans|Scala}}
{{trans|Scala}}
<lang D>import std.stdio;
<syntaxhighlight lang=D>import std.stdio;
import std.typecons;
import std.typecons;


Line 622: Line 622:
find_brauer(i);
find_brauer(i);
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>N = 7
<pre>N = 7
Line 673: Line 673:


=={{header|EchoLisp}}==
=={{header|EchoLisp}}==
<lang scheme>
<syntaxhighlight lang=scheme>
;; 2^n
;; 2^n
(define exp2 (build-vector 32 (lambda(i)(expt 2 i))))
(define exp2 (build-vector 32 (lambda(i)(expt 2 i))))
Line 720: Line 720:
(printf "L(%d) = %d - brauer-chains: %d non-brauer: %d chains: %a %a "
(printf "L(%d) = %d - brauer-chains: %d non-brauer: %d chains: %a %a "
n *minlg* [*counts* 0] [*counts* 1] [*chains* 0] [*chains* 1]))
n *minlg* [*counts* 0] [*counts* 1] [*chains* 0] [*chains* 1]))
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 743: Line 743:
===Version 1===
===Version 1===
{{trans|Kotlin}}
{{trans|Kotlin}}
<lang go>package main
<syntaxhighlight lang=go>package main


import "fmt"
import "fmt"
Line 896: Line 896:
findBrauer(num, 12, 79)
findBrauer(num, 12, 79)
}
}
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 983: Line 983:
{{trans|Phix}}
{{trans|Phix}}
Much faster than Version 1 and can now complete the non-Brauer analysis for N > 79 in a reasonable time.
Much faster than Version 1 and can now complete the non-Brauer analysis for N > 79 in a reasonable time.
<lang go>package main
<syntaxhighlight lang=go>package main


import (
import (
Line 1,100: Line 1,100:
}
}
fmt.Printf("\nTook %s\n", time.Since(start))
fmt.Printf("\nTook %s\n", time.Since(start))
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 1,191: Line 1,191:
=={{header|Groovy}}==
=={{header|Groovy}}==
{{trans|Java}}
{{trans|Java}}
<lang Groovy>class AdditionChains {
<syntaxhighlight lang=Groovy>class AdditionChains {
private static class Pair {
private static class Pair {
int f, s
int f, s
Line 1,244: Line 1,244:
}
}
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>N = 7
<pre>N = 7
Line 1,298: Line 1,298:
Implementation using backtracking.
Implementation using backtracking.


<lang haskell>import Data.List (union)
<syntaxhighlight lang=haskell>import Data.List (union)


-- search strategies
-- search strategies
Line 1,320: Line 1,320:
isBrauer [_] = True
isBrauer [_] = True
isBrauer [_,_] = True
isBrauer [_,_] = True
isBrauer (x:y:xs) = (x - y) `elem` (y:xs) && isBrauer (y:xs)</lang>
isBrauer (x:y:xs) = (x - y) `elem` (y:xs) && isBrauer (y:xs)</syntaxhighlight>


Usage examples
Usage examples
Line 1,340: Line 1,340:
Tasks implementation
Tasks implementation


<lang haskell>task :: Int -> IO()
<syntaxhighlight lang=haskell>task :: Int -> IO()
task n =
task n =
let ch = chains total n
let ch = chains total n
Line 1,352: Line 1,352:
printf "non-Brauer chains(%i)\t: count = %i\tEx: %s\n\n" n (length ch - length br) (show $ reverse $ head nbr)
printf "non-Brauer chains(%i)\t: count = %i\tEx: %s\n\n" n (length ch - length br) (show $ reverse $ head nbr)
else
else
putStrLn "No non Brauer chains\n"</lang>
putStrLn "No non Brauer chains\n"</syntaxhighlight>


<pre>λ> mapM_ task [7,14,21,29,32,42,64]
<pre>λ> mapM_ task [7,14,21,29,32,42,64]
Line 1,385: Line 1,385:
For the extra task used compiled code, not GHCi.
For the extra task used compiled code, not GHCi.


<lang haskell>extraTask :: Int -> IO()
<syntaxhighlight lang=haskell>extraTask :: Int -> IO()
extraTask n =
extraTask n =
let ch = chains brauer n
let ch = chains brauer n
Line 1,393: Line 1,393:
putStrLn "Non-Brauer analysis suppressed\n"
putStrLn "Non-Brauer analysis suppressed\n"


main = mapM_ extraTask [47, 79, 191, 382, 379]</lang>
main = mapM_ extraTask [47, 79, 191, 382, 379]</syntaxhighlight>


<pre>L(47) = 8
<pre>L(47) = 8
Line 1,422: Line 1,422:
Journal de théorie des nombres de Bordeaux, 6 no. 1 (1994), p. 21-38,'' [http://www.numdam.org/item?id=JTNB_1994__6_1_21_0].
Journal de théorie des nombres de Bordeaux, 6 no. 1 (1994), p. 21-38,'' [http://www.numdam.org/item?id=JTNB_1994__6_1_21_0].


<lang haskell>binaryChain 1 = [1]
<syntaxhighlight lang=haskell>binaryChain 1 = [1]
binaryChain n | even n = n : binaryChain (n `div` 2)
binaryChain n | even n = n : binaryChain (n `div` 2)
| odd n = n : binaryChain (n - 1)
| odd n = n : binaryChain (n - 1)
Line 1,441: Line 1,441:
c1 `add` c2 = map (head c2 +) c1 ++ c2
c1 `add` c2 = map (head c2 +) c1 ++ c2
log2 = floor . logBase 2 . fromIntegral</lang>
log2 = floor . logBase 2 . fromIntegral</syntaxhighlight>


<pre>λ> binaryChain 191
<pre>λ> binaryChain 191
Line 1,457: Line 1,457:
=={{header|Java}}==
=={{header|Java}}==
{{trans|D}}
{{trans|D}}
<lang Java>public class AdditionChains {
<syntaxhighlight lang=Java>public class AdditionChains {
private static class Pair {
private static class Pair {
int f, s;
int f, s;
Line 1,510: Line 1,510:
}
}
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>N = 7
<pre>N = 7
Line 1,562: Line 1,562:
=={{header|Julia}}==
=={{header|Julia}}==
{{trans|Python}}
{{trans|Python}}
<lang julia>checksequence(pos, seq, n, minlen) =
<syntaxhighlight lang=julia>checksequence(pos, seq, n, minlen) =
pos > minlen || seq[1] > n ? (minlen, 0) :
pos > minlen || seq[1] > n ? (minlen, 0) :
seq[1] == n ? (pos, 1) :
seq[1] == n ? (pos, 1) :
Line 1,587: Line 1,587:
println("Number of minimum length Brauer chains: $nchains")
println("Number of minimum length Brauer chains: $nchains")
end
end
</lang>{{out}}
</syntaxhighlight>{{out}}
<pre>
<pre>
N = 7
N = 7
Line 1,631: Line 1,631:


I've then extended the code to count the number of non-Brauer chains of the same minimum length - basically 'brute' force to generate all addition chains and then subtracted the number of Brauer ones - plus examples for both. For N <= 64 this adds little to the execution time but adds about 1 minute for N = 79 and I gave up waiting for N = 191! To deal with these glacial execution times, I've added code which enables you to suppress the non-Brauer generation for N above a specified figure.
I've then extended the code to count the number of non-Brauer chains of the same minimum length - basically 'brute' force to generate all addition chains and then subtracted the number of Brauer ones - plus examples for both. For N <= 64 this adds little to the execution time but adds about 1 minute for N = 79 and I gave up waiting for N = 191! To deal with these glacial execution times, I've added code which enables you to suppress the non-Brauer generation for N above a specified figure.
<lang scala>// version 1.1.51
<syntaxhighlight lang=scala>// version 1.1.51


var example: List<Int>? = null
var example: List<Int>? = null
Line 1,721: Line 1,721:
println("Searching for Brauer chains up to a minimum length of 12:")
println("Searching for Brauer chains up to a minimum length of 12:")
for (num in nums) findBrauer(num, 12, 79)
for (num in nums) findBrauer(num, 12, 79)
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 1,807: Line 1,807:
=={{header|Lua}}==
=={{header|Lua}}==
{{trans|D}}
{{trans|D}}
<lang lua>function index(a,i)
<syntaxhighlight lang=lua>function index(a,i)
return a[i + 1]
return a[i + 1]
end
end
Line 1,874: Line 1,874:
end
end


main()</lang>
main()</syntaxhighlight>
{{out}}
{{out}}
<pre>N = 7
<pre>N = 7
Line 1,927: Line 1,927:
{{trans|Go}}
{{trans|Go}}
This is a translation of the second Go version.
This is a translation of the second Go version.
<lang Nim>import times, strutils
<syntaxhighlight lang=Nim>import times, strutils


const
const
Line 2,005: Line 2,005:
if nonBrauerCount > 0:
if nonBrauerCount > 0:
echo "Non-Brauer example: ", nonBrauerExample.join(", ")
echo "Non-Brauer example: ", nonBrauerExample.join(", ")
echo "\nTook ", now() - start</lang>
echo "\nTook ", now() - start</syntaxhighlight>


{{out}}
{{out}}
Line 2,093: Line 2,093:
=={{header|Perl}}==
=={{header|Perl}}==
{{trans|Raku}}
{{trans|Raku}}
<lang perl>use strict;
<syntaxhighlight lang=perl>use strict;
use feature 'say';
use feature 'say';


Line 2,201: Line 2,201:
# 47, 79, 191, 382, 379, 379, 12509);
# 47, 79, 191, 382, 379, 379, 12509);
say "Searching for Brauer chains up to a minimum length of 12:";
say "Searching for Brauer chains up to a minimum length of 12:";
for (@nums) { findBrauer $_, 12, 79 }</lang>
for (@nums) { findBrauer $_, 12, 79 }</syntaxhighlight>
{{out}}
{{out}}
<pre style="height:35ex">N = 7
<pre style="height:35ex">N = 7
Line 2,252: Line 2,252:
Note the internal values of l(n) are [consistently] +1 compared to what the rest of the world says.
Note the internal values of l(n) are [consistently] +1 compared to what the rest of the world says.


<!--<lang Phix>(phixonline)-->
<!--<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>
Line 2,353: Line 2,353:
<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;">"l(%d) = %d, Brauer:%d,%s Non-Brauer:%d,%s (%s, %d perms)\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">num</span><span style="color: #0000FF;">,</span><span style="color: #000000;">l</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">bc</span><span style="color: #0000FF;">,</span><span style="color: #000000;">bs</span><span style="color: #0000FF;">,</span><span style="color: #000000;">nbc</span><span style="color: #0000FF;">,</span><span style="color: #000000;">ns</span><span style="color: #0000FF;">,</span><span style="color: #000000;">e</span><span style="color: #0000FF;">,</span><span style="color: #000000;">tries</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;">"l(%d) = %d, Brauer:%d,%s Non-Brauer:%d,%s (%s, %d perms)\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">num</span><span style="color: #0000FF;">,</span><span style="color: #000000;">l</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">bc</span><span style="color: #0000FF;">,</span><span style="color: #000000;">bs</span><span style="color: #0000FF;">,</span><span style="color: #000000;">nbc</span><span style="color: #0000FF;">,</span><span style="color: #000000;">ns</span><span style="color: #0000FF;">,</span><span style="color: #000000;">e</span><span style="color: #0000FF;">,</span><span style="color: #000000;">tries</span><span style="color: #0000FF;">})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</lang>-->
<!--</syntaxhighlight>-->


{{out}}
{{out}}
Line 2,391: Line 2,391:
=={{header|Python}}==
=={{header|Python}}==
{{trans|Java}}
{{trans|Java}}
<lang python>def prepend(n, seq):
<syntaxhighlight lang=python>def prepend(n, seq):
return [n] + seq
return [n] + seq


Line 2,429: Line 2,429:
nums = [7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379]
nums = [7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379]
for i in nums:
for i in nums:
find_brauer(i)</lang>
find_brauer(i)</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,481: Line 2,481:


====Faster method====
====Faster method====
<lang python>def bauer(n):
<syntaxhighlight lang=python>def bauer(n):
chain = [0]*n
chain = [0]*n
in_chain = [False]*(n + 1)
in_chain = [False]*(n + 1)
Line 2,517: Line 2,517:
for n in [7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379]:
for n in [7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379]:
best, cnt = bauer(n)
best, cnt = bauer(n)
print(f'L({n}) = {len(best) - 1}, count of minimum chain: {cnt}\ne.g.: {best}\n')</lang>
print(f'L({n}) = {len(best) - 1}, count of minimum chain: {cnt}\ne.g.: {best}\n')</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,539: Line 2,539:
This implementation uses the [https://docs.racket-lang.org/rosette-guide/index.html Rosette] language in Racket. It is inefficient as it asks an SMT solver to enumerate every possible solutions. However, it is very straightforward to write, and in fact is quite efficient for computing <code>l(n)</code> and finding one example (solve n = 379 in ~3 seconds).
This implementation uses the [https://docs.racket-lang.org/rosette-guide/index.html Rosette] language in Racket. It is inefficient as it asks an SMT solver to enumerate every possible solutions. However, it is very straightforward to write, and in fact is quite efficient for computing <code>l(n)</code> and finding one example (solve n = 379 in ~3 seconds).


<lang racket>#lang rosette
<syntaxhighlight lang=racket>#lang rosette


(define (basic-constraints xs n)
(define (basic-constraints xs n)
Line 2,595: Line 2,595:


(for ([x (in-list '(191 382 379 12509))])
(for ([x (in-list '(191 382 379 12509))])
(compute/time x #:enumerate? #f))</lang>
(compute/time x #:enumerate? #f))</syntaxhighlight>


{{out}}
{{out}}
Line 2,685: Line 2,685:
(formerly Perl 6)
(formerly Perl 6)
{{trans|Kotlin}}
{{trans|Kotlin}}
<lang perl6>my @Example = ();
<syntaxhighlight lang=perl6>my @Example = ();


sub check-Sequence($pos, @seq, $n, $minLen --> List) {
sub check-Sequence($pos, @seq, $n, $minLen --> List) {
Line 2,781: Line 2,781:


say "Searching for Brauer chains up to a minimum length of 12:";
say "Searching for Brauer chains up to a minimum length of 12:";
find-Brauer $_, 12, 79 for 7, 14, 21, 29, 32, 42, 64 #, 47, 79, 191, 382, 379, 379, 12509 # un-comment for extra-credit</lang>
find-Brauer $_, 12, 79 for 7, 14, 21, 29, 32, 42, 64 #, 47, 79, 191, 382, 379, 379, 12509 # un-comment for extra-credit</syntaxhighlight>
{{out}}
{{out}}
<pre>Searching for Brauer chains up to a minimum length of 12:
<pre>Searching for Brauer chains up to a minimum length of 12:
Line 2,832: Line 2,832:
=={{header|Ruby}}==
=={{header|Ruby}}==
{{trans|D}}
{{trans|D}}
<lang ruby>def check_seq(pos, seq, n, min_len)
<syntaxhighlight lang=ruby>def check_seq(pos, seq, n, min_len)
if pos > min_len or seq[0] > n then
if pos > min_len or seq[0] > n then
return min_len, 0
return min_len, 0
Line 2,880: Line 2,880:
end
end


main()</lang>
main()</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,933: Line 2,933:
=={{header|Scala}}==
=={{header|Scala}}==
Following Scala implementation finds number of minimum length Brauer chains and corresponding length.
Following Scala implementation finds number of minimum length Brauer chains and corresponding length.
<lang Scala>
<syntaxhighlight lang=Scala>
object chains{
object chains{


Line 2,966: Line 2,966:
}
}
}
}
</syntaxhighlight>
</lang>
<pre>
<pre>
N = 7
N = 7
Line 3,023: Line 3,023:
=={{header|Visual Basic .NET}}==
=={{header|Visual Basic .NET}}==
{{trans|C#}}
{{trans|C#}}
<lang vbnet>Module Module1
<syntaxhighlight lang=vbnet>Module Module1


Function Prepend(n As Integer, seq As List(Of Integer)) As List(Of Integer)
Function Prepend(n As Integer, seq As List(Of Integer)) As List(Of Integer)
Line 3,081: Line 3,081:
End Sub
End Sub


End Module</lang>
End Module</syntaxhighlight>
{{out}}
{{out}}
<pre>N = 7
<pre>N = 7
Line 3,136: Line 3,136:


Non-Brauer analysis limited to N = 191 in order to finish in a reasonable time - about 10.75 minutes on my machine.
Non-Brauer analysis limited to N = 191 in order to finish in a reasonable time - about 10.75 minutes on my machine.
<lang ecmascript>var maxLen = 13
<syntaxhighlight lang=ecmascript>var maxLen = 13
var maxNonBrauer = 191
var maxNonBrauer = 191


Line 3,223: Line 3,223:
} else System.print("Non-Brauer analysis suppressed")
} else System.print("Non-Brauer analysis suppressed")
}
}
System.print("\nTook %(System.clock - start) seconds.")</lang>
System.print("\nTook %(System.clock - start) seconds.")</syntaxhighlight>


{{out}}
{{out}}
Line 3,312: Line 3,312:
=={{header|zkl}}==
=={{header|zkl}}==
{{trans|EchoLisp}}
{{trans|EchoLisp}}
<lang zkl>var exp2=(32).pump(List,(2).pow), // 2^n, n=0..31
<syntaxhighlight lang=zkl>var exp2=(32).pump(List,(2).pow), // 2^n, n=0..31
_minlg, _counts, _chains; // counters and results
_minlg, _counts, _chains; // counters and results
Line 3,346: Line 3,346:
}
}
}
}
}</lang>
}</syntaxhighlight>
<lang zkl>fcn task(n){
<syntaxhighlight lang=zkl>fcn task(n){
_minlg=(0).MAX;
_minlg=(0).MAX;
chains(n,List(1),0);
chains(n,List(1),0);
Line 3,353: Line 3,353:
.fmt(n,_minlg,_counts.xplode(),_chains.filter()));
.fmt(n,_minlg,_counts.xplode(),_chains.filter()));
}
}
T(7,14,21,29,32,42,64,47,79).apply2(task);</lang>
T(7,14,21,29,32,42,64,47,79).apply2(task);</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>