16
\$\begingroup\$

A recent SO question asks for a convenient one-liner to generate a list of numbers and their negative counterparts in Python.

Given two integers \$1≤a≤b\$, generate all the integers \$x\$ such that \$a≤|x|≤b\$. The result may be printed or returned in any order or structure, as putting the result into a list and sorting it, yields [-b,1-b,2-b,…,-a,a,a+1,a+2,…,b]

Examples

\$a=6,b=9\$ gives [6,-6,7,-7,8,-8,9,-9] or [6,7,8,9,-9,-8,-7,-6] or [-8,7,-9,-7,9,8,-6,6] or [[6,-6],[7,-7],[8,-8],[9,-9]] or [[6,7,8,9],[-6,-7,-8,-9]] etc.

\$a=6,b=6\$ gives [6,-6] or [-6,6] or [[6,-6]] or [[6],[-6]] etc.

\$\endgroup\$
7
  • \$\begingroup\$ Semi-related \$\endgroup\$ – Kevin Cruijssen Apr 23 '20 at 9:29
  • \$\begingroup\$ Since you seemed to accept concatenated negative numbers in a comment to a certain answer, do you accept 1-1 2-2 3-3 4-4? \$\endgroup\$ – the default. Apr 23 '20 at 11:15
  • 3
    \$\begingroup\$ @mypronounismonicareinstate It wasn't just concatenated negative numbers. They were generated as proper numbers, and just printed individually with no separator. That's fine. However, I would object to using string operations to interleave spaces and dashes with duplicated digits, as the individual numbers are never generated then. \$\endgroup\$ – Adám Apr 23 '20 at 11:19
  • 1
    \$\begingroup\$ @HighlyRadioactive By the looks of that Hello world example it can print, so you could print the - characters manually? \$\endgroup\$ – Kevin Cruijssen Apr 24 '20 at 21:22
  • 1
    \$\begingroup\$ @KevinCruijssen It's not allowed. "However, I would object to using string operations to interleave spaces and dashes with duplicated digits, as the individual numbers are never generated then." -- Adám \$\endgroup\$ – null Apr 25 '20 at 4:19

42 Answers 42

11
\$\begingroup\$

Python 2, 33 bytes

def f(a,b):print-a,a;a<b<f(a+1,b)

Try it online!

A recursive function that prints in a two-column format. Based on ideas from Surculose Sputum.

In Python 3, we'd need 2 more bytes for print() needing parens.


Python 2, 37 bytes

lambda a,b:range(a,b+1)+range(-b,1-a)

Try it online!

Unfortunately for this challenge, Python's ranges are exclusive, so we have to add 1 to both upper endpoints.

\$\endgroup\$
7
\$\begingroup\$

05AB1E, 4 bytes

ŸD(«

Try it online!

Explanation

     Takes two input integers
Ÿ    Inclusive range.
 D   Duplicate the stack.
  (  Negate all items of the duplicated item.
   « Concatenate both lists.
     Implicit output
\$\endgroup\$
7
\$\begingroup\$

Haskell, 21 bytes

a%b=[a..b]++[-b.. -a]

Try it online!

Looks like this boring solution is shortest. The space in before -a is needed to avoid a misparse with ..-.

22 bytes

a%b=[id,(0-)]<*>[a..b]

Try it online!

22 bytes

a%b=[[x,-x]|x<-[a..b]]

Try it online!

23 bytes

a%b=do x<-[a..b];[x,-x]

Try it online!

23 bytes

a%b=(,)<*>(0-)<$>[a..b]

Try it online!

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

PowerShell, 28 bytes

$args[0]..$args[1]|%{$_,-$_}

Try it online!

$args[0]..$args[1] generates integer array range from $args[0] to $args[1]. It's piped and then each item in that array is mapped to itself and its negative counterpart.

\$\endgroup\$
1
  • \$\begingroup\$ Welcome to PPCG and great first answer, Eligrhath! Just received your first upvote from me :) \$\endgroup\$ – AviFS Apr 23 '20 at 11:28
4
\$\begingroup\$

Python 3, 40 39 bytes

-1 byte thanks to @xnor!

f=lambda a,b:b//a*[0]and[a,-a]+f(a+1,b)

Try it online!

This would be 38 bytes in Python2, by replacing // operator with just /.

\$\endgroup\$
2
  • 2
    \$\begingroup\$ Huh, your solution is more competitive that I'd expected for anything recursive here. You can save a byte on the base case, two in Python 2: Try it online! \$\endgroup\$ – xnor Apr 23 '20 at 8:46
  • \$\begingroup\$ @xnor Ah yes the list multiplication trick. Gotta keep that in mind, thanks! \$\endgroup\$ – Surculose Sputum Apr 23 '20 at 8:51
4
\$\begingroup\$

Pyth, 5 bytes

_BM}F

Try it online!

}F forms an inclusive range, then _B pairs a number with its negation, and M maps that over the list.

\$\endgroup\$
3
\$\begingroup\$

Dyalog APL, 19 bytes

{(⊢,-)⍺,⍺(⊣+∘⍳-⍨)⍵}

Try it online!

\$\endgroup\$
4
  • 1
    \$\begingroup\$ Do you know TIO can auto-generate posts like this one? [Esc],[s],[g]. \$\endgroup\$ – Adám Apr 23 '20 at 8:59
  • \$\begingroup\$ Welcome to PPCG and great first answer. Who'd have known you're already a very active member of APL Orchard before your first submission! Hope to continue to see you in the room :) \$\endgroup\$ – AviFS Apr 23 '20 at 11:39
  • \$\begingroup\$ By the by, this format is also often used in APL TIO links, let me know what you think... I find it convenient for demonstrating all the input cases, when there are several: Click me Even in the case of one input, it can be rather attractive: Peekaboo \$\endgroup\$ – AviFS Apr 23 '20 at 11:44
  • \$\begingroup\$ Thank you all for your helpful encouragement. \$\endgroup\$ – xpqz Apr 23 '20 at 11:48
3
\$\begingroup\$

Ruby, 22 bytes

->a,b{[*-b..-a,*a..b]}

Try it online!

\$\endgroup\$
3
\$\begingroup\$

R, 26 25 bytes

-1 bytes thanks to Giuseppe

function(a,b)c(a:b,-b:-a))

Try it online!

\$\endgroup\$
0
3
\$\begingroup\$

C (gcc), 44 43 42 bytes

Saved a byte thanks to ceilingcat!!!
Saved a byte thanks to S.S. Anne!!!

f(a,b){for(;b/a;)printf("-%d %1$d ",a++);}

Try it online!

\$\endgroup\$
0
3
\$\begingroup\$

Jelly, 3 bytes

rNƬ

A dyadic Link accepting two integers (either way around) which yields a list of two lists.

Try it online!

How?

rNƬ - Link: integer, a; integer b                         e.g. 7; 4
r   - inclusive range  [a..b]                                  [7,6,5,4]
  Ƭ - collect up while unique, applying:
 N  -   negate (vectorises)                    0-applications: [[7,6,5,4]]
                                               1-application:  [[7,6,5,4],[-7,-6,-5,-4]]
                                               2-applications: [[7,6,5,4],[-7,-6,-5,-4],[7,6,5,4]]
                                                               - no longer distinct
                                                            -> [[7,6,5,4],[-7,-6,-5,-4]]

There are many, many ways to achieve this task in four bytes in Jelly.

\$\endgroup\$
3
\$\begingroup\$

Java 10, 76 56 52 50 bytes

b->a->{for(;a<=b;)System.out.println(a+","+-a++);}

-22 bytes thanks to @OlivierGrégoire.

Takes the inputs in reverse order. Prints pairs of positive and negative integers "a,-a" newline separated.

Try it online.

Explanation:

b->a->{                  // Method with two integer parameters and no return-type
  for(;a<=b;)            //  Loop in the range [a,b]:
    System.out.println(  //   Print with trailing newline:
      a                  //    `a`
      +" "               //    appended with a space
      +-a                //    appended with `-a`
         ++);}           //   And then increase `a` by 1 with `a++`
\$\endgroup\$
5
  • 1
    \$\begingroup\$ Don't know if fully valid, but 72 bytes \$\endgroup\$ – Olivier Grégoire Apr 24 '20 at 20:35
  • 1
    \$\begingroup\$ Or 56 bytes. \$\endgroup\$ – Olivier Grégoire Apr 24 '20 at 20:41
  • 1
    \$\begingroup\$ @OlivierGrégoire Ah nice, I hadn't thought about just printing directly.. And an additional -1 by removing that space at +++ and -3 by printing directly. I like that Map approach as well btw, very original. :D \$\endgroup\$ – Kevin Cruijssen Apr 24 '20 at 21:18
  • \$\begingroup\$ If you take the print route, take it entirely! ;-) I used \n for consistency because of a comment to the question. But one more byte can be gained if you keep the space. \$\endgroup\$ – Olivier Grégoire Apr 24 '20 at 21:42
  • \$\begingroup\$ @OlivierGrégoire Ah nice. :) And space or comma should be fine. OP even allows this kind of output. \$\endgroup\$ – Kevin Cruijssen Apr 24 '20 at 21:47
2
\$\begingroup\$

Keg, -pn , 5 bytes

ɧ⑷④±.

It prints all the numbers separated by newlines.

Explained

ɧ⑷④±.
ɧ      # Generate a range between the two implicit inputs
 ⑷④±. # For each number in that range, print it raw without popping, negate it, and print it raw

Try it online!

\$\endgroup\$
2
  • 1
    \$\begingroup\$ The challenge says you may print it in any structure, so this is probably okay. \$\endgroup\$ – user92069 Apr 23 '20 at 8:40
  • \$\begingroup\$ @petStorm It is. \$\endgroup\$ – Adám Apr 23 '20 at 8:41
2
\$\begingroup\$

C# (Visual C# Interactive Compiler), 47 46 bytes

Much shorter than the beautiful LINQ solutions with SelectMany :(
I also cannot remember when I last wrote a for loop while code-golfing, so I likely missed trivial golfs.

a=>b=>{for(int i=a;i<=b;Print(-i++))Print(i);}

Try it online!

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

Google Sheets, 66 bytes

=ArrayFormula({Row(Indirect(A1&":"&A2));-Row(Indirect(A1&":"&A2))}

Sheets will automatically add the last closing parentheses when you exit the cell. (A 1.5% byte reduction!)

Input is in cells A1 and A2. The order doesn't actually matter.
Indirect(A1&":"&A2) creates a range that contains all the rows between those numbers, inclusive.
Row(Indirect(~)) returns the row numbers of everything in that range.
{Row(~);-Row(~)} creates an array of the positive and negative row numbers.
ArrayFormula(~) makes all the other bits operate on and return arrays. Without this, it would only return the first value in the array (the first row number) instead of all of them.

Example

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

PHP, 51 46 40 bytes

fn($a,$b)=>[range($a,$b),range(-$b,-$a)]

Try it online!

simply using php7 lambda functions short notation and built-in array functions..

EDIT: hum I see that from PHP7.4 we have now a spread operator! -5 bytes

EDIT2: thanks to DomHastings for saving another 6 bytes!

\$\endgroup\$
2
  • 1
    \$\begingroup\$ Based on the accepted examples, I think you can drop the spreads entirely for -6! \$\endgroup\$ – Dom Hastings Apr 23 '20 at 13:40
  • \$\begingroup\$ @DomHastings Oh, yep! Hadn't even looked at the examples :D I was glad to use this new stuff though \$\endgroup\$ – Kaddath Apr 23 '20 at 13:41
2
\$\begingroup\$

Bash + Core utilties, 21 bytes

seq $1 $2;seq -$2 -$1

Try it online!

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

LaTeX, 61 56 bytes

\input tikz.tex\def\f#1#2{\foreach~in{#1,...,#2}{~;-~;}}

Defines a macro f that takes input as two arguments and outputs the numbers as tokens to latex (so they are printed in the pdf), semicolon-seperated.

Explanation

\input tikz.tex                % load the tikz package for the foreach command
\def\f#1#2{                    % define a macro f that takes two arguments
   \foreach ~                  % loop with the loop variable called ~
                               % (to save a space between the name and "in")
   in {#1,...,#2} {            % where ~ ranges from the first to the second 
                               % argument, inclusive
        ~;-~;                  % the macro f expands to
                               % ~
                               % a semicolon and a minus sign
                               % ~
                               % another semicolon
   }
}

Example

\documentclass{article}
\input tikz.tex
\def\f#1#2{\foreach~in{#1,...,#2}{~;-~;}}
\begin{document}
\f6 9

\f6 6
\end{document}

Output: enter image description here

\$\endgroup\$
2
  • \$\begingroup\$ 56 bytes by using \input tikz.tex and looping over ~ instead of \,: \input tikz.tex\def\f#1#2{\foreach~in{#1,...,#2}{~ -~ }} \$\endgroup\$ – L. F. Apr 25 '20 at 8:06
  • \$\begingroup\$ @L.F. thanks :) \$\endgroup\$ – corvus_192 Apr 27 '20 at 7:56
1
\$\begingroup\$

Erlang (escript), 36 bytes

g(A,B)->[[X,-X]||X<-lists:seq(A,B)].

Try it online!

Erlang (escript), 40 bytes

Port of Surculose Sputum's answer.

g(A,A)->[A,-A];g(A,B)->[A,-A]++g(A+1,B).

Try it online!

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

Befunge-98 (FBBI), 24 bytes

&00p&v
0g-k@>::.'-,.1+:0

Try it online!

Explanation

&00p& is the input part. &00p takes \$b\$ as input and stores it in the top left corner. & takes input \$a\$ and pushes it to the stack.

0g-k@>::.'-,.1+:0 is the main loop and, as the instruction pointer wraps around, equivalent to:

::.'-,.1+:00g-k@

::                duplicate a twice
  .               print a
   '-,            print '-'
      .           print a
       1+         increase a
         :        duplicate the new value of a
          00g     get b from the top-left corner
             -    calculate a-b, as Befunge has no negative values,
                  this is 0 for b>=a
              k@  execute *quit* (b-a)-times
\$\endgroup\$
1
\$\begingroup\$

JavaScript (Node.js), 33 31 bytes

-2 bytes thanks to @mypronounismonicareinstate.

b=>f=a=>a>b?[]:[a,-a,...f(a+1)]

Try it online!

\$\endgroup\$
2
  • \$\begingroup\$ As far as I see, the outermost parentheses aren't necessary (or are they for some reason?) \$\endgroup\$ – the default. Apr 23 '20 at 9:24
  • \$\begingroup\$ @mypronounismonicareinstate thanks for noticing, coming from Python, I just assumed they needed to be there. \$\endgroup\$ – ovs Apr 23 '20 at 9:28
1
\$\begingroup\$

J, 10 bytes

]-.&i:<:@[

Try it online!

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

Husk, 5 bytes

mSe_…

Try it online.

Or alternatively:

Svm_…

Try it online.

Explanation:

    …  # Create a an inclusive range using the two (implicit) input-arguments
m      # Map over this list
 Se    # and pair each element with:
   _   #  Its negative
       # (after which the result is output implicitly)

    …  # Create a an inclusive range using the two (implicit) input-arguments
 v     # Concatenate it with:
S m    #  The same list with each value mapped to:
   _   #   Its negative
       # (after which the result is output implicitly)
\$\endgroup\$
1
\$\begingroup\$

Burlesque, 11 bytes

ps^pr@Jng.+

Try it online!

I feel like there's probably a better way to parse the input, but I'm not getting it. Explanation:

ps^p          # Parse input as block and split block to stack
    r@        # Generate range between two inputs
      Jng     # Duplicate and negate
         .+   # Concatenate and implicitly output
\$\endgroup\$
1
\$\begingroup\$

K (oK), 15 bytes

{1 -1*/:y,y^!x}

Try it online!

\$\endgroup\$
7
  • \$\begingroup\$ Why does {1 -1*,y,y^!x} not work? \$\endgroup\$ – Adám Apr 23 '20 at 12:23
  • \$\begingroup\$ @Adám K needs instructions (eahright) how to multiply, since the length of both args do not match. Multiplication (as many of the verbs) is right-atomic - it penetrates in depth to the levels of the nesting of the right argument. \$\endgroup\$ – Galen Ivanov Apr 23 '20 at 12:25
  • \$\begingroup\$ I'm not sure I understand what "right-atomic" means. I just thought that for a scalar function, if one side had one element and the other many, it'd extend the single argument. \$\endgroup\$ – Adám Apr 23 '20 at 12:29
  • \$\begingroup\$ @Adám Hmm, as it seems * is fully atomic. In our case I'm multiplying a list of length 2 (1 -1) by a list of length 4 (9 6 7 8). I'm not sure why does ' (each) not work here. \$\endgroup\$ – Galen Ivanov Apr 23 '20 at 12:37
  • \$\begingroup\$ Each-ing with lists of two different lengths is always a length error. \$\endgroup\$ – Adám Apr 23 '20 at 12:38
1
\$\begingroup\$

brainfuck, 36 bytes

,[->+>->-<<<],+[->>+<<]>>[-<.+>>.-<]

Try it online!

Clarification

Input and output are treated as bytes (as permitted in Can numeric input/output be in the form of byte values?)

Since negative bytes don't really make sense, a negative answer wraps around and starts at the largest value of the cell. For example, given a cell size of 128, the output for the input in bytes [6, 9] will be (in bytes) [6,(128-6),7,(128-7),8,(128-8),9,(128-9)]

Hopefully that's a fair enough interpretation of the rules!

\$\endgroup\$
1
  • \$\begingroup\$ i.e. your bytes should be interpreted as 2's complement representations of signed integers. If BF can only actually do I/O in unsigned decimal, that seems fine to me. In assembly language there are no types, it's all just bytes, so it's up to the programmer to to write code that uses signed operations / comparisons on those bytes as opposed to float or unsigned compares. (Many operations other than compare are the same for signed 2's complement vs. unsigned binary integers; division, right shift, and widening mul being different.) \$\endgroup\$ – Peter Cordes Apr 25 '20 at 1:50
1
\$\begingroup\$

Perl 5, 20 bytes

say"$_
-$_"for<>..<>

Try it online!

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

Zsh, 17 bytes

echo {,-}{$1..$2}

Try it online!

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

Bash, 22 bytes

1 byte more than Bash+seq, 5 bytes more than Zsh due to eval

eval echo {,-}{$1..$2}

Try it online!

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

Piet, 90 codels

Did someone say "one-liner"?

Piet solution at codel size 1

Okay, so technically it's three lines, but I couldn't figure out how to exit a Piet program in less than three pixels of width (or how to loop in less than two pixels). Here it is with a codel size of 4:

Piet solution at codel size 4

And here's the npiet trace of it processing \$a=6, b=9\$:

Piet solution traced in npiet

For input, it takes \$b\$ then \$a\$. For output, it calculates each value of \$x\$ and \$-x\$, outputting them without separators (as was allowed in a comment, as long as the individual numbers are actually calculated).

\$\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.