Balanced ternary: Difference between revisions
Content added Content deleted
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
|||
Line 29: | Line 29: | ||
{{trans|Python}} |
{{trans|Python}} |
||
< |
<syntaxhighlight lang=11l>F py_idiv(a, b) |
||
I a >= 0 |
I a >= 0 |
||
R a I/ b |
R a I/ b |
||
Line 119: | Line 119: | ||
V r = a * (b - c) |
V r = a * (b - c) |
||
print(‘a * (b - c): ’r.to_int()‘ ’r)</ |
print(‘a * (b - c): ’r.to_int()‘ ’r)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 131: | Line 131: | ||
=={{header|Ada}}== |
=={{header|Ada}}== |
||
Specifications (bt.ads): |
Specifications (bt.ads): |
||
< |
<syntaxhighlight lang=Ada>with Ada.Finalization; |
||
package BT is |
package BT is |
||
Line 177: | Line 177: | ||
procedure Finalize (Object : in out Balanced_Ternary); |
procedure Finalize (Object : in out Balanced_Ternary); |
||
end BT;</ |
end BT;</syntaxhighlight> |
||
Implementation (bt.adb): |
Implementation (bt.adb): |
||
< |
<syntaxhighlight lang=Ada>with Ada.Unchecked_Deallocation; |
||
package body BT is |
package body BT is |
||
Line 360: | Line 360: | ||
end Initialize; |
end Initialize; |
||
end BT;</ |
end BT;</syntaxhighlight> |
||
Test task requirements (testbt.adb): |
Test task requirements (testbt.adb): |
||
< |
<syntaxhighlight lang=Ada>with Ada.Text_Io; use Ada.Text_Io; |
||
with Ada.Integer_Text_Io; use Ada.Integer_Text_Io; |
with Ada.Integer_Text_Io; use Ada.Integer_Text_Io; |
||
with BT; use BT; |
with BT; use BT; |
||
Line 381: | Line 381: | ||
Put("a * (b - c) = "); Put(To_integer(Result), 4); |
Put("a * (b - c) = "); Put(To_integer(Result), 4); |
||
Put_Line (" " & To_String(Result)); |
Put_Line (" " & To_String(Result)); |
||
end TestBT;</ |
end TestBT;</syntaxhighlight> |
||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 399: | Line 399: | ||
To demonstrate the possibility, the ''integerFromBT'' and ''negateBT'' handlers here work by being tricksy with the characters' Unicode numbers. It's a more efficient way to deal with the characters. But I'm not sure how this'll be taken ''vis-à-vis'' not converting to native integers first, so the remaining handlers use a strictly if-then string comparison approach. Applescript's quite happy to convert automatically between integers, reals, numeric strings, and single-item lists containing numbers, so ''BTFromInteger'' accepts any of these forms, but the numbers represented must be whole-number values and must be small enough not to error AppleScript's ''as integer'' coercion. This coercion is error free for numbers in the range -(2 ^ 31) to 2 ^ 31 - 1, although actual integer class objects can only represent numbers in the range -(2 ^ 29) to 2 ^ 29 - 1. ''IntegerFromBT'' doesn't currently impose any integer-class size limit on its output. |
To demonstrate the possibility, the ''integerFromBT'' and ''negateBT'' handlers here work by being tricksy with the characters' Unicode numbers. It's a more efficient way to deal with the characters. But I'm not sure how this'll be taken ''vis-à-vis'' not converting to native integers first, so the remaining handlers use a strictly if-then string comparison approach. Applescript's quite happy to convert automatically between integers, reals, numeric strings, and single-item lists containing numbers, so ''BTFromInteger'' accepts any of these forms, but the numbers represented must be whole-number values and must be small enough not to error AppleScript's ''as integer'' coercion. This coercion is error free for numbers in the range -(2 ^ 31) to 2 ^ 31 - 1, although actual integer class objects can only represent numbers in the range -(2 ^ 29) to 2 ^ 29 - 1. ''IntegerFromBT'' doesn't currently impose any integer-class size limit on its output. |
||
< |
<syntaxhighlight lang=applescript>-- Build a balanced ternary, as text, from an integer value or acceptable AppleScript substitute. |
||
on BTFromInteger(n) |
on BTFromInteger(n) |
||
try |
try |
||
Line 566: | Line 566: | ||
set line4 to "a * (b - c) = " & it & " or " & my integerFromBT(it) |
set line4 to "a * (b - c) = " & it & " or " & my integerFromBT(it) |
||
return line1 & linefeed & line2 & linefeed & line3 & linefeed & line4</ |
return line1 & linefeed & line2 & linefeed & line3 & linefeed & line4</syntaxhighlight> |
||
{{output}} |
{{output}} |
||
< |
<syntaxhighlight lang=applescript>"a = 523 |
||
b = -436 |
b = -436 |
||
c = 65 |
c = 65 |
||
a * (b - c) = ----0+--0++0 or -262023"</ |
a * (b - c) = ----0+--0++0 or -262023"</syntaxhighlight> |
||
=={{header|ATS}}== |
=={{header|ATS}}== |
||
< |
<syntaxhighlight lang=ATS> |
||
(* |
(* |
||
** This one is |
** This one is |
||
Line 789: | Line 789: | ||
// |
// |
||
} (* end of [main0] *) |
} (* end of [main0] *) |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 799: | Line 799: | ||
=={{header|AutoHotkey}}== |
=={{header|AutoHotkey}}== |
||
< |
<syntaxhighlight lang=AutoHotkey>BalancedTernary(n){ |
||
k = 0 |
k = 0 |
||
if abs(n)<2 |
if abs(n)<2 |
||
Line 820: | Line 820: | ||
} |
} |
||
return r |
return r |
||
}</ |
}</syntaxhighlight> |
||
Examples:< |
Examples:<syntaxhighlight lang=AutoHotkey>data = |
||
( |
( |
||
523 |
523 |
||
Line 831: | Line 831: | ||
result .= A_LoopField " : " BalancedTernary(A_LoopField) "`n" |
result .= A_LoopField " : " BalancedTernary(A_LoopField) "`n" |
||
MsgBox % result |
MsgBox % result |
||
return</ |
return</syntaxhighlight> |
||
Outputs:<pre> |
Outputs:<pre> |
||
523 : +-0++0+ |
523 : +-0++0+ |
||
Line 840: | Line 840: | ||
=={{header|C}}== |
=={{header|C}}== |
||
{{trans|Perl}} |
{{trans|Perl}} |
||
< |
<syntaxhighlight lang=c>#include <stdio.h> |
||
#include <string.h> |
#include <string.h> |
||
Line 1,041: | Line 1,041: | ||
return 0; |
return 0; |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> a: +-0++0+ 523 |
<pre> a: +-0++0+ 523 |
||
Line 1,049: | Line 1,049: | ||
=={{header|C sharp|C#}}== |
=={{header|C sharp|C#}}== |
||
< |
<syntaxhighlight lang=csharp>using System; |
||
using System.Text; |
using System.Text; |
||
using System.Collections.Generic; |
using System.Collections.Generic; |
||
Line 1,279: | Line 1,279: | ||
return result; |
return result; |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
output: |
output: |
||
<pre>a: +-0++0+ = 523 |
<pre>a: +-0++0+ = 523 |
||
Line 1,287: | Line 1,287: | ||
=={{header|C++}}== |
=={{header|C++}}== |
||
< |
<syntaxhighlight lang=cpp>#include <iostream> |
||
#include <string> |
#include <string> |
||
#include <climits> |
#include <climits> |
||
Line 1,499: | Line 1,499: | ||
return 0; |
return 0; |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output |
Output |
||
Line 1,511: | Line 1,511: | ||
=={{header|Common Lisp}}== |
=={{header|Common Lisp}}== |
||
< |
<syntaxhighlight lang=lisp>;;; balanced ternary |
||
;;; represented as a list of 0, 1 or -1s, with least significant digit first |
;;; represented as a list of 0, 1 or -1s, with least significant digit first |
||
Line 1,603: | Line 1,603: | ||
(bt-integer b) (bt-string b) |
(bt-integer b) (bt-string b) |
||
(bt-integer c) (bt-string c) |
(bt-integer c) (bt-string c) |
||
(bt-integer d) (bt-string d)))</ |
(bt-integer d) (bt-string d)))</syntaxhighlight>output<syntaxhighlight lang=text>a 523 +-0++0+ |
||
b -436 -++-0-- |
b -436 -++-0-- |
||
c 65 +-++- |
c 65 +-++- |
||
a × (b − c) = -262023 ----0+--0++0</ |
a × (b − c) = -262023 ----0+--0++0</syntaxhighlight> |
||
=={{header|D}}== |
=={{header|D}}== |
||
{{trans|Python}} |
{{trans|Python}} |
||
< |
<syntaxhighlight lang=d>import std.stdio, std.bigint, std.range, std.algorithm; |
||
struct BalancedTernary { |
struct BalancedTernary { |
||
Line 1,753: | Line 1,753: | ||
const /*immutable*/ r = a * (b - c); |
const /*immutable*/ r = a * (b - c); |
||
writeln("a * (b - c): ", r.toBint, ' ', r); |
writeln("a * (b - c): ", r.toBint, ' ', r); |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>a: 523 +-0++0+ |
<pre>a: 523 +-0++0+ |
||
Line 1,762: | Line 1,762: | ||
=={{header|Elixir}}== |
=={{header|Elixir}}== |
||
{{trans|Erlang}} |
{{trans|Erlang}} |
||
< |
<syntaxhighlight lang=elixir>defmodule Ternary do |
||
def to_string(t), do: ( for x <- t, do: to_char(x) ) |> List.to_string |
def to_string(t), do: ( for x <- t, do: to_char(x) ) |> List.to_string |
||
Line 1,835: | Line 1,835: | ||
IO.puts "b = #{bs} -> #{b}" |
IO.puts "b = #{bs} -> #{b}" |
||
IO.puts "c = #{cs} -> #{c}" |
IO.puts "c = #{cs} -> #{c}" |
||
IO.puts "a x (b - c) = #{rs} -> #{r}"</ |
IO.puts "a x (b - c) = #{rs} -> #{r}"</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,846: | Line 1,846: | ||
=={{header|Erlang}}== |
=={{header|Erlang}}== |
||
< |
<syntaxhighlight lang=erlang> |
||
-module(ternary). |
-module(ternary). |
||
-compile(export_all). |
-compile(export_all). |
||
Line 1,936: | Line 1,936: | ||
add_util(1) -> [0,1]; |
add_util(1) -> [0,1]; |
||
add_util(0) -> [0,0]. |
add_util(0) -> [0,0]. |
||
</syntaxhighlight> |
|||
</lang> |
|||
'''Output''' |
'''Output''' |
||
< |
<syntaxhighlight lang=erlang> |
||
234> ternary:test(). |
234> ternary:test(). |
||
A = +-0++0+ -> 523 |
A = +-0++0+ -> 523 |
||
Line 1,945: | Line 1,945: | ||
A x (B - C) = 0----0+--0++0 -> -262023 |
A x (B - C) = 0----0+--0++0 -> -262023 |
||
ok |
ok |
||
</syntaxhighlight> |
|||
</lang> |
|||
Line 1,953: | Line 1,953: | ||
{{trans|Common Lisp}} |
{{trans|Common Lisp}} |
||
{{works with|Factor|0.98}} |
{{works with|Factor|0.98}} |
||
< |
<syntaxhighlight lang=factor>USING: kernel combinators locals formatting lint literals |
||
sequences assocs strings arrays |
sequences assocs strings arrays |
||
math math.functions math.order ; |
math math.functions math.order ; |
||
Line 2,015: | Line 2,015: | ||
"c" c bt>integer c bt>string "%s: %d, %s\n" printf |
"c" c bt>integer c bt>string "%s: %d, %s\n" printf |
||
"a*(b-c)" d bt>integer d bt>string "%s: %d, %s\n" printf |
"a*(b-c)" d bt>integer d bt>string "%s: %d, %s\n" printf |
||
]</ |
]</syntaxhighlight> |
||
<lang>a: 523, +-0++0+ |
<syntaxhighlight lang=text>a: 523, +-0++0+ |
||
b: -436, -++-0-- |
b: -436, -++-0-- |
||
c: 65, +-++- |
c: 65, +-++- |
||
a*(b-c): -262023, ----0+--0++0</ |
a*(b-c): -262023, ----0+--0++0</syntaxhighlight> |
||
=={{header|FreeBASIC}}== |
=={{header|FreeBASIC}}== |
||
{{trans|Liberty BASIC}} |
{{trans|Liberty BASIC}} |
||
< |
<syntaxhighlight lang=freebasic> |
||
#define MAX(a, b) iif((a) > (b), (a), (b)) |
#define MAX(a, b) iif((a) > (b), (a), (b)) |
||
Dim Shared As Integer pow, signo |
Dim Shared As Integer pow, signo |
||
Line 2,151: | Line 2,151: | ||
Print "a*(b-c): ", a * (b - c) |
Print "a*(b-c): ", a * (b - c) |
||
Sleep |
Sleep |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,280: | Line 2,280: | ||
</pre> |
</pre> |
||
'''A crude English/Pidgin Algol translation of the above [[:Category:Glagol]] code.''' |
'''A crude English/Pidgin Algol translation of the above [[:Category:Glagol]] code.''' |
||
< |
<syntaxhighlight lang=algol68>PROGRAM Setun+; |
||
USES |
USES |
||
Parameter IS "...\Departments\Exchange\" |
Parameter IS "...\Departments\Exchange\" |
||
Line 2,392: | Line 2,392: | ||
Output.ChTarget(" = %d.", InNumber(), 0, 0, 0); |
Output.ChTarget(" = %d.", InNumber(), 0, 0, 0); |
||
Remove.Memory |
Remove.Memory |
||
END Setun.</ |
END Setun.</syntaxhighlight> |
||
=={{header|Go}}== |
=={{header|Go}}== |
||
< |
<syntaxhighlight lang=go>package main |
||
import ( |
import ( |
||
Line 2,618: | Line 2,618: | ||
fmt.Println("int overflow") |
fmt.Println("int overflow") |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,629: | Line 2,629: | ||
=={{header|Groovy}}== |
=={{header|Groovy}}== |
||
Solution: |
Solution: |
||
< |
<syntaxhighlight lang=groovy>enum T { |
||
m('-', -1), z('0', 0), p('+', 1) |
m('-', -1), z('0', 0), p('+', 1) |
||
Line 2,788: | Line 2,788: | ||
String toString() { value } |
String toString() { value } |
||
}</ |
}</syntaxhighlight> |
||
Test: |
Test: |
||
< |
<syntaxhighlight lang=groovy>BalancedTernaryInteger a = new BalancedTernaryInteger('+-0++0+') |
||
BalancedTernaryInteger b = new BalancedTernaryInteger(-436) |
BalancedTernaryInteger b = new BalancedTernaryInteger(-436) |
||
BalancedTernaryInteger c = new BalancedTernaryInteger(T.p, T.m, T.p, T.p, T.m) |
BalancedTernaryInteger c = new BalancedTernaryInteger(T.p, T.m, T.p, T.p, T.m) |
||
Line 2,806: | Line 2,806: | ||
println "\nDemonstrate failure:" |
println "\nDemonstrate failure:" |
||
assert (a * (b-c)) == a</ |
assert (a * (b-c)) == a</syntaxhighlight> |
||
Output: |
Output: |
||
Line 2,831: | Line 2,831: | ||
=={{header|Haskell}}== |
=={{header|Haskell}}== |
||
BTs are represented internally as lists of digits in integers from -1 to 1, but displayed as "+-0" strings. |
BTs are represented internally as lists of digits in integers from -1 to 1, but displayed as "+-0" strings. |
||
< |
<syntaxhighlight lang=haskell>data BalancedTernary = Bt [Int] |
||
zeroTrim a = if null s then [0] else s where |
zeroTrim a = if null s then [0] else s where |
||
Line 2,888: | Line 2,888: | ||
print $ map btInt [a,b,c] |
print $ map btInt [a,b,c] |
||
print $ r |
print $ r |
||
print $ btInt r</ |
print $ btInt r</syntaxhighlight> |
||
=={{header|Icon}} and {{header|Unicon}}== |
=={{header|Icon}} and {{header|Unicon}}== |
||
Line 2,895: | Line 2,895: | ||
Works in both languages: |
Works in both languages: |
||
< |
<syntaxhighlight lang=unicon>procedure main() |
||
a := "+-0++0+" |
a := "+-0++0+" |
||
write("a = +-0++0+"," = ",cvtFromBT("+-0++0+")) |
write("a = +-0++0+"," = ",cvtFromBT("+-0++0+")) |
||
Line 2,984: | Line 2,984: | ||
} |
} |
||
return (\negate,map(mul,"+-","-+")) | mul |
return (\negate,map(mul,"+-","-+")) | mul |
||
end</ |
end</syntaxhighlight> |
||
Output: |
Output: |
||
Line 3,000: | Line 3,000: | ||
Implementation: |
Implementation: |
||
< |
<syntaxhighlight lang=j>trigits=: 1+3 <.@^. 2 * 1&>.@| |
||
trinOfN=: |.@((_1 + ] #: #.&1@] + [) #&3@trigits) :. nOfTrin |
trinOfN=: |.@((_1 + ] #: #.&1@] + [) #&3@trigits) :. nOfTrin |
||
nOfTrin=: p.&3 :. trinOfN |
nOfTrin=: p.&3 :. trinOfN |
||
Line 3,011: | Line 3,011: | ||
add=: carry@(+/@,:) |
add=: carry@(+/@,:) |
||
neg=: - |
neg=: - |
||
mul=: trimLead0@carry@(+//.@(*/))</ |
mul=: trimLead0@carry@(+//.@(*/))</syntaxhighlight> |
||
trinary numbers are represented as a sequence of polynomial coefficients. The coefficient values are limited to 1, 0, and -1. The polynomial's "variable" will always be 3 (which happens to illustrate an interesting absurdity in the terminology we use to describe polynomials -- one which might be an obstacle for learning, for some people). |
trinary numbers are represented as a sequence of polynomial coefficients. The coefficient values are limited to 1, 0, and -1. The polynomial's "variable" will always be 3 (which happens to illustrate an interesting absurdity in the terminology we use to describe polynomials -- one which might be an obstacle for learning, for some people). |
||
Line 3,029: | Line 3,029: | ||
Definitions for example: |
Definitions for example: |
||
< |
<syntaxhighlight lang=j>a=: trinOfStr '+-0++0+' |
||
b=: trinOfN -436 |
b=: trinOfN -436 |
||
c=: trinOfStr '+-++-'</ |
c=: trinOfStr '+-++-'</syntaxhighlight> |
||
Required example: |
Required example: |
||
< |
<syntaxhighlight lang=j> nOfTrin&> a;b;c |
||
523 _436 65 |
523 _436 65 |
||
Line 3,041: | Line 3,041: | ||
----0+--0++0 |
----0+--0++0 |
||
nOfTrin a mul b (add -) c |
nOfTrin a mul b (add -) c |
||
_262023</ |
_262023</syntaxhighlight> |
||
=={{header|Java}}== |
=={{header|Java}}== |
||
< |
<syntaxhighlight lang=java> |
||
/* |
/* |
||
* Test case |
* Test case |
||
Line 3,256: | Line 3,256: | ||
} |
} |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output: |
Output: |
||
Line 3,271: | Line 3,271: | ||
{{trans|Python}} |
{{trans|Python}} |
||
< |
<syntaxhighlight lang=julia>struct BalancedTernary <: Signed |
||
digits::Vector{Int8} |
digits::Vector{Int8} |
||
end |
end |
||
Line 3,355: | Line 3,355: | ||
println("a * (b - c): $(Int(r)), $r") |
println("a * (b - c): $(Int(r)), $r") |
||
@assert Int(r) == Int(a) * (Int(b) - Int(c))</ |
@assert Int(r) == Int(a) * (Int(b) - Int(c))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 3,365: | Line 3,365: | ||
=={{header|Kotlin}}== |
=={{header|Kotlin}}== |
||
This is based on the Java entry. However, I've added 'BigInteger' support as this is a current requirement of the task description even though it's not actually needed to process the test case: |
This is based on the Java entry. However, I've added 'BigInteger' support as this is a current requirement of the task description even though it's not actually needed to process the test case: |
||
< |
<syntaxhighlight lang=scala>// version 1.1.3 |
||
import java.math.BigInteger |
import java.math.BigInteger |
||
Line 3,508: | Line 3,508: | ||
val iResult = bResult.toBigInteger() |
val iResult = bResult.toBigInteger() |
||
println("a * (b - c) = $bResult = $iResult") |
println("a * (b - c) = $bResult = $iResult") |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 3,519: | Line 3,519: | ||
=={{header|Liberty BASIC}}== |
=={{header|Liberty BASIC}}== |
||
<syntaxhighlight lang=lb> |
|||
<lang lb> |
|||
global tt$ |
global tt$ |
||
tt$="-0+" '-1 0 1; +2 -> 1 2 3, instr |
tt$="-0+" '-1 0 1; +2 -> 1 2 3, instr |
||
Line 3,657: | Line 3,657: | ||
wend |
wend |
||
end function |
end function |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
Line 3,672: | Line 3,672: | ||
=={{header|Lua}}== |
=={{header|Lua}}== |
||
{{trans|C}} |
{{trans|C}} |
||
< |
<syntaxhighlight lang=lua>function to_bt(n) |
||
local d = { '0', '+', '-' } |
local d = { '0', '+', '-' } |
||
local v = { 0, 1, -1 } |
local v = { 0, 1, -1 } |
||
Line 3,817: | Line 3,817: | ||
end |
end |
||
main()</ |
main()</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> a: +-0++0+ 523 |
<pre> a: +-0++0+ 523 |
||
Line 3,825: | Line 3,825: | ||
=={{header|Mathematica}} / {{header|Wolfram Language}}== |
=={{header|Mathematica}} / {{header|Wolfram Language}}== |
||
< |
<syntaxhighlight lang=mathematica>frombt = FromDigits[StringCases[#, {"+" -> 1, "-" -> -1, "0" -> 0}], |
||
3] &; |
3] &; |
||
tobt = If[Quotient[#, 3, -1] == 0, |
tobt = If[Quotient[#, 3, -1] == 0, |
||
Line 3,846: | Line 3,846: | ||
btnegate@#1], |
btnegate@#1], |
||
If[StringLength@#2 == 1, |
If[StringLength@#2 == 1, |
||
"0", #0[#1, StringDrop[#2, -1]] <> "0"]] &;</ |
"0", #0[#1, StringDrop[#2, -1]] <> "0"]] &;</syntaxhighlight> |
||
Examples: |
Examples: |
||
< |
<syntaxhighlight lang=mathematica>frombt[a = "+-0++0+"] |
||
b = tobt@-436 |
b = tobt@-436 |
||
frombt[c = "+-++-"] |
frombt[c = "+-++-"] |
||
btmultiply[a, btsubtract[b, c]]</ |
btmultiply[a, btsubtract[b, c]]</syntaxhighlight> |
||
Outputs: |
Outputs: |
||
<pre>523 |
<pre>523 |
||
Line 3,863: | Line 3,863: | ||
=={{header|МК-61/52}}== |
=={{header|МК-61/52}}== |
||
{{trans|Glagol}} |
{{trans|Glagol}} |
||
< |
<syntaxhighlight lang=mk-61>ЗН П2 Вx |x| П0 0 П3 П4 1 П5 |
||
ИП0 /-/ x<0 80 |
ИП0 /-/ x<0 80 |
||
ИП0 ^ ^ 3 / [x] П0 3 * - П1 |
ИП0 ^ ^ 3 / [x] П0 3 * - П1 |
||
Line 3,874: | Line 3,874: | ||
ИП2 /-/ ПП 88 1 П3 БП 10 |
ИП2 /-/ ПП 88 1 П3 БП 10 |
||
ИП3 x#0 86 ИП2 ПП 88 ИП4 С/П |
ИП3 x#0 86 ИП2 ПП 88 ИП4 С/П |
||
8 + ИП5 * ИП4 + П4 ИП5 1 0 * П5 В/О</ |
8 + ИП5 * ИП4 + П4 ИП5 1 0 * П5 В/О</syntaxhighlight> |
||
''Note: the "-", "0", "+" denotes by digits, respectively, the "7", "8", "9".'' |
''Note: the "-", "0", "+" denotes by digits, respectively, the "7", "8", "9".'' |
||
=={{header|Nim}}== |
=={{header|Nim}}== |
||
< |
<syntaxhighlight lang=Nim>import strformat |
||
import tables |
import tables |
||
Line 4,056: | Line 4,056: | ||
echo "a × (b - c):" |
echo "a × (b - c):" |
||
echo fmt"– in ternary: {x}" |
echo fmt"– in ternary: {x}" |
||
echo fmt"– in decimal: {x.toInt}"</ |
echo fmt"– in decimal: {x.toInt}"</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 4,074: | Line 4,074: | ||
=={{header|OCaml}}== |
=={{header|OCaml}}== |
||
< |
<syntaxhighlight lang=ocaml>type btdigit = Pos | Zero | Neg |
||
type btern = btdigit list |
type btern = btdigit list |
||
Line 4,125: | Line 4,125: | ||
let _ = |
let _ = |
||
Printf.printf "a = %d\nb = %d\nc = %d\na * (b - c) = %s = %d\n" |
Printf.printf "a = %d\nb = %d\nc = %d\na * (b - c) = %s = %d\n" |
||
(to_int a) (to_int b) (to_int c) (to_string d) (to_int d);</ |
(to_int a) (to_int b) (to_int c) (to_string d) (to_int d);</syntaxhighlight> |
||
Output: |
Output: |
||
<pre>a = 523 |
<pre>a = 523 |
||
Line 4,133: | Line 4,133: | ||
=={{header|Perl}}== |
=={{header|Perl}}== |
||
< |
<syntaxhighlight lang=perl>use strict; |
||
use warnings; |
use warnings; |
||
Line 4,207: | Line 4,207: | ||
printf " c: %14s %10d\n", $c, from_bt( $c ); |
printf " c: %14s %10d\n", $c, from_bt( $c ); |
||
printf "a*(b-c): %14s %10d\n", $d, from_bt( $d ); |
printf "a*(b-c): %14s %10d\n", $d, from_bt( $d ); |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> a: +-0++0+ 523 |
<pre> a: +-0++0+ 523 |
||
Line 4,218: | Line 4,218: | ||
Using strings to represent balanced ternary. Note that as implemented dec2bt and bt2dec are limited to Phix integers (~+/-1,000,000,000), |
Using strings to represent balanced ternary. Note that as implemented dec2bt and bt2dec are limited to Phix integers (~+/-1,000,000,000), |
||
but it would probably be pretty trivial (albeit quite a bit slower) to replace them with (say) ba2bt and bt2ba which use/yield bigatoms. |
but it would probably be pretty trivial (albeit quite a bit slower) to replace them with (say) ba2bt and bt2ba which use/yield bigatoms. |
||
<!--< |
<!--<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: #008080;">function</span> <span style="color: #000000;">bt2dec</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">bt</span><span style="color: #0000FF;">)</span> |
<span style="color: #008080;">function</span> <span style="color: #000000;">bt2dec</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">bt</span><span style="color: #0000FF;">)</span> |
||
Line 4,311: | Line 4,311: | ||
<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;">"%7s: %12s %9d\n"</span><span style="color: #0000FF;">,{</span><span style="color: #008000;">"c"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">c</span><span style="color: #0000FF;">,</span><span style="color: #000000;">bt2dec</span><span style="color: #0000FF;">(</span><span style="color: #000000;">c</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;">"%7s: %12s %9d\n"</span><span style="color: #0000FF;">,{</span><span style="color: #008000;">"c"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">c</span><span style="color: #0000FF;">,</span><span style="color: #000000;">bt2dec</span><span style="color: #0000FF;">(</span><span style="color: #000000;">c</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;">"%7s: %12s %9d\n"</span><span style="color: #0000FF;">,{</span><span style="color: #008000;">"a*(b-c)"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">res</span><span style="color: #0000FF;">,</span><span style="color: #000000;">bt2dec</span><span style="color: #0000FF;">(</span><span style="color: #000000;">res</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;">"%7s: %12s %9d\n"</span><span style="color: #0000FF;">,{</span><span style="color: #008000;">"a*(b-c)"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">res</span><span style="color: #0000FF;">,</span><span style="color: #000000;">bt2dec</span><span style="color: #0000FF;">(</span><span style="color: #000000;">res</span><span style="color: #0000FF;">)})</span> |
||
<!--</ |
<!--</syntaxhighlight>--> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 4,323: | Line 4,323: | ||
show it manages a 5000+digit multiplication and subtraction in about 0.2s, which I say is "reasonable", given that I didn't try very hard, |
show it manages a 5000+digit multiplication and subtraction in about 0.2s, which I say is "reasonable", given that I didn't try very hard, |
||
as evidenced by that daft addition lookup table! |
as evidenced by that daft addition lookup table! |
||
<!--< |
<!--<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;">atom</span> <span style="color: #000000;">t0</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">time</span><span style="color: #0000FF;">()</span> |
<span style="color: #004080;">atom</span> <span style="color: #000000;">t0</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">time</span><span style="color: #0000FF;">()</span> |
||
Line 4,341: | Line 4,341: | ||
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span> |
<span style="color: #008080;">end</span> <span style="color: #008080;">while</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;">"It took %d subtractions to reach 0. (%3.2fs)\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">count</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;">"It took %d subtractions to reach 0. (%3.2fs)\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">count</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> |
||
<!--</ |
<!--</syntaxhighlight>--> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 4,349: | Line 4,349: | ||
=={{header|PicoLisp}}== |
=={{header|PicoLisp}}== |
||
< |
<syntaxhighlight lang=PicoLisp>(seed (in "/dev/urandom" (rd 8))) |
||
(setq *G '((0 -1) (1 -1) (-1 0) (0 0) (1 0) (-1 1) (0 1))) |
(setq *G '((0 -1) (1 -1) (-1 0) (0 0) (1 0) (-1 1) (0 1))) |
||
Line 4,470: | Line 4,470: | ||
(println 'R (trih R) R) ) |
(println 'R (trih R) R) ) |
||
(bye)</ |
(bye)</syntaxhighlight> |
||
=={{header|Prolog}}== |
=={{header|Prolog}}== |
||
Line 4,477: | Line 4,477: | ||
'''The conversion.'''<br> |
'''The conversion.'''<br> |
||
Library '''clpfd''' is used so that '''bt_convert''' works in both ways Decimal => Ternary and Ternary ==> Decimal. |
Library '''clpfd''' is used so that '''bt_convert''' works in both ways Decimal => Ternary and Ternary ==> Decimal. |
||
< |
<syntaxhighlight lang=Prolog>:- module('bt_convert.pl', [bt_convert/2, |
||
op(950, xfx, btconv), |
op(950, xfx, btconv), |
||
btconv/2]). |
btconv/2]). |
||
Line 4,544: | Line 4,544: | ||
R1 #= R - 3 * C1, % C1 #= 1, |
R1 #= R - 3 * C1, % C1 #= 1, |
||
convert(N1, C1, [R1 | LC], LF). |
convert(N1, C1, [R1 | LC], LF). |
||
</ |
</syntaxhighlight><br> |
||
'''The addition.''' <br> |
'''The addition.''' <br> |
||
The same predicate is used for addition and substraction. |
The same predicate is used for addition and substraction. |
||
< |
<syntaxhighlight lang=Prolog>:- module('bt_add.pl', [bt_add/3, |
||
bt_add1/3, |
bt_add1/3, |
||
op(900, xfx, btplus), |
op(900, xfx, btplus), |
||
Line 4,670: | Line 4,670: | ||
strip_nombre(L) --> |
strip_nombre(L) --> |
||
L. |
L. |
||
</syntaxhighlight> |
|||
</lang> |
|||
'''The multiplication.''' <br> |
'''The multiplication.''' <br> |
||
We give a predicate '''euclide(?A, +B, ?Q, ?R)''' which computes both the multiplication and the division, but it is very inefficient.<br> |
We give a predicate '''euclide(?A, +B, ?Q, ?R)''' which computes both the multiplication and the division, but it is very inefficient.<br> |
||
The predicates '''multiplication(+B, +Q, -A)''' and '''division(+A, +B, -Q, -R)''' are much more efficient. |
The predicates '''multiplication(+B, +Q, -A)''' and '''division(+A, +B, -Q, -R)''' are much more efficient. |
||
< |
<syntaxhighlight lang=Prolog>:- module('bt_mult.pl', [op(850, xfx, btmult), |
||
btmult/2, |
btmult/2, |
||
multiplication/3 |
multiplication/3 |
||
Line 4,845: | Line 4,845: | ||
; mult_(B, Q1, A1, R, Resultat, Ajout)) . |
; mult_(B, Q1, A1, R, Resultat, Ajout)) . |
||
</syntaxhighlight> |
|||
</lang> |
|||
Example of output : |
Example of output : |
||
<pre> ?- A btconv "+-0++0+". |
<pre> ?- A btconv "+-0++0+". |
||
Line 4,864: | Line 4,864: | ||
=={{header|Python}}== |
=={{header|Python}}== |
||
{{trans|Common Lisp}} |
{{trans|Common Lisp}} |
||
< |
<syntaxhighlight lang=python>class BalancedTernary: |
||
# Represented as a list of 0, 1 or -1s, with least significant digit first. |
# Represented as a list of 0, 1 or -1s, with least significant digit first. |
||
Line 4,958: | Line 4,958: | ||
print "a * (b - c):", r.to_int(), r |
print "a * (b - c):", r.to_int(), r |
||
main()</ |
main()</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>a: 523 +-0++0+ |
<pre>a: 523 +-0++0+ |
||
Line 4,966: | Line 4,966: | ||
=={{header|Racket}}== |
=={{header|Racket}}== |
||
< |
<syntaxhighlight lang=racket>#lang racket |
||
;; Represent a balanced-ternary number as a list of 0's, 1's and -1's. |
;; Represent a balanced-ternary number as a list of 0's, 1's and -1's. |
||
Line 5,041: | Line 5,041: | ||
[description (list 'a 'b 'c "a×(b−c)")]) |
[description (list 'a 'b 'c "a×(b−c)")]) |
||
(printf "~a = ~a or ~a\n" description (bt->integer bt) (bt->string bt)))) |
(printf "~a = ~a or ~a\n" description (bt->integer bt) (bt->string bt)))) |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{output}} |
{{output}} |
||
Line 5,054: | Line 5,054: | ||
(formerly Perl 6) |
(formerly Perl 6) |
||
{{Works with|rakudo|2017.01}} |
{{Works with|rakudo|2017.01}} |
||
<lang |
<syntaxhighlight lang=raku lines>class BT { |
||
has @.coeff; |
has @.coeff; |
||
Line 5,116: | Line 5,116: | ||
say 'b == ', $b.Int; |
say 'b == ', $b.Int; |
||
say 'c == ', $c.Int; |
say 'c == ', $c.Int; |
||
say "a × (b − c) == ", ~$x, ' == ', $x.Int;</ |
say "a × (b − c) == ", ~$x, ' == ', $x.Int;</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>a == 523 |
<pre>a == 523 |
||
Line 5,125: | Line 5,125: | ||
=={{header|REXX}}== |
=={{header|REXX}}== |
||
The REXX program could be optimized by using (procedure) with '''expose''' and having the <big>'''$.'''</big> and <big>'''@.'''</big> variables set only once. |
The REXX program could be optimized by using (procedure) with '''expose''' and having the <big>'''$.'''</big> and <big>'''@.'''</big> variables set only once. |
||
< |
<syntaxhighlight lang=rexx>/*REXX program converts decimal ◄───► balanced ternary; it also performs arithmetic. */ |
||
numeric digits 10000 /*be able to handle gihugic numbers. */ |
numeric digits 10000 /*be able to handle gihugic numbers. */ |
||
Ao = '+-0++0+' ; Abt = Ao /* [↓] 2 literals used by subroutine*/ |
Ao = '+-0++0+' ; Abt = Ao /* [↓] 2 literals used by subroutine*/ |
||
Line 5,175: | Line 5,175: | ||
btNorm: _= strip(arg(1), 'L', 0); if _=='' then _=0; return _ /*normalize the number.*/ |
btNorm: _= strip(arg(1), 'L', 0); if _=='' then _=0; return _ /*normalize the number.*/ |
||
btSub: return btAdd( arg(1), btNeg( arg(2) ) ) /*subtract two BT args.*/ |
btSub: return btAdd( arg(1), btNeg( arg(2) ) ) /*subtract two BT args.*/ |
||
btShow: say center( arg(1), 9) right( arg(2), 20) @@ right( bt2d(arg(2)), 9) @; return</ |
btShow: say center( arg(1), 9) right( arg(2), 20) @@ right( bt2d(arg(2)), 9) @; return</syntaxhighlight> |
||
{{out|output|text= when using the default input:}} |
{{out|output|text= when using the default input:}} |
||
<pre> |
<pre> |
||
Line 5,186: | Line 5,186: | ||
=={{header|Ruby}}== |
=={{header|Ruby}}== |
||
< |
<syntaxhighlight lang=ruby>class BalancedTernary |
||
include Comparable |
include Comparable |
||
def initialize(str = "") |
def initialize(str = "") |
||
Line 5,308: | Line 5,308: | ||
val = eval(exp) |
val = eval(exp) |
||
puts "%8s :%13s,%8d" % [exp, val, val.to_i] |
puts "%8s :%13s,%8d" % [exp, val, val.to_i] |
||
end</ |
end</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 5,319: | Line 5,319: | ||
=={{header|Rust}}== |
=={{header|Rust}}== |
||
< |
<syntaxhighlight lang=rust>use std::{ |
||
cmp::min, |
cmp::min, |
||
convert::{TryFrom, TryInto}, |
convert::{TryFrom, TryInto}, |
||
Line 5,576: | Line 5,576: | ||
} |
} |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output |
Output |
||
Line 5,588: | Line 5,588: | ||
=={{header|Scala}}== |
=={{header|Scala}}== |
||
This implementation represents ternaries as a reversed list of bits. Also, there are plenty of implicit convertors |
This implementation represents ternaries as a reversed list of bits. Also, there are plenty of implicit convertors |
||
< |
<syntaxhighlight lang=scala> |
||
object TernaryBit { |
object TernaryBit { |
||
val P = TernaryBit(+1) |
val P = TernaryBit(+1) |
||
Line 5,675: | Line 5,675: | ||
implicit def intToTernary(i: Int): Ternary = valueOf(i) |
implicit def intToTernary(i: Int): Ternary = valueOf(i) |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
Then these classes can be used in the following way: |
Then these classes can be used in the following way: |
||
< |
<syntaxhighlight lang=scala> |
||
object Main { |
object Main { |
||
Line 5,693: | Line 5,693: | ||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 5,703: | Line 5,703: | ||
Besides, we can easily check, that the code works for any input. This can be achieved with ScalaCheck: |
Besides, we can easily check, that the code works for any input. This can be achieved with ScalaCheck: |
||
< |
<syntaxhighlight lang=scala> |
||
object TernarySpecification extends Properties("Ternary") { |
object TernarySpecification extends Properties("Ternary") { |
||
Line 5,719: | Line 5,719: | ||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 5,729: | Line 5,729: | ||
=={{header|Tcl}}== |
=={{header|Tcl}}== |
||
This directly uses the printable representation of the balanced ternary numbers, as Tcl's string operations are reasonably efficient. |
This directly uses the printable representation of the balanced ternary numbers, as Tcl's string operations are reasonably efficient. |
||
< |
<syntaxhighlight lang=tcl>package require Tcl 8.5 |
||
proc bt-int b { |
proc bt-int b { |
||
Line 5,785: | Line 5,785: | ||
- { return [bt-sub $sub $b] } |
- { return [bt-sub $sub $b] } |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
Demonstration code: |
Demonstration code: |
||
< |
<syntaxhighlight lang=tcl>for {set i 0} {$i<=10} {incr i} {puts "$i = [int-bt $i]"} |
||
puts "'+-+'+'+--' = [bt-add +-+ +--] = [bt-int [bt-add +-+ +--]]" |
puts "'+-+'+'+--' = [bt-add +-+ +--] = [bt-int [bt-add +-+ +--]]" |
||
puts "'++'*'++' = [bt-mul ++ ++] = [bt-int [bt-mul ++ ++]]" |
puts "'++'*'++' = [bt-mul ++ ++] = [bt-int [bt-mul ++ ++]]" |
||
Line 5,796: | Line 5,796: | ||
puts "a = [bt-int $a], b = [bt-int $b], c = [bt-int $c]" |
puts "a = [bt-int $a], b = [bt-int $b], c = [bt-int $c]" |
||
set abc [bt-mul $a [bt-sub $b $c]] |
set abc [bt-mul $a [bt-sub $b $c]] |
||
puts "a*(b-c) = $abc (== [bt-int $abc])"</ |
puts "a*(b-c) = $abc (== [bt-int $abc])"</syntaxhighlight> |
||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 5,818: | Line 5,818: | ||
=={{header|Visual Basic .NET}}== |
=={{header|Visual Basic .NET}}== |
||
{{trans|C#}} |
{{trans|C#}} |
||
< |
<syntaxhighlight lang=vbnet>Imports System.Text |
||
Module Module1 |
Module Module1 |
||
Line 6,005: | Line 6,005: | ||
End Class |
End Class |
||
End Module</ |
End Module</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>a: +-0++0+ = 523 |
<pre>a: +-0++0+ = 523 |
||
Line 6,016: | Line 6,016: | ||
{{libheader|Wren-big}} |
{{libheader|Wren-big}} |
||
{{libheader|Wren-trait}} |
{{libheader|Wren-trait}} |
||
< |
<syntaxhighlight lang=ecmascript>import "/big" for BigInt |
||
import "/trait" for Comparable |
import "/trait" for Comparable |
||
Line 6,140: | Line 6,140: | ||
var bResult = a * (b - c) |
var bResult = a * (b - c) |
||
var iResult = bResult.toBigInt |
var iResult = bResult.toBigInt |
||
System.print("a * (b - c) = %(bResult) = %(iResult)")</ |
System.print("a * (b - c) = %(bResult) = %(iResult)")</syntaxhighlight> |
||
{{out}} |
{{out}} |