N numbers closest to zero staying balanced

10

2

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>

Conor O'Brien

Posted 2015-11-03T20:16:27.660

Reputation: 36 228

Can the output be a range object rather than a list? – Brad Gilbert b2gills – 2015-11-08T20:40:36.283

@BradGilbertb2gills Sorry, a range object is an invalid output. – Conor O'Brien – 2015-11-08T20:42:41.160

The empty list is not always falsey. – SuperJedi224 – 2015-11-08T21:44:20.413

@SuperJedi224 In which contexts? – Conor O'Brien – 2015-11-08T21:45:04.147

There are languages (I.E. Javascript) in which the empty list is considered a truthy value. – SuperJedi224 – 2015-11-08T21:46:07.403

@SuperJedi224 so it is... – Conor O'Brien – 2015-11-08T21:46:35.690

Answers

4

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.

Dennis

Posted 2015-11-03T20:16:27.660

Reputation: 196 637

5

Mathematica, 32 30 24 bytes

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

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

LegionMammal978

Posted 2015-11-03T20:16:27.660

Reputation: 15 731

You can save a byte by using the Unicode brackets for Floor. – Martin Ender – 2015-11-03T22:28:01.243

Also, Range[-a,a=...] seems to work, saving another byte. – Martin Ender – 2015-11-03T22:29:33.153

OddQ@#&&Range@#-(#+1)/2& – ngenisis – 2017-01-05T01:06:31.287

5

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.

lirtosiast

Posted 2015-11-03T20:16:27.660

Reputation: 20 331

4

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!

nimi

Posted 2015-11-03T20:16:27.660

Reputation: 34 639

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 – 2015-11-03T21:10:13.757

34: g n=[1|odd n]>>[-div n 2..div n 2] – xnor – 2015-11-03T21:19:43.460

You should edit it in, it's a small change. – xnor – 2015-11-03T21:28:10.973

g n=[1|odd n]>>take n[-div n 2..] also saves a char. – xnor – 2015-11-03T21:31:25.053

1@xnor: you're golfing it down faster than I can edit my posts. – nimi – 2015-11-03T21:35:07.517

I'd like something like g n=take(sum[n|odd n])[-div n 2..] to work, but it's 34 chars. – xnor – 2015-11-03T21:52:52.810

g n=take(n*mod n 2)[-div n 2..] – xnor – 2015-11-03T21:58:36.667

@xnor: thanks again! Unfortunately the challenge now requires a falsey value for the unbalanced case. As [] is not falsey in Haskell, the answer is now invalid. – nimi – 2015-11-03T22:07:37.590

Is only False falsey? Do you have to Either? – xnor – 2015-11-03T22:41:23.723

@xnor: there's the Maybe type, i.e. Just [-1,0,1] or Nothing, but I think according to meta a falsey value must work within a if ... then .. else, so I'm afraid only Bool (Trueor False) fits. – nimi – 2015-11-03T22:45:38.743

@xnor: there's listToMaybe which turns the empty list into Nothing and a non empty list l into Just l, but it needs the Data.Maybe import. – nimi – 2015-11-03T23:07:25.987

@xnor: ... sorry a mistake listToMaybe makes Just (head l) in the non empty case, i.e. only the first element of l is wrapped into Just. – nimi – 2015-11-03T23:18:49.847

4

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!

ETHproductions

Posted 2015-11-03T20:16:27.660

Reputation: 47 880

Using x%2&&[for(y of...] saves a byte. – intrepidcoder – 2015-11-03T22:58:06.567

ES6, 43, n=>Array(n&1&&n--).fill().map((x,i)=>i-n/2) if returning an empty array is allowed – edc65 – 2015-11-03T23:08:27.990

@intrepidcoder Thanks! I've changed this. – ETHproductions – 2015-11-03T23:11:18.550

@edc65 Thanks as well! I've added this into the answer. – ETHproductions – 2015-11-03T23:11:32.390

x=>x%2&&[for(y of Array(x--).keys())y-x/2] is 42. – intrepidcoder – 2015-11-04T01:28:01.890

@intrepidcoder Thanks again! – ETHproductions – 2015-11-04T03:21:06.513

42 for ES6 too n=>Array(n&1&&n).fill(n=-n>>1).map(x=>++n) – edc65 – 2015-11-05T07:26:43.723

41: n=>[...Array(n&1&&n--)].map((x,i)=>i-n/2) for the ES6 entry – Mama Fun Roll – 2015-11-05T22:49:32.837

@ןnɟuɐɯɹɐןoɯ and edc65 Holy cow, this is getting ridiculous ;) Thanks for the help! I wonder if 40 is possible... – ETHproductions – 2015-11-06T04:05:23.380

4

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

AdmBorkBork

Posted 2015-11-03T20:16:27.660

Reputation: 41 581

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: http://codegolf.stackexchange.com/a/63005/45925)

– Jonathan Leech-Pepin – 2015-11-05T12:59:05.577

3

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

El'endia Starman

Posted 2015-11-03T20:16:27.660

Reputation: 14 504

3

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

Dennis

Posted 2015-11-03T20:16:27.660

Reputation: 196 637

3

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}

Kat

Posted 2015-11-03T20:16:27.660

Reputation: 69

2

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.

Dennis

Posted 2015-11-03T20:16:27.660

Reputation: 196 637

2

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)

Kade

Posted 2015-11-03T20:16:27.660

Reputation: 7 463

If you do k%2*, you can avoid the parens. – xnor – 2015-11-03T20:50:31.437

2

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!

ETHproductions

Posted 2015-11-03T20:16:27.660

Reputation: 47 880

5To 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 – 2015-11-04T02:34:22.210

3Perhaps they don't like the language? (I love the language, though I can see how others might not.) – Conor O'Brien – 2015-11-04T03:58:33.987

2

O, 18

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

Live demo.

kirbyfan64sos

Posted 2015-11-03T20:16:27.660

Reputation: 8 730

5Is there a language for every capital letter in the English alphabet?! – Conor O'Brien – 2015-11-04T00:04:32.847

They should also be listed in increasing order. – Geobits – 2015-11-04T02:28:51.223

@MickeyT Fixed that at the cost of 5 bytes. – kirbyfan64sos – 2015-11-04T02:50:51.110

@Geobits Fixed that, too. – kirbyfan64sos – 2015-11-04T02:51:04.173

2

@CᴏɴᴏʀO'Bʀɪᴇɴ There are a couple available

– phase – 2015-12-01T04:07:02.237

@phase If anyone takes Z, I will be ticked. ;) – Conor O'Brien – 2015-12-01T16:21:51.530

@ConorOBrien https://github.com/z-lang/z-lang and https://github.com/matt-auld/z-lang...

– kirbyfan64sos – 2015-12-01T19:59:17.650

2

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.

Addison Crump

Posted 2015-11-03T20:16:27.660

Reputation: 10 763

"Final global var" that sounds intense – Conor O'Brien – 2015-11-04T00:35:18.380

3It is intense. – Addison Crump – 2015-11-04T00:38:56.987

@CᴏɴᴏʀO'Bʀɪᴇɴ intensity intensifies – Addison Crump – 2015-11-04T07:52:06.067

2

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

Downgoat

Posted 2015-11-03T20:16:27.660

Reputation: 27 116

I should implement these special-char abbreviations into Japt. :) BTW, are you sure Ω is 1 byte? – ETHproductions – 2015-11-04T03:45:12.500

@ETHproductions Aww :( forgot to check that before I implemented that. I'll fix that in the next commit – Downgoat – 2015-11-04T03:46:16.293

I hate that the Greek letters are 2-byte ;-; – Conor O'Brien – 2015-11-04T03:57:46.353

Y'all are complaining? Feel glad you don't have to deal with 's unprintable chars. ;___; – Mama Fun Roll – 2015-11-05T04:00:02.840

@ןnɟuɐɯɹɐןoɯ lol, but looking at ESMin's source code, I recommend trying to keep special characters under 0xFF (255) to keep them 1-byte – Downgoat – 2015-11-05T04:04:02.010

1@Vɪʜᴀɴ Nah, it's a nice challenge/quirk that keeps stuff interesting. Besides, unprintable chars look cool. – Mama Fun Roll – 2015-11-05T04:10:06.463

4@ןnɟuɐɯɹɐןoɯ As long as you can actually see them. On my phone, not even your language's name is visible. :P – Dennis – 2015-11-05T04:23:29.080

2@Dennis It adds to the language's mysterious aura... – Mama Fun Roll – 2015-11-05T04:36:55.377

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

Mama Fun Roll

Posted 2015-11-03T20:16:27.660

Reputation: 7 234

2

F#, 38 bytes

The falsey result is an empty list.

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

Hand-E-Food

Posted 2015-11-03T20:16:27.660

Reputation: 7 912

1

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

flodel

Posted 2015-11-03T20:16:27.660

Reputation: 2 345

1

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

ChicagoRedSox

Posted 2015-11-03T20:16:27.660

Reputation: 240

1

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>

Jonathan Leech-Pepin

Posted 2015-11-03T20:16:27.660

Reputation: 273

1

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.

Brad Gilbert b2gills

Posted 2015-11-03T20:16:27.660

Reputation: 12 713

1

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.

Adnan

Posted 2015-11-03T20:16:27.660

Reputation: 41 965

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);
    }
}
}

Henry

Posted 2015-11-03T20:16:27.660

Reputation: 11

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?) – None – 2017-01-05T08:13:48.707

@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 – 2017-01-05T08:18:27.080

0

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.

Titus

Posted 2015-11-03T20:16:27.660

Reputation: 13 814

0

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?}

IMP1

Posted 2015-11-03T20:16:27.660

Reputation: 510

0

Ruby, 25 bytes

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

G B

Posted 2015-11-03T20:16:27.660

Reputation: 11 099