Negative base numbers: Difference between revisions
added RPL
(Added Quackery.) |
(added RPL) |
||
(4 intermediate revisions by 4 users not shown) | |||
Line 19:
{{trans|Python}}
<
I n == 0
R ‘0’
Line 60:
print(‘Converted back to decimal’)
E
print(‘Error converting back to decimal’)</
{{out}}
Line 76:
=={{header|Action!}}==
<
INT FUNC MyMod(INT a,b)
Line 156:
Test(15,-10)
Test(-568,-63)
RETURN</
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Negative_base_numbers.png Screenshot from Atari 8-bit computer]
Line 176:
{{trans|Modula}}
<
package Negative_Base_Numbers is
Line 310:
driver (15, -10);
driver (36_058, -62);
end Main;</
{{out}}
<pre>
Line 327:
=={{header|ALGOL 68}}==
{{works with|ALGOL 68G|Any - tested with release 2.8.3.win32}}
<
# Note - no checks for valid bases or digits bases -2 .. -63 are handled #
# A-Z represent the digits 11 .. 35, a-z represent the digits 36 .. 61 #
Line 395:
# The defining document for ALGOL 68 spells the name "Algol 68" on the cover, though inside it is "ALGOL 68" #
# at the risk of "judging a language by it's cover", we use "Algol 68" as the name here... #
test n base( - LONG 36492107981104, -63, "Algol 68" )</
{{out}}
<pre>
Line 410:
=={{header|C}}==
{{trans|modula-2}}
<
const char DIGITS[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
Line 512:
return 0;
}</
{{out}}
<pre> 10 encoded in base -2 = 11110
Line 528:
=={{header|C sharp|C#}}==
{{trans|Java}}
<
using System.Collections.Generic;
using System.Linq;
Line 591:
}
}
}</
{{out}}
<pre> 10 encoded in base -2 = 11110
Line 607:
=={{header|C++}}==
{{trans|C#}}
<
#include <iostream>
#include <tuple>
Line 681:
return 0;
}</
{{out}}
<pre> 10 encoded in base -2 = 11110
Line 696:
=={{header|D}}==
<
immutable DIGITS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
Line 757:
}
return total;
}</
{{out}}
Line 774:
=={{header|F_Sharp|F#}}==
===The Functions===
<
//I provide 2 fuctions D2N takes a radix and an integer returning a sequence of integers
// N2D takse a radix and a sequence of integers returning an integer
Line 783:
|_->Some(g-(α+1)*n,α+1)) g|>Seq.rev
let N2D n g=fst(Seq.foldBack(fun g (Σ,α)->(Σ+α*g,n*α)) g (0,1))
</syntaxhighlight>
===The Task===
<
let t0,t146,t10,t15=D2N -13 0,D2N -3 146,D2N -2 10,D2N -10 15
Seq.iter(fun n->Seq.iter(printf "%d ")n; printfn "")[t0;t146;t10;t15]
Seq.iter(printfn "%d ")[N2D -13 t0;N2D -3 t146;N2D -2 t10;N2D -10 t15]
</syntaxhighlight>
{{out}}
<pre>
Line 804:
=={{header|Factor}}==
{{works with|Factor|0.99 2020-03-02}}
<
math.extras math.functions math.parser sequences ;
Line 820:
"%d_10 is %s_%d\n%s_%d is %d_10\n\n" printf ;
10 -2 146 -3 15 -10 [ .round-trip ] 2tri@</
{{out}}
<pre>
Line 832:
195_-10 is 15_10
</pre>
=={{header|FreeBASIC}}==
{{trans|VBA}}
<syntaxhighlight lang="vb">#define DIGITS "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
Dim cadena(63) As String
Function mod2(a As Long, b As Integer) As Long
Return a - (a \ b) * b
End Function
Function StrReverse(Byval text As String) As String
Dim As String text2 = text
Dim As Integer x, lt = Len(text)
For x = 0 To lt Shr 1 - 1
Swap text2[x], text2[lt - x - 1]
Next x
Return text2
End Function
Function EncodeNegativeBase(Byval n As Long, base_ As Integer) As String
Dim As Long Puntero, idx, rem_
Dim result As String
If base_ > -1 Or base_ < -62 Then
Return result
Else
If n = 0 Then
Return "0"
Else
Puntero = 0
Do While n <> 0
rem_ = mod2(n, base_)
n \= base_
If rem_ < 0 Then
n += 1
rem_ = rem_ - base_
End If
result &= Mid(DIGITS, rem_ + 1, 1)
Loop
End If
End If
Return StrReverse(result)
End Function
Function DecodeNegativeBase(ns As String, base_ As Integer) As Long
Dim As Long total, bb
Dim As Integer i, j
If base_ < -62 Or base_ > -1 Then Return 0
If Mid(ns, 1, 1) = "0" Or (Mid(ns, 1, 1) = "0" And Mid(ns, 2, 1) = "0") Then Return 0
i = Len(ns)
total = 0
bb = 1
Do While i >= 1
j = Instr(DIGITS, Mid(ns, i, 1)) - 1
total += j * bb
bb *= base_
i -= 1
Loop
Return total
End Function
Sub Driver(n As Long, b As Integer)
Dim As String ns = EncodeNegativeBase(n, b)
Print Str(n); " encoded in base "; b; " = "; ns
Dim As Long p = DecodeNegativeBase(ns, b)
Print ns; " decoded in base "; b; " ="; p
Print
End Sub
Driver 10, -2
Driver 146, -3
Driver 15, -10
Driver 118492, -62
Sleep</syntaxhighlight>
{{out}}
<pre>Same as VBA entry.</pre>
=={{header|Go}}==
{{trans|Kotlin}}
<
import (
Line 908 ⟶ 988:
fmt.Printf("%13s decoded in base %-3d = %d\n\n", ns, b, n)
}
}</
{{out}}
Line 929 ⟶ 1,009:
=={{header|Haskell}}==
<
import Numeric (showIntAtBase)
Line 961 ⟶ 1,041:
printAtBase (-10) 15
printAtBase (-16) 107
printAtBase (-36) 41371458</
{{out}}
Line 1,065 ⟶ 1,145:
{{trans|Kotlin}}
{{works with|Java|9}}
<
import java.util.Map;
import java.util.Objects;
Line 1,117 ⟶ 1,197:
}
}
}</
{{out}}
<pre> 10 encoded in base -2 = 11110
Line 1,134 ⟶ 1,214:
{{works with|jq|1.5}}
If your jq does not have `trunc/0` then use this:
<
<
if ($b >= 0) then error("negbase requires negative base")
elif . == 0 then "0"
Line 1,168 ⟶ 1,248:
;
test</
{{out}}
<
[true,true]
[true,true]</
=={{header|Julia}}==
{{works with|Julia|0.6}}
<
function negbase(n, b)
if n == 0 return "0" end
Line 1,203 ⟶ 1,283:
decoded = invnegbase(encoded, base)
println("\nencode $num in base $base:\n-> expected: $rst\n-> resulted: $encoded\n-> decoded: $decoded")
end</
{{out}}
Line 1,222 ⟶ 1,302:
=={{header|Kotlin}}==
<
const val DIGITS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
Line 1,264 ⟶ 1,344:
System.out.printf("%12s decoded in base %-3d = %d\n\n", ns, p.second, n)
}
}</
{{out}}
Line 1,282 ⟶ 1,362:
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<
out={},
rem,n=number,b=base
Line 1,302 ⟶ 1,382:
Print[EncodeNegBase[10,-2],"=",DecodeBase[EncodeNegBase[10,-2],-2]];
Print[EncodeNegBase[146,-3],"=",DecodeBase[EncodeNegBase[146,-3],-3]];
Print[EncodeNegBase[15,-10],"=",DecodeBase[EncodeNegBase[15,-10],-10]];</
<pre>{1,1,1,1,0}=10
{2,1,1,0,2}=146
{1,9,5}=15</pre>
Extra Credit:
<
DecodeBase[ToCharacterCode[$Version], -(2^16 - 1)](*2-byte encoding*)</
<pre>805433247971592164648901981307140864173502418954511864100981464890629926293823767730118860531000284192172723837
1402171866107096793294662824351970913227448502019658754262020315290937172496459102043149157175108006798078612200544768242812932737034448604720533372980987964929785521161173764118702296122915325508945150191589743829011670147956776269027485433441427722106</pre>
=={{header|Modula-2}}==
<
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;
Line 1,423 ⟶ 1,503:
ReadChar
END NegativeBase.</
{{out}}
<pre> 10 encoded in base -2 = 11110
Line 1,438 ⟶ 1,518:
=={{header|Nim}}==
<
const
Line 1,488 ⟶ 1,568:
const Nim = Number(base: -62, value: "Nim")
echo "The string “Nim” is decoded from base -62 to base 10 as: ", Nim.toInt</
{{out}}
Line 1,504 ⟶ 1,584:
=={{header|ooRexx}}==
{{trans|REXX}}
<
* Adapt for ooRexx (use of now invalid variable names)
* and make it work for base -63 (Algol example)
Line 1,562 ⟶ 1,642:
Else
r='ok'
Return r</
{{out}}
<pre> 10 converted to base -2 ----> 11110 ok
Line 1,574 ⟶ 1,654:
=={{header|Perl}}==
{{libheader|ntheory}}
<
use feature 'say';
use POSIX qw(floor);
Line 1,610 ⟶ 1,690:
say '11110 from base -2: ', decode("11110", -2);
say '21102 from base -3: ', decode("21102", -3);
say ' 195 from base -10: ', decode("195", -10);</
{{out}}
<pre>
Line 1,622 ⟶ 1,702:
=={{header|Phix}}==
<!--<
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">digits</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"0123456789"</span><span style="color: #0000FF;">&</span>
Line 1,672 ⟶ 1,752:
<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;">"%9d <--------------'%s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">nn</span><span style="color: #0000FF;">,</span><span style="color: #000000;">ok</span><span style="color: #0000FF;">})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</
{{out}}
<pre>
Line 1,687 ⟶ 1,767:
=={{header|Python}}==
<
from __future__ import print_function
Line 1,729 ⟶ 1,809:
print (result)
if DecodeNegBase(result, -10) == 15: print ("Converted back to decimal")
else: print ("Error converting back to decimal")</
{{out}}
Line 1,744 ⟶ 1,824:
=={{header|Quackery}}==
<
over iff
[
else drop ] is /mod+ ( n n --> n n )
Line 1,781 ⟶ 1,860:
15 dup echo say " -> "
-10 ->negabase$ dup echo$ say " -> "
-10 negabase$-> echo cr</
{{out}}
Line 1,792 ⟶ 1,871:
=={{header|Racket}}==
<
(define all-digits (string->list "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-"))
Line 1,850 ⟶ 1,929:
(define-values (->hexadecimal hexadecimal->) (negabase-convertors 16))
(check-equal? (->hexadecimal 31) "1F"))</
{{out}}
Line 1,871 ⟶ 1,950:
Note that the parse-base routine will handle 'illegal' negative negative-base values without blowing up.
<syntaxhighlight lang="raku"
my $result;
while $value {
Line 1,922 ⟶ 2,001:
# 'Illegal' negative-base value
say q| '-21'.&parse-base(-10) = |, '-21'.&parse-base(-10);</
{{out}}
<pre> 4.&base( -4) = 130 : '130'.&parse-base( -4) = 4
Line 1,946 ⟶ 2,025:
Doing pretty much the same tests as the explicit version.
<syntaxhighlight lang="raku"
for < 4 -4 0 -7 10 -2 146 -3 15 -10 -19 -10 107 -16
Line 1,954 ⟶ 2,033:
printf "%21s.&to-base\(%5d\) = %-11s : %13s.&from-base\(%5d\) = %s\n",
+$v, $r, $nbase, "'$nbase'", $r, $nbase.&from-base($r);
}</
{{out}}
<pre> 4.&to-base( -4) = 130 : '130'.&from-base( -4) = 4
Line 1,973 ⟶ 2,052:
<br>negative base back to the original number in base ten (and issues an error message if not correct).
===handles up to base -10===
<
@=' converted to base '; numeric digits 300 /*be able to handle ginormous numbers. */
n= 10; b= -2; q= nBase(n, b); say right(n, 20) @ right(b, 3) '────►' q ok()
Line 2,001 ⟶ 2,080:
p= p + 1 /*bump the power by 1. */
end /*j*/ /* [↓] process the number "bottom-up".*/
return $</
{{out|output|text= when using the default inputs:}}
<pre>
Line 2,015 ⟶ 2,094:
<br>because the symbols (glyphs or numerals) used herein may not be in the same exact order. The symbols represented
<br>in this REXX program should be able to represent almost any programming language used on Rosetta Code.
<
@=' converted to base '; numeric digits 300 /*be able to handle ginormous numbers. */
n= 10; b= -2; q= nBase(n, b); say right(n, 20) @ right(b,3) '────►' q ok()
Line 2,047 ⟶ 2,126:
$= $ + v * r**p; p= p + 1 /*add it to $ (result); bump power by 1*/
end /*j*/ /* [↑] process the number "bottom-up".*/
return $</
{{out|output|text= when using the default inputs:}}
<pre>
Line 2,059 ⟶ 2,138:
=={{header|Ring}}==
<
# Project : Negative base numbers
Line 2,099 ⟶ 2,178:
next
return svect
</syntaxhighlight>
{{out}}
<pre>
Line 2,109 ⟶ 2,188:
195 decoded in base -10 = 15
</pre>
=={{header|RPL}}==
{{trans||Python}}
« → base
« '''IF''' DUP NOT '''THEN''' →STR
'''ELSE'''
""
'''WHILE''' OVER '''REPEAT'''
base MOD LASTARG / FLOOR
'''IF''' OVER 0 < '''THEN'''
1 + SWAP
base -
'''ELSE''' SWAP '''END'''
ROT +
'''END''' SWAP DROP
» » '<span style="color:blue">→NEGB</span>' STO
« → nstr base
« 0
1 nstr SIZE '''FOR''' j
base *
nstr j DUP SUB STR→ +
'''NEXT'''
» » '<span style="color:blue">NEGB→</span>' STO
« { 10 -2 146 -3 15 -10 } → cases
« 1 cases SIZE '''FOR''' j
cases j GET cases j 1 + GET <span style="color:blue">→NEGB</span>
DUP cases j 1 + GET <span style="color:blue">NEGB→</span>
2 '''STEP'''
cases SIZE →LIST
» » '<span style="color:blue">TASK</span>' STO
{{out}}
<pre>
1: { "11110" 10 "21102" 146 "195" 15 }
</pre>
=={{header|Ruby}}==
{{trans|Julia}}
{{works with|Ruby|2.3}}
<
# convert a base 10 integer into a negative base value (as a string)
Line 2,150 ⟶ 2,265:
puts("Enc: %8i base %-3i = %5s base %-3i Dec: %5s base %-3i = %8i base %-3i" %
[decimal, 10, encoded, base, encoded, base, decoded, 10])
end</
{{out}}
<pre>Enc: 10 base 10 = 11110 base -2 Dec: 11110 base -2 = 10 base 10
Line 2,160 ⟶ 2,275:
=={{header|Rust}}==
{{trans|Go}}
<
Line 2,208 ⟶ 2,323:
}
return out.chars().rev().collect();
}</
=={{header|Scala}}==
<
val digits = ('0' to '9') ++ ('a' to 'z') ++ ('A' to 'Z')
Line 2,234 ⟶ 2,349:
}._1
}
}</
<
println(s"$n in base -$b = ${NegativeBase.intToStr(n, b)}")
println(s"$s from base -$b = ${NegativeBase.strToInt(s, b)}")
Line 2,244 ⟶ 2,359:
testConversion(3)(146, "21102")
testConversion(10)(15, "195")
testConversion(62)(795099356, "Scala")</
{{out}}
Line 2,258 ⟶ 2,373:
=={{header|Seed7}}==
<
const string: DIGITS is "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
Line 2,328 ⟶ 2,443:
doCheck(15, -10);
doCheck(404355637, -62);
end func;</
{{out}}
Line 2,345 ⟶ 2,460:
{{trans|Raku}}
{{trans|Python}}
<
var out = []
var r = 0
Line 2,381 ⟶ 2,496:
# Extra
say ("25334424 in base -31: ", EncodeNegBase(25334424, -31))
say ("sidef from base -31: ", DecodeNegBase("sidef", -31))</
{{out}}
<pre>
Line 2,398 ⟶ 2,513:
=={{header|VBA}}==
{{trans|Modula-2}}
<
Dim Str(63) As String
Private Function mod2(a As Long, b As Integer) As Long
Line 2,463 ⟶ 2,578:
Driver 15, -10
Driver 118492, -62
End Sub</
{{out}}
<pre>10 encoded in base -2 = 11110
Line 2,480 ⟶ 2,595:
{{trans|Kotlin}}
{{libheader|Wren-fmt}}
<
var digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
Line 2,518 ⟶ 2,633:
var n = decodeNegBase.call(ns, p[1])
Fmt.print("$8s decoded in base $-3d = $d\n", ns, p[1], n)
}</
{{out}}
Line 2,536 ⟶ 2,651:
=={{header|zkl}}==
<
var [const] cs=[0..9].chain(["a".."z"]).pump(String); //"0123456789abcd..z"
_assert_(-37 < radix < -1,"invalid radix");
Line 2,550 ⟶ 2,665:
fcn toInt(str,radix){ // the toInt(radix) method radix is 2..36
str.reduce('wrap(s,d,rdx){ s*radix + d.toInt(rdx); },0,radix.abs());
}</
<
results:=ns.pump(List,Void.Xplode,toNBase);
foreach nb,r in (ns.zip(results)){
_,b:=nb;
println("%10d.base(%3d) = \"%s\" --> %d".fmt(nb.xplode(),r,toInt(r,b)));
}</
{{out}}
<pre>
|