Quantcast
Viewing all articles
Browse latest Browse all 6

Answer by Doorknob for Golfing: How many unit-length squares in a list of 2d coordinates?

Ruby, 164161153 147 characters

f=->a{a.combination(4).map(&:sort).uniq.count{|x|[x[1][0]==l=x[0][0],x[3][0]==m=x[2][0],x[2][1]==n=x[0][1],x[3][1]==o=x[1][1],m-l==1,o-n==1].all?}}

It's actually very readable, except for the part that tests whether it's a unit square or not.

Probably many improvements possible, attempting to find them now.

Samples (all of them work):

puts f[[[0,0], [0,1], [1,1], [1,0], [0,2], [1,2]]]                             #--> 2puts f[[[0,0], [0,1], [1,1], [1,0], [0,2], [1,2], [2,2], [2,1]]]               #--> 3puts f[[[0,0], [0,1], [1,1], [1,0], [0,2], [1,2], [2,2], [2,1], [2,0]]]        #--> 4puts f[[[0,0], [0,1], [1,1], [1,0], [0,2], [1,2], [2,2], [2,1], [2,0], [9,9]]] #--> 4

I may be able to find a trick with transpose, but I've been trying for a while and I can't. Here's what it does:

irb(main):001:0> a = [[5, 10], [5, 11], [6, 10], [6, 11]]=> [[5, 10], [5, 11], [6, 10], [6, 11]]irb(main):002:0> a.transpose=> [[5, 5, 6, 6], [10, 11, 10, 11]]

Viewing all articles
Browse latest Browse all 6

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>