Take the 2-minute tour ×
Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

List the coordinates of 8 squares adjacent to (0, 0) in a 2d grid. Namely,

[(1,-1),(1,0),(1,1),(0,1),(-1,1),(-1,0),(-1,-1),(0,-1)]

Order does not matter. The goal is to store the points into a list. Shortest answer wins.

share|improve this question
    
Formatted exactly like the string in your question, or listed in the native/natural format for your language? –  DigitalTrauma Apr 8 at 16:52
2  
@DigitalTrauma, listed in natural format. –  Karolis Juodelė Apr 8 at 16:53
1  
Can you just clarify if the (0, 0) has to be omitted from the output? –  Gareth Apr 8 at 17:32
1  
@Gareth, yes, it has to be omitted. It would be 9 squares with (0,0), after all. –  Karolis Juodelė Apr 8 at 17:41
1  
@DigitalTrauma, store only. –  Karolis Juodelė Apr 8 at 17:58

32 Answers 32

up vote 15 down vote accepted

J - 12 char

The most natural representation of a list of pairs is a list of boxes containing each pair.

   }.4|.,{;~i:1
+---+----+---+---+-----+----+----+----+
|0 1|1 _1|1 0|1 1|_1 _1|_1 0|_1 1|0 _1|
+---+----+---+---+-----+----+----+----+

The magic happens in {, called Catalogue. It is essentially a generalized Cartesian product. The }.4|. part is for removing the 0 0 pair.

share|improve this answer

Bash + grep 35

eval echo\ {-1..1},{-1..1}\;|grep 1

I know this doesn't beat the other bash answer but someone had to think of grep

share|improve this answer
2  
+1 for a slightly different approach –  DigitalTrauma Apr 8 at 18:26

Python 43 32

l=zip([1,-1,0]*3,[-1,1]*3+[0]*2)

Inspired by @primo

share|improve this answer
    
I don't think this is 43 bytes anymore :) –  2rs2ts Apr 9 at 17:03
    
It looks like 43 characters to me - am I missing something? Oh wow, that solution above is sweet. –  isaacg Apr 9 at 18:36
    
@issacg I had miscounted earlier, my mistake. Nice improvement, though. –  2rs2ts Apr 9 at 18:50
    
I like it. Nice improvement on my 40. –  primo Apr 20 at 4:47

Ruby 29 28 26

(a=-1,1,0).product(a)[0,8]

Bonus solution:

Ruby has many nice builtin array operators, but some of them have ridiculously long names.

[*[-1,1,0].repeated_permutation(2)].take 8
share|improve this answer
    
Doesn't this include the 0,0? –  Gareth Apr 8 at 17:27
    
You don't actually need the square brackets in your first answer. –  histocrat Apr 8 at 17:28
    
@histocrat thanks! –  daniero Apr 8 at 17:40
1  
@DigitalTrauma :P –  daniero Apr 8 at 20:04
1  
You can go further: (a=-1,1,0).product(a)[0,8] is 26 chars. –  algorithmshark Apr 8 at 20:33

GolfScript (17 chars)

9,4-{[.3/(\3%(]}%

Since the question calls for the points to be "listed in natural format", this leaves an array on the stack. To pretty-print it, append p, as in the online demo.

share|improve this answer

Brainfuck, 1093 characters.

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

EDIT 209 characters

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

Original by Benjamin - i gave it another shot as well and got to 209 characters as well.

share|improve this answer
5  
Someday, Brainfuck will win a code-golf contest ! –  Michael Apr 10 at 7:17
2  
@Michael : it did, once: codegolf.stackexchange.com/questions/8915/… –  vsz Apr 10 at 12:54
1  
My solution is 5 times more concise :) codegolf.stackexchange.com/a/25666/20279 –  Benjamin Apr 10 at 14:51

Haskell 32

c=[0,1,-1]
_:l=[(a,b)|a<-c,b<-c]

The list is l (L).

share|improve this answer
    
+1 Nice use of pattern matching. –  Kaya Apr 9 at 2:53
    
You could do _:l=(,)<$>c<*>c to save 6 characters, although it requires import Control.Applicative. –  Karolis Juodelė Apr 9 at 4:45
    
Yeah, having free import statements would be pretty cool. It'd be interesting to specify free imports on a challenge, and see what sort of different responses you'ld get. –  isaacg Apr 9 at 4:59

Perl, 43 bytes

for$x(-1..1){$x|$_&&push@r,[$x,$_]for-1..1}

The result is stored in array @r. Explicitly it can be defined with 58 bytes:

@r=([-1,-1],[-1,0],[-1,1],[0,-1],[0,1],[1,-1],[1,0],[1,1])
share|improve this answer

J, 16 characters

   }.4|.,<@,"0/~i:1

Usage:

   }.4|.,<@,"0/~i:1
┌───┬────┬───┬───┬─────┬────┬────┬────┐
│0 1│1 _1│1 0│1 1│_1 _1│_1 0│_1 1│0 _1│
└───┴────┴───┴───┴─────┴────┴────┴────┘

Pretty ugly - especially dropping the (0, 0). There's probably a better way.

share|improve this answer

Mathematica 23

Most@Tuples[{-1,1,0},2]
(*
{{-1, -1}, {-1, 1}, {-1, 0}, {1, -1}, {1, 1}, {1, 0}, {0, -1}, {0, 1}}
*)
share|improve this answer
    
Cheeky. :) Very nice idea! I think precedence rules should allow you to replace Tuples[{...},2] with {...}~Tuples~2 to save another byte. –  Martin Büttner Apr 8 at 18:26
    
@m.buettner Thanks. That byte is lost afterwards when trying to apply Most[] (or I can't find a way around it). BTW I never saw you around mathematica.stackexchange.com Any particular reason? –  belisarius Apr 8 at 18:31
    
Can you explain how this works? –  DigitalTrauma Apr 8 at 18:33
    
Ah, I thought ~..~ had higher precedence than @. I think that means I can save a byte in quite a few of my mathematica-answers :D. No particular reason why I haven't been around mathematica stackexchange, but I haven't used other SE sites other than SO much until recently. And I don't really consider myself an expert in Mathematica to be answering interesting questions. And I also don't use it for more than some casual stuff like here in code golf and the odd physics problem. –  Martin Büttner Apr 8 at 18:34
2  
@DigitalTrauma Tuples[{a,b,c ...}, n] generates all possible lists of length n containing {a,b,c ...} as elements. Then Most[] discards the last one (which is {0,0} ) –  belisarius Apr 8 at 18:35

Mathematica, 44 characters

Outer[List,d=Range@3-2,d]~Flatten~1~Drop~{5}

Well. Generates all 9 coordinates, flattens the list and drops the centre.

share|improve this answer
    
Very nice use of common functions, Outer and Range, but they should not return the point {0,0}. –  David Carraher Apr 8 at 17:32
    
@m.buettner Good. Thanks. +1 –  DigitalTrauma Apr 8 at 17:38

Python 50:

l=[(a,b)for a in[1,0,-1]for b in[1,0,-1]];l.pop(4)
share|improve this answer

Brainfuck, 217 209 characters.

Only a bit worse than Java! 5x less than the other BF solution.

++++++++++[>+++++++++>++++>+++++>++++<<<<-]>+.>.>-.>++++.+.<.<+.>>-.<<-.>.>.<-.<+.>>.<<-.>+.>.<.<+.>>.<<-.>-.>.<+.<+.>>.<<-.>>+.<.>-.<.<+.>>.<<-.>>+.<.>-.<-.<+.>>.<<-.>>+.<+.>-.+.<.<+.>>-.<<-.>-.>.+.<+.<+.<++.
share|improve this answer
    
You mean 1/5th of the other solution :D But i accept your challlenge. Allthough i think i can not get it any smaller than this. –  Rob Quist Apr 11 at 9:09
    
Hah.. I gave it a shot as well and came to the same amount of characters... Coincidence? –  Rob Quist Apr 11 at 10:28

Bash, 25 characters

Storing the list of coordinates as a bash array a:

a=({-1..1},{-1..1});a[4]=

Output:

$ a=({-1..1},{-1..1});a[4]=
$ echo ${a[@]}
-1,-1 -1,0 -1,1 0,-1 0,1 1,-1 1,0 1,1
$
share|improve this answer

F# - 41 36 bytes

[for i in 0..7->i*2/5-1,(i*5/4)%3-1]
share|improve this answer

C++, 60

Let's do this an interesting way. Hint: "2" is ASCII 50.

char x[]="11123332",y[8],i;for(i=8;i--;)y[(i+2)%8]=x[i]-=50;
share|improve this answer
    
Can you do char *x="11123332" to save a char? –  DigitalTrauma Apr 8 at 18:22
1  
or just auto x="11123332" to save another –  Oliver Hallam Apr 8 at 18:36
    
@DigitalTrauma you can, but only once the array has been declared, otherwise it throws an exception. Eliminating declarations my code becomes char*x="11123332";for(i=8;i--;)y[(i+2)%8]=x[i]-=50; saving 8 bytes. You have to include the type specifier char so it knows what to store in *x. –  steveverrill Apr 8 at 18:42
    
or char*x="11123332" if you're not so comfortable with auto. –  ace Apr 8 at 18:42
    
You can save another byte with i=8;while(i--) I believe. Combine with char*x= and you're looking at only 57 bytes. –  corsiKa Apr 9 at 1:44

Python - 57 54 56

r=range(-1,2);list({(i,j) for i in r for j in r}-{(0,0)})

Improved to

r=[-1,0,1];list({(i,j) for i in r for j in r}-{(0,0)})

with storage of the variable

r=[-1,0,1];l=list({(i,j) for i in r for j in r}-{(0,0)})
share|improve this answer
2  
r=[-1,0,1] is shorter! –  Roberto Bonvallet Apr 8 at 17:56
    
You're right- nice one –  willem Apr 8 at 17:58
    
Um, you need to print it. –  user80551 Apr 8 at 18:04
    
Only storing is needed according to the instructions, so perhaps its necessary to add l= before list at a price of 2 chars –  willem Apr 8 at 18:05

Perl 6: 27 characters

Most simply:

$/=(-1..1 X -1..1)[^4,5..*]

Get the permutations of -1, 0, and 1 with itself, and hard-code skipping (0, 0). But that's no fun! I prefer things to be more complex: (50 characters)

$/=map {[.re,.im]},grep *.abs>0,(-1..1 X+ -i,0i,i)
share|improve this answer

Python - 37 bytes

a=[(i*2/5-1,-i%3-1)for i in range(8)]

An alternative at 40:

a=zip([0,1,-1]*3,[0]*3+[1]*3+[-1]*3)[1:]

And a 42 that's also interesting:

a=0,1,-1;a=zip(sum(zip(a,a,a),()),a*3)[1:]
share|improve this answer

APL (13 characters)

1↓,∘.,⍨0 1 ¯1

Explanation:

1↓           ⍝ Drop the first element of
  ,          ⍝ an array that comes from the matrix formed by
   ∘.,⍨      ⍝ concatenating each element with every other element
       0 1 ¯1⍝ in this array [0,1,-1]
share|improve this answer

Java 207 204

Way too much, I know, but its the best I could do right now...
I might think of something better...

class A{public static void main(String...a){int[][] l=new int[8][2];for(int x=-1,y,i=0;x<2;x++){for(y=-1;y<2;y++){if(x!=0||y!=0){l[i][0]=x;l[i][1]=y;System.out.print("("+l[i][0]+","+l[i][1]+")");i++;}}}}}

Sensibly:

class A {
    public static void main(String...a) {
        int[][] l = new int[8][2];
        for (int x = -1, y, i = 0; x < 2; x++) {
            for (y = -1; y < 2; y++) {
                if (x != 0 || y != 0) {
                    l[i][0] = x;
                    l[i][1] = y;
                    System.out.print("("+l[i][0]+","+l[i][1]+")");
                    i++;
                }
            }
        }
    }
}
share|improve this answer
    
main(String[] args) -> main(String...s) Saves 3 characters. –  Averroes Apr 10 at 15:10
    
@Averroes thanks! edited. –  kukac67 Apr 10 at 15:11
    
I bet String[]a is better than String...a –  Olathe Jul 6 at 22:20

PYG (27):

P(*ItPr((-1,0,1),repeat=2))

Nothing all that special, really.

In regular python:

from itertools import product
for i in product((-1,0,1),repeat=2): print i
share|improve this answer
1  
This prints (0, 0). I think this is not supposed to be included –  DigitalTrauma Apr 8 at 17:29
    
The OP has clarified (0,0) should not be included. Let me know when you fix this and I'll remove my downvote :) –  DigitalTrauma Apr 8 at 17:44
    
What is this "PYG", you speak of? (Presumably not a Pig Latin program or yet another package manager.) –  Cees Timmerman Apr 11 at 9:25

C, 73

main(i){for(i=0;i<9;i++)if(i-4)printf("%s(%d,%d)",i?",":"",i%3-1,i/3-1);}
share|improve this answer

Mathematica: 41

This works most of the time ;)

Union[RandomInteger[2,{99,2}]-1]~Drop~{5}

Equivalently:

Drop[Union@RandomInteger[2,{99,2}]-1,{5}]
share|improve this answer
    
In the first case you can lose another character, by using infix notation for RandomInteger. –  Martin Büttner Apr 11 at 11:17

Matlab: 53

Similar to my other answer:

unique(round(2*rand(99,2))-1,'rows');ans([1:4,6:9],:)

I couldn't index on the output of unique directly, and I couldn't find a way around that...

share|improve this answer

Haskell 97

Too much for Haskell and definitely not as good as the other Haskell answer, but here's a different, albeit sucky, approach:

take 8 (zip (replicate 3 (-1) ++ replicate 3 1 ++ replicate 3 0) (concat (replicate 3 [-1,1,0])))

:D

share|improve this answer

Scala, 56

Self-explanatory.

def x=List(-1,0,1);for{i<-x;j<-x;if i!=0|j!=0}yield(i,j)

Ungolfed:

def x=List(-1,0,1)
for{
  i <- x
  j <- x
  if i!=0 | j!=0
} yield(i,j)
share|improve this answer

Perl, 42 characters:

@r=map[split","],grep/1/,glob"{-1,0,1},"x2

Uses the shell-like glob functionality to generate the list of strings ("-1,-1","-1,0","-1,1","0,-1","0,0","0,1","1,-1","1,0","1,1"), discards strings that don't contain the character "1" (i.e. drop "0,0"), then splits the strings on comma to get the desired data structure.

41 characters:

@r=map[split x],grep/1/,glob"{-1,0,1}x"x2

abuses barewords: the strings are ("-1x-1","-1x0", etc.) and the split is done on the letter x instead.

share|improve this answer

Fortran: 101 96

Fortran supports complex variables, so we just store the 8 values as a set of complex numbers and get ourselves a list of tuples.

complex x(8);x=reshape([(1,-1),(1,0),(1,1),(0,1),(-1,1),(-1,0),(-1,-1),(0,-1)],[8]);print*,x;end

Printing this to look nice might be a pain in the butt because printing the real and aimag components adds a lot of bytes. But we can deal with floats.


Old answer:

complex x(8);k=1;do i=-1,1;do j=-1,1;if((j==0).and.(i==0))cycle;x(k)=cmplx(i,j);k=k+1;enddo;enddo;end

This abuses implicit typing (as usual).

share|improve this answer

SQL 109 (that far)

create table a(x int);insert into a values(-1),(0),(1);select a.x,b.x y from a,a b where not(a.x=0 and b.x=0)

if you want to retest it, you can prepend drop table if exists a;

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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