How to resolve the algorithm Negative base numbers step by step in the jq programming language

Published on 12 May 2024 09:40 PM
#Jq

How to resolve the algorithm Negative base numbers step by step in the jq programming language

Table of Contents

Problem Statement

Negative base numbers are an alternate way to encode numbers without the need for a minus sign. Various negative bases may be used including negadecimal (base -10), negabinary (-2) and negaternary (-3).[1][2]

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Negative base numbers step by step in the jq programming language

Source code in the jq programming language

def trunc: if . >= 0 then floor else -(-(.)|trunc) end;

def negbase($b):
  if ($b >= 0) then error("negbase requires negative base")
  elif . == 0 then "0"
  else {n: ., ans: ""}
  | until(.n == 0;
         .r = ((.n % $b))
  	 | .n = ((.n / $b) | trunc)
         | if .r < 0 then .n += 1 | .r -= $b else . end
         | .ans = (.r|tostring) + .ans )
  | .ans
  end ;

def sigma(stream): reduce stream as $x (null; .+$x);

def invnegbase($b):
  (explode | reverse | map(. - 48)) as $s
  | sigma( range(0; $s|length) | ($s[.] * pow($b; .)));
 
def testset: {
   "11110": [10, -2],
   "21102": [146, -3],
   "195":   [15, -10]
 };

def test: testset
| to_entries[]
| .value[0] as $n
| .value[1] as $base
| ($n|negbase($base)) as $neg
| ($neg | invnegbase($base)) as $invneg
| [.key == $neg, $n == $invneg]
;

test

[true,true]
[true,true]
[true,true]

  

You may also check:How to resolve the algorithm Integer sequence step by step in the Fish programming language
You may also check:How to resolve the algorithm 100 doors step by step in the TSE SAL programming language
You may also check:How to resolve the algorithm Stream merge step by step in the Phix programming language
You may also check:How to resolve the algorithm Comments step by step in the Peloton programming language
You may also check:How to resolve the algorithm Non-continuous subsequences step by step in the Pop11 programming language