13
\$\begingroup\$

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>

\$\endgroup\$
7
  • \$\begingroup\$ Can the output be a range object rather than a list? \$\endgroup\$ Nov 8 '15 at 20:40
  • \$\begingroup\$ @BradGilbertb2gills Sorry, a range object is an invalid output. \$\endgroup\$ Nov 8 '15 at 20:42
  • \$\begingroup\$ The empty list is not always falsey. \$\endgroup\$ Nov 8 '15 at 21:44
  • \$\begingroup\$ @SuperJedi224 In which contexts? \$\endgroup\$ Nov 8 '15 at 21:45
  • 2
    \$\begingroup\$ 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? \$\endgroup\$ Aug 27 '20 at 11:12

35 Answers 35

6
\$\begingroup\$

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.
\$\endgroup\$
5
\$\begingroup\$

APL, 16 15 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.

\$\endgroup\$
0
5
\$\begingroup\$

Mathematica, 32 30 24 bytes

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

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

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

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
\$\endgroup\$
4
\$\begingroup\$

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

\$\endgroup\$
1
4
\$\begingroup\$

Haskell, 37 36 31 bytes

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!

\$\endgroup\$
12
  • \$\begingroup\$ 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. \$\endgroup\$
    – xnor
    Nov 3 '15 at 21:10
  • \$\begingroup\$ 34: g n=[1|odd n]>>[-div n 2..div n 2] \$\endgroup\$
    – xnor
    Nov 3 '15 at 21:19
  • \$\begingroup\$ You should edit it in, it's a small change. \$\endgroup\$
    – xnor
    Nov 3 '15 at 21:28
  • \$\begingroup\$ g n=[1|odd n]>>take n[-div n 2..] also saves a char. \$\endgroup\$
    – xnor
    Nov 3 '15 at 21:31
  • 1
    \$\begingroup\$ @xnor: you're golfing it down faster than I can edit my posts. \$\endgroup\$
    – nimi
    Nov 3 '15 at 21:35
4
\$\begingroup\$

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).
\$\endgroup\$
4
\$\begingroup\$

JavaScript (ES6), 44 43 42 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!

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

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)
\$\endgroup\$
1
  • \$\begingroup\$ If you do k%2*, you can avoid the parens. \$\endgroup\$
    – xnor
    Nov 3 '15 at 20:50
3
\$\begingroup\$

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
\$\endgroup\$
3
\$\begingroup\$

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}
\$\endgroup\$
3
+100
\$\begingroup\$

Vyxal, 8 bytes

∷$½:N$ṡ∧

Try it Online!

Explanation

∷$½:N$ṡ∧
∷          Parity
 $         Swap (putting the input on top again)
  ½        Half
   :       Duplicate
    N      Negate
     $     Swap
      ṡ    Range from a to b
       ∧   Logical AND
\$\endgroup\$
2
  • \$\begingroup\$ Try it Online! for 6 bytes no? \$\endgroup\$
    – lyxal
    May 15 at 13:13
  • \$\begingroup\$ @lyxal The program must give a falsy output for all even numbers. \$\endgroup\$
    – xigoi
    May 15 at 13:59
2
\$\begingroup\$

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.
\$\endgroup\$
2
\$\begingroup\$

O, 18

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

Live demo.

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

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)
           i*                 Additively invert
             }                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.
\$\endgroup\$
3
  • \$\begingroup\$ "Final global var" that sounds intense \$\endgroup\$ Nov 4 '15 at 0:35
  • 3
    \$\begingroup\$ It is intense. \$\endgroup\$ Nov 4 '15 at 0:38
  • \$\begingroup\$ @CᴏɴᴏʀO'Bʀɪᴇɴ intensity intensifies \$\endgroup\$ Nov 4 '15 at 7:52
2
\$\begingroup\$

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
)

This answer is non-competing

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

F#, 38 bytes

The falsey result is an empty list.

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

𝔼𝕊𝕄𝕚𝕟, 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).

\$\endgroup\$
2
\$\begingroup\$

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!

\$\endgroup\$
2
  • 5
    \$\begingroup\$ 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. :-) \$\endgroup\$ Nov 4 '15 at 2:34
  • 3
    \$\begingroup\$ Perhaps they don't like the language? (I love the language, though I can see how others might not.) \$\endgroup\$ Nov 4 '15 at 3:58
2
\$\begingroup\$

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).

\$\endgroup\$
2
\$\begingroup\$

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)
\$\endgroup\$
7
  • \$\begingroup\$ Is there a way in MathGolf to just multiply the two numbers after step 3 and then skip the if-else? \$\endgroup\$ Aug 27 '20 at 10:13
  • \$\begingroup\$ @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¥*╤? \$\endgroup\$ Aug 27 '20 at 10:16
  • \$\begingroup\$ Yes, that's what I meant, but I didn't expect that [0] would be truthy in MathGolf. \$\endgroup\$ Aug 27 '20 at 10:19
  • \$\begingroup\$ (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? \$\endgroup\$ Aug 27 '20 at 10:32
  • \$\begingroup\$ @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? \$\endgroup\$ Aug 27 '20 at 11:07
2
\$\begingroup\$

Python 3.8 (pre-release), 37 bytes

lambda x:x%2*[*range(-x//2+1,x//2+1)]

Try it online!

\$\endgroup\$
1
\$\begingroup\$

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).

\$\endgroup\$
1
\$\begingroup\$

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).

\$\endgroup\$
1
\$\begingroup\$

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>
\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

Jelly, 6 5 bytes

HŒRxḂ

Try it online!

Explanation

HŒRxḂ   Main monadic link
H       Halve
 ŒR     Balanced range
   x    Repeat
    Ḃ    parity of n

-1 byte by finding out there's almost a builtin for this

\$\endgroup\$
1
\$\begingroup\$

Risky, 10 bytes

0?+0*:?\2__?+0-_?/2

Try it online!

Explanation

0     range
?         input
+       +
0         0
*   repeat
:     0 ≠
?         input
\       mod
2         2
_ map
_
?         item
+       +
0         0
-   -
_
?         input
/       /
2         2
\$\endgroup\$
0
\$\begingroup\$

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.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.