1
\$\begingroup\$

I have a 7x7 board and I want to select some elements from it. The elements I want to select are marked o, the other ones are marked x.

Here is the board:

xoxoxox
ooooooo
xooooox
ooooooo
xooooox
ooooooo
xoxoxox

I use indexing starting from 1. The point (1,1) is the top left.

The current list comprehension I have to select the o-elements is the following:

[(r,c) | r<-[1..7], c<-[1..7],
         (not (even r) && not (even c) && r/=1 && r/=7 && c/=1 && c/=7) 
         || even r
         || even c]

I am wondering if I can make this list comprehension more simple. The code above is in Haskell, however, pseudo-code or Python list comprehensions are also fine with me.

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

Since 7 is prime, the following pseudo code works, although it involves some “thinking around the corner”.

[(r,c) | r<-[1..7], c<-[1..7], r * c not in [1, 3, 5, 7, 21, 35, 49]]

A more straightforward way would be

(r /= 1 && r /= 7 && c /= 1 && c /= 7) || even r || even c
\$\endgroup\$
  • 2
    \$\begingroup\$ The first solution generates the correct result. The second one still includes the xs on the first and last row. \$\endgroup\$ – JNevens Dec 17 '16 at 18:01

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.