13
3
Balanced bases:
Balanced bases are essentially the same as normal bases, except that digits can be positive or negative, while in normal bases digits can only be positive.
From here on, balanced bases of base b
may be represented as balb
- so balanced base 4 = bal4
.
In this challenge's definition, the range of digits in a balanced base of base b
is from -(k - 1)
to b - k
, where
k = ceil(b/2)
Examples of the range of digits in various balanced bases:
bal10:
k = ceil(10/2) = 5
range = -(5 - 1) to 10 - 5 = -4 to 5
= -4, -3, -2, -1, 0, 1, 2, 3, 4, 5
bal5:
k = ceil(5/2) = 3
range = -(3 - 1) to 5 - 3 = -2 to 2
= -2, -1, 0, 1, 2
Representations of numbers in balanced bases is basically the same as normal bases. For example, the representation of the number 27
(base 10) to bal4
(balanced base 4) is 2 -1 -1
, because
2 -1 -1 (bal4)
= 2 * 4^2 + -1 * 4 + -1 * 1
= 32 + (-4) + (-1)
= 27 (base 10)
Task:
Your task is, given three inputs:
- the number to be converted (
n
)- this input can be flexible, see "I/O Flexibility"
- the base which
n
is currently in (b
) - the base which
n
is to be converted to (c
)
Where 2 < b, c < 1,000
.
Return the number in balanced base c
representation of n
. The output can also be flexible.
The program/function must determine the length of n
from the input itself.
I/O Flexibility:
Your input n
and output can be represented in these ways:
- your language's definition of an array
- a string, with any character as a separator (e.g. spaces, commas)
Examples:
Note that these use a Python array as n
and the output. You may use whatever fits your language, as long as it fits within "I/O Flexibility"'s definition.
[2, -1, -1] 4 7 = [1, -3, -1]
[1, 2, 3, 4] 9 5 = [1, 2, 2, -1, 2]
[10, -9, 10] 20 5 = [1, 1, 1, -2, 1, 0]
This is code-golf, so shortest code in bytes wins!
In your first answer, 4 is not a legal bal7 digit; I believe the answer should be [1, -3, -1]. And I get different answers for the second test case ([1,2,2,-1,2]) and third test case ([1,1,0,-2,1,0]) as well...? – Greg Martin – 2017-01-11T05:42:53.137
@GregMartin Ah, whoops - I calculated those by hand, so there was bound to be some problems. Thanks for noticing! Can you double-check your solutions, just in case? – clismique – 2017-01-11T05:44:49.370
@GregMartin @Qwerp-Derp Third test case is
[1,1,1,-2,1,0]
– ngenisis – 2017-01-11T06:36:18.387