# N numbers closest to zero staying balanced

Objective: Given a positive integer n:

• If n is odd, output the list of n numbers closest to 0 in increasing order
• If n is even, output a Falsey value.

Test cases:

5 -> [-2,-1,0,1,2]
4 -> false (or any Falsey value)
1 -> [0]


## Reference implementation

function update(){
var num = +document.getElementById("yield").value;
if(num){
var out = document.getElementById("output");
if(num % 2 == 1){
// base is balanced
var baseArr = [];
for(var i=0;i<num;i++){
baseArr.push(i-Math.floor(num/2));
}
out.innerHTML = baseArr.join(" ");
} else {
out.innerHTML = "false";
}
} else {
out.innerHTML = "<i>enter input</i>";
}
}

setInterval(update,1);
* {
font-family: "Constantia", "Consolas", monospace;
}

[type="number"] {
width: 10px;
width: 2em;
}

#output {
font-family: "Consolas", monospace;
}
Input: <input type="number" id="yield" value="3"> is <span id="output"><i>enter input</i></span>

• Can the output be a range object rather than a list? – Brad Gilbert b2gills Nov 8 '15 at 20:40
• @BradGilbertb2gills Sorry, a range object is an invalid output. – Conor O'Brien Nov 8 '15 at 20:42
• The empty list is not always falsey. – SuperJedi224 Nov 8 '15 at 21:44
• @SuperJedi224 In which contexts? – Conor O'Brien Nov 8 '15 at 21:45
• I know it's been a while, but can we use [0] as falsey result, even though $n=1$ results in [0] as truthy result as well? – Kevin Cruijssen Aug 27 '20 at 11:12

# Pyth, 10 bytes

*-R/Q2Q%Q2


Try it online.

### How it works

            (implicit) Store the input in Q.
/Q2      Calculate Q/2 (integer division).
-R   Q     Subtract that value (-R) from each element in [0, ..., Q-1] (Q).
*      %Q2  Repeat the resulting array Q%2 times.


## APL, 1615 13 bytes

Thanks to @Dennis for -2 bytes!

⌊(⍳⊢×2|⊢)-÷∘2


This is a monadic train that gives an empty array for even input. Below is the diagram:

┌────┴─────┐
⌊ ┌────────┼─┐
┌─┴─┐      - ∘
⍳ ┌─┼───┐   ┌┴┐
⊢ × ┌─┼─┐ ÷ 2
2 | ⊢


First, ⊢×2|⊢ gives the input times its mod 2; that is, odds will give themselves, and evens give 0. We use ⍳ to create a list of numbers from 1 to that (⍳0 gives the empty array), and then we subtract half the input and floor.

# Mathematica, 3230 24 bytes

OddQ@#&&Range@#-(#+1)/2&


Code-golfing trick: The last argument to And doesn't have to be a boolean.

• You can save a byte by using the Unicode brackets for Floor. – Martin Ender Nov 3 '15 at 22:28
• Also, Range[-a,a=...] seems to work, saving another byte. – Martin Ender Nov 3 '15 at 22:29
• OddQ@#&&Range@#-(#+1)/2& – ngenisis Jan 5 '17 at 1:06

## PowerShell, 50 52 Bytes

param($a)$b=$a/2-.5;(0,((0-$b)..$b-join' '))[($a%2)]


Oof. Pretty verbose answer. Takes input $a, then sets a new variable $b as the "floor" of $a/2. Generates a new number range from (0-$b) to $b, then joins the range with spaces, and has that as the second element of a two-element array (the first element is 0). Then uses $a%2 to index into that array for output.

Alternate version using more "traditional" if/else flow, at 54 bytes:

param($a)$b=$a/2-.5;if($a%2){(0-$b)..$b-join' ';exit}0


Edit - Needed to add some logic to output a falsey value if the input is even

• Save 3 bytes by changing (0-$b) to just -$b. Also, just multiplying by *0 will output a null string (evaluates to false in powershell). (see: codegolf.stackexchange.com/a/63005/45925) – Jonathan Leech-Pepin Nov 5 '15 at 12:59

g n=take(n*mod n 2)[-div n 2..]


Unbalanced is indicated by the empty list. Usage example: g 7 -> [-3,-2,-1,0,1,2,3].

@xnor found 5 bytes. Thanks!

• Is there no way to make the empty list case a condition? Doing g n=[x|x<-[-div n 2..(n+1)/2],odd n] is equally long. – xnor Nov 3 '15 at 21:10
• 34: g n=[1|odd n]>>[-div n 2..div n 2] – xnor Nov 3 '15 at 21:19
• You should edit it in, it's a small change. – xnor Nov 3 '15 at 21:28
• g n=[1|odd n]>>take n[-div n 2..] also saves a char. – xnor Nov 3 '15 at 21:31
• @xnor: you're golfing it down faster than I can edit my posts. – nimi Nov 3 '15 at 21:35

# J, 12 bytes

i:@%~2&!*2&|


This is a monadic verb that returns 0 (falsy) for even numbers. Try it online with J.js.

### Test run

   (i:@%~2&!*2&|) 3
_1 0 1
(i:@%~2&!*2&|) 2
0


### How it works

              Right argument: y
2&|  Take y modulo 2.
2&!      Calculate y C 2 = y(y-1)/2.
*     Multiply the results.
%~         Divide the product by y.
This yields (y-1)*(y%2)/2 = (y-1)/2 (y even) | 0 (y odd).
@           Take the result and...
i:              apply the bilateral index generator z -> (-z ... z).


# JavaScript (ES6), 444342 41 bytes

crossed out 44 is still regular 44 ;(

n=>[...Array(n&1&&n--)].map((x,i)=>i-n/2)


For odd inputs, returns a integer array of length x, centered at 0; for even, returns 0. I think this is as short as it can get. (Saved a couple bytes thanks to @edc65 and @ןnɟuɐɯɹɐןoɯ!)

ES6 alternative: (42 bytes, thanks to @intrepidcoder)

x=>x%2&&[for(y of Array(x--).keys())y-x/2]


Suggestions welcome!

• Using x%2&&[for(y of...] saves a byte. – intrepidcoder Nov 3 '15 at 22:58
• ES6, 43, n=>Array(n&1&&n--).fill().map((x,i)=>i-n/2) if returning an empty array is allowed – edc65 Nov 3 '15 at 23:08
• @intrepidcoder Thanks! I've changed this. – ETHproductions Nov 3 '15 at 23:11
• @edc65 Thanks as well! I've added this into the answer. – ETHproductions Nov 3 '15 at 23:11
• x=>x%2&&[for(y of Array(x--).keys())y-x/2] is 42. – intrepidcoder Nov 4 '15 at 1:28

# Python 2, 34 32 Bytes

Right now I'm not sure if I can output whatever I want if it's not balanced, so currently this just returns an empty list in the case of an unbalance-able base. It's an anonymous lambda function, so give it a name to use it.

lambda k:k%2*range(-k/2+1,-~k/2)

• If you do k%2*, you can avoid the parens. – xnor Nov 3 '15 at 20:50

## Minkolang 0.10, 18 bytes

nd2%?.d2:~r[dN1+].


### Explanation

n          Take input as integer (k)
d2%?.      Duplicate k and stop if it's even
d2:~       Duplicate k, then divide by 2 and negate to get first number
r          Put k on top
[    ].    Loop k times and then stop
dN1+      Duplicate, output as integer, and increment


# DUP, 31 bytes

[a:a;2/b:[b;_[$b;<][$1+]#][0]?]


Try it here.

Anonymous lambda. Usage:

5[a:a;2/b:[b;_[$b;<][$1+]#][0]?]!


# Explanation

[                             ] {lambda}
a:                             {store input to a}
a;2/                         {divmod a by 2}
b:                       {store quotient to b, top of stack is now remainder}
[               ][ ]?  {conditional}
b;_                   {if remainder is 1, get b and negate it}
[    ][   ]#         {while loop}
$b;< {while top of stack is less than b}$1+           {duplicate and increment}
0    {otherwise, leave falsy value}


# Brachylog, 9 bytes

%₂1&~l≠≜o


Try it online!

### Explanation

An interesting (ab)use of Brachylog's backtracking algorithm:

%₂1        First, assert that the input mod 2 is 1 (if not, the predicate fails)
&       Then, the input
~l      is the length of some list
≠     in which all elements are different
≜   Generate a list that matches those conditions
Brachylog will try to fill the array with integers, starting from 0 and
increasing in absolute value; since they all have to be different, the result
will be of the form [0, 1, -1, 2, -2, ...]
o  Sort ascending


# CJam, 13 12 bytes

{_2md@,@f-*}


This is an anonymous function that pops an integer from the stack and pushes a digit array (odd base) or an empty array (even base) in return. Try it online in the CJam interpreter.

### How it works

_          e# Copy the input (N).
2md       e# Push N/2 and N%2.
@      e# Rotate N on top of the stack.
,     e# Push [0 ... N-1].
@    e# Rotate N/2 on top of the stack.
f-  e# Subtract N/2 from each element of [0 ... N-1].
* e# Repeat the resulting array N%2 times.


# O, 18

M(.e\2/.@{_}dmrr]p


Live demo.

• Is there a language for every capital letter in the English alphabet?! – Conor O'Brien Nov 4 '15 at 0:04
• They should also be listed in increasing order. – Geobits Nov 4 '15 at 2:28
• @MickeyT Fixed that at the cost of 5 bytes. – kirbyfan64sos Nov 4 '15 at 2:50
• @Geobits Fixed that, too. – kirbyfan64sos Nov 4 '15 at 2:51
• @CᴏɴᴏʀO'Bʀɪᴇɴ There are a couple available – phase Dec 1 '15 at 4:07

# Vitsy, 27 25 Bytes

I'm gonna golf this down tomorrow, but I really ought to go to bed now.

D2M)[&1]D1-i*}\[D2/NaO2+]
D                             Duplicate the input.
2M)[&1]                      If the input is even (input%2=0) generate a new stack
and push 1 to it.
D                     Duplicate the top value - if it wasn't even, this will be the input. Otherwise, it's one.
1-                   Subtract one (to balance around zero)
}                Shift over an item in the stack - this ensures that
we have either the input or one on top.
\[        ]     Repeat input times.
D2/N          Duplicate the top item and print it out.
aO        Newline (I'm pretty sure this is valid separation)
2+      Add one to the top item of the stack.

• "Final global var" that sounds intense – Conor O'Brien Nov 4 '15 at 0:35
• It is intense. – Addison Crump Nov 4 '15 at 0:38
• @CᴏɴᴏʀO'Bʀɪᴇɴ intensity intensifies – Addison Crump Nov 4 '15 at 7:52

# TeaScript, 16 bytes 18

x%2Þr(xØ)ßl-x/2)


Pretty simple. The special characters are actually just "abbreviations" for longer code sequences.

I still haven't made permalinks so you'll have to copy paste into the interpreter

### Explanation

x%2 &&    // If x is NOT even return falsy, else...
r(x--)    // Range 0-input. Subtracts one from input
m(#       // Loop through range
l-      // Current item in loop, minus...
x/2   // input - 1, divided by two
)


• I should implement these special-char abbreviations into Japt. :) BTW, are you sure Ω is 1 byte? – ETHproductions Nov 4 '15 at 3:45
• @ETHproductions Aww :( forgot to check that before I implemented that. I'll fix that in the next commit – Downgoat Nov 4 '15 at 3:46
• @Vɪʜᴀɴ Nah, it's a nice challenge/quirk that keeps stuff interesting. Besides, unprintable chars look cool. – Mama Fun Roll Nov 5 '15 at 4:10
• @ןnɟuɐɯɹɐןoɯ As long as you can actually see them. On my phone, not even your language's name is visible. :P – Dennis Nov 5 '15 at 4:23
• @Dennis It adds to the language's mysterious aura... – Mama Fun Roll Nov 5 '15 at 4:36

# F#, 38 bytes

The falsey result is an empty list.

let O n=if n%2<1 then[]else[-n/2..n/2]


# 𝔼𝕊𝕄𝕚𝕟, 21 chars / 37 bytes

ô[…Ѧ(ï&1⅋ï‡)]ć⇀_-ï/2⸩


Try it here (Firefox only).

Here's a 20-char / 35-byte answer (non-competing, since the answer uses changes implemented after the question was asked):

ô(ï%2⅋ѨĶ(ï‡)ć⇀$-ï/2⸩  Try it here (Firefox only). # Japt, 21 19 bytes Japt is a shortened version of JavaScript. U%2&&(X=-U/2+K o1-X  For odd inputs, returns a integer array of length x, centered at 0; for even, returns 0. Rough JS translation: output(U%2&&(X=-U/2+.5).range(1-X));  where x.range(y) creates a list of integers from x to y. Test it online! In modern Japt, this is only 11 bytes: u ©Uo-U/2-½  Try it online! • To whoever downvoted this answer, can you please explain why? I'd like to know where I went wrong so I can fix it. Thanks. :-) – ETHproductions Nov 4 '15 at 2:34 • Perhaps they don't like the language? (I love the language, though I can see how others might not.) – Conor O'Brien Nov 4 '15 at 3:58 # R, 26 bytes a=scan();-(i=a%/%2*a%%2):i  Try it online! Integer-divide input by 2, and multiply by input modulo 2 (so it becomes zero if input is even). Then output the range of integers from negative to positive of this value. (for a fairer comparison with the previous (half-decade-old!) R answer, the approach here would be 28 bytes as a function). ## R, 30 bytes function(n)(x=(1-n)/2*n%%2):-x  Roughly, x:-x returns the integers from x to -x, where I set x to (1-n)/2. I also use the modulo-2 factor n%%2 in the definition of x to force x to zero when n is even, in which case, 0:0 returns 0 (falsey). # Perl, 36 bytes I have a feeling this can be shortened: $,=$";$n=<>;print$n%2?-$n/2..$n/2:0;  Range treats floats as integers, so, e.g. 5/2 = 2.5 gets silently converted to 2. (If formatting doesn't matter, then remove $,=$"; for a total of 30 bytes). ## Powershell, 49 bytes param($a)$b=$a/2-.5;"[$(-$b..$b-join",")]"*($a%2)


Even numbers evaluated to $false since they provide an empty line output. ("[$(-$b..$b-join",")]"*($a%2))-eq$True ===> False


Odd numbers output the exact reference string. You can save 4 more bytes (now 45) by removing the [] from the output string.

PS> .\balanced.ps1 4

PS> .\balanced.ps1 5
[-2,-1,0,1,2]

PS> .\balanced.ps1 0

PS> .\balanced.ps1 1
[0]

PS>


## Powershell, 36 Bytes

param($a)$b=$a/2-.5;(-$b..$b)*($a%2)


This has the same falsey result but outputs the list of numbers separated by newlines:

PS> .\balanced-newline.ps1 4

PS> .\balanced-newline.ps1 1
0

PS> .\balanced-newline.ps1 5
-2
-1
0
1
2

PS>


# Perl 6, 25 bytes

The shortest lambda expression I could come up with that outputs a list rather than a range is:

{$_%2&&|((1-$_)/2..$_/2)} # 25  Testing: for 0..10 ->$a {
if {$_%2&&|((1-$_)/2..$_/2)}($a) -> $b { say "$a.fmt('%5s')  $b" } else { say "$a.fmt('%5s')  False"
}
}

    0  False
1  0
2  False
3  -1 0 1
4  False
5  -2 -1 0 1 2
6  False
7  -3 -2 -1 0 1 2 3
8  False
9  -4 -3 -2 -1 0 1 2 3 4
10  False


This takes advantage of the fact that Perl 6 treats the number 0 as a false value. If the output had to be exactly False you could replace $_%2 with $_!%%2.

# 05AB1E, 8 bytes (non-competing)

The language postdates the challenge and is therefore non-competing. Code:

È#¹;D(ŸR


Try it online!

Explanation:

È#        # If input % 2 == 0, end the program
¹       # Push the first input from the register
;      # Halve, push input / 2 rounded down
D     # Duplicate top of the stack
(    # Negate
Ÿ   # Inclusive range, pushes [a .. b]
R  # Reverse the array


Uses CP-1252 encoding.

# MathGolf, 6 (or 4?) bytes

½k¥¿╤<


Outputs 0 as falsey output.

Try it online.

If we're allowed to output [0] as falsey output, even though $$\n=1\$$ results in [0] as truthy output as well, this could be 4 bytes instead:

¥*½╤


Try it online.

Explanation:

½       # Integer-divide the (implicit) input-integer by 2
k      # Push the input-integer again
¥     # Modulo-2
¿    # If input%2 is truthy / 1 / odd:
╤   #  Pop the input//2 and push a list in the range [-input//2, input//2]
# Else (it's falsey / 0 / even instead):
<  #  Check if the (implicit) input is smaller than input//2, which is falsey / 0
# (after which the entire stack joined together is output implicitly as result)

¥       # Modulo-2 on the (implicit) input-integer (1 if odd; 0 if even)
*      # Multiply that by the (implicit) input-integer
½     # Integer-divide it by 2
╤    # Pop and push a list in the range [-(input%2*input//2), input%2*input//2]
# (after which the entire stack joined together is output implicitly as result)

• Is there a way in MathGolf to just multiply the two numbers after step 3 and then skip the if-else? – Dominic van Essen Aug 27 '20 at 10:13
• @DominicvanEssen That would result in outputs of [0] instead of 0 though. And since test case $n=1$ is truthy with output [0], I can't use that same [0] as falsey value. I assume you meant something like ½k¥*╤? – Kevin Cruijssen Aug 27 '20 at 10:16
• Yes, that's what I meant, but I didn't expect that [0] would be truthy in MathGolf. – Dominic van Essen Aug 27 '20 at 10:19
• (after writing my first ever golfing program to check that [0] is actually falsey) let's put it a different way: why does the output of n=1 need to be different from the falsey output of even n? – Dominic van Essen Aug 27 '20 at 10:32
• @DominicvanEssen No, [0] isn't truthy in MathGolf. But it is for this challenge for $n=1$. So if I also use [0] for all falsey results, how would you differentiate between a truthy [0] and falsey [0] result in this challange? – Kevin Cruijssen Aug 27 '20 at 11:07

# PHP, 50 bytes

<?=($n=$argv[1])&1?join(_,range(-$k=$n/2|0,$k)):0;  program, takes input from STDIN, prints _ delimited list or 0. or function f($n){return$n&1?range(-$k=$n/2|0,$k):0;}


function takes argument, returns array or 0.

# Java, 145 bytes

public class c{static void c(int n){for(int i=n/2*-1;i<=n/2;i++){if(n%2==0){System.out.print("false");break;}System.out.print(i);}}}


Explanation: Sorry, I know this is really long. I didn't see an answer for java so I decided to put one in. Let me know if I need to write the main function (Im not sure if thats the policy or not). Basically it divides the number by two and multiplies it by -1 for the lower bound and for the upper bound it just uses the number divided by two. I'm kind of new to this page so if I didn't format anything right then let me know. Also, I know that answers can be shortened with lambda functions but I don't know how to use them and Im not sure if Java supports them.

Here is a more readable version which is less golfed:

public class StackOverflow {
static void c(int n){
for (int i = n/2*-1; i<=n/2; i++){
if(n%2==0){
System.out.print("false");
break;
}
System.out.print(" " + i);
}
}
}

• The normal rule is that you need to write a program or function. In Java, a function will nearly always be shorter (especially as it lets you output via return – the return value is a legitimate form of output – rather than needin to use System.out, although in this case for return to work you'd need to store the partially constructed lists in a string). Recent Java does support lambdas, and they normally come out shorter than a "regular" function definition. (Also, why the leading whitespace?) – user62131 Jan 5 '17 at 8:13
• @ais523 The leading whitespace is just my own personal habit and I didn't include it in the byte count, I guess I should get rid of it. Thanks for the help! – Henry Jan 5 '17 at 8:18

## Ruby, 25 bytes

->n{n%2>0&&[*(-n/=2)..n]}


# Ruby, 27 bytes

->n{[*0-n/2..n/2]if n.odd?}


Creates an anonymous lambda function that will return the array of n numbers closest to 0 if n is odd, and returns nil (a falsey value in ruby) otherwise.

Ruby rounds its integer division towards -infinity, but 0-n/2 is shorter than -n/2+1 (since the minus sign is there anyway), and because n is now considered positive, the rounding works in my favour.

### Old Version (28 bytes)

->n{[*-n/2+1..n/2]if n.odd?}


# Japt, 8 bytes

Outputs 0 for even inputs.

u ©Uo-Uz


Try it

u ©Uo-Uz     :Implicit input of integer U
u            :Modulo 2