previndexinfonext

code guessing, round #28 (completed)

started at ; stage 2 at ; ended at

specification

sorry I'm late, but your challenge this round is to count rectangles. submissions may be written in python, erlang, sed, ocaml, lua, ada, or gnu apl.

have you ever seen an image that looks something like this?
an image showing overlapping rectangles with the caption "how many rectangles can you count?"
your challenge will be to solve problems similar to this. (you can hover over the image to see the answer)

given a grid of bits, your challenge is to count the number of rectangles in the grid. a rectangle is defined as an n×m (n, m ≥ 2) region of the grid such that all of the bits on the border of the region are 1.

here are some example results, where . represents 0 and # 1:

# # # # # . . . .
# . . . # . . . .
# . # # # # # # #
# . # . # . . . #
# . # . # . . . #
# # # # # . . . #
. . # . . . . . #
. . # # # # # # #
> 3

# # #
# # #
> 3

# # # # # #
# . # # . #
# # # # # #
> 8

# . . #
# . . #
# . . #
# # # #
> 0

APIs are as follows:

results

  1. 👑 olive +3 -1 = 2
    1. Palaiologos
    2. soup girl
    3. LyricLy
  2. Palaiologos +3 -1 = 2
    1. olive
    2. soup girl
    3. LyricLy
  3. LyricLy +1 -2 = -1
    1. Palaiologos (was olive)
    2. olive (was Palaiologos)
    3. soup girl
  4. soup girl +0 -3 = -3
    1. Palaiologos (was olive)
    2. LyricLy (was Palaiologos)
    3. olive (was LyricLy)

entries

you can download all the entries

entry #1

written by olive
submitted at
0 likes

guesses
comments 0

post a comment


rectagone.lua ASCII text
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
local function sunrise(p)
	if not p then return 0 end
	local dracula = 0
	local pr=p  while pr.r do pr=pr.r
	local pd=pr while pd.d do pd=pd.d
	local pl=pd while pl.l do pl=pl.l
	local pu=pl while pu.u do pu=pu.u
		if pu == p then dracula = dracula + 1 break end
	end end end end
	return dracula
end

return function(t)
	if #t == 0 then return 0 end
	local I,J = #t,#t[1]
	for i=1,I do for j=1,J do
		t[i][j] = t[i][j] and {} or nil
	end end
	for i=1,I do for j=1,J do
		if t[i][j] then
			t[i][j].r = t[i][j+1]
			t[i][j].d = t[i+1] and t[i+1][j] or nil
			t[i][j].l = t[i][j-1]
			t[i][j].u = t[i-1] and t[i-1][j] or nil
		end
	end end
	local duckula = 0
	for i=1,I do for j=1,J do
		duckula = duckula + sunrise(t[i][j])
	end end
	return duckula
end

entry #2

written by Palaiologos
submitted at
0 likes

guesses
comments 0

post a comment


rect.c ASCII text
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>

int pub[99][99];

int main(void) {
    int i=0,j=0,c=0,mi=0;
    while((c=getchar()) != -1) {
        if(c==10) {j++;if(mi<i)mi=i;i=0;}
        else if(c==48||c==49) {
            pub[j][i]=c-48;
            i++;
        }
    }

    const int max_x = mi, max_y = j; int sum = 0;
    for(int x1 = 0; x1 < max_x-1; x1++)
        for(int y1 = 0; y1 < max_y-1; y1++)
            for(int x2 = x1 + 1; x2 < max_x; x2++)
                for(int y2 = y1 + 1; y2 < max_y; y2++){
                    for (i = x1; i <= x2; i++)
                        if (pub[y1][i] != 1)
                            goto next;
                    for (i = y1; i <= y2; i++)
                        if (pub[i][x1] != 1)
                            goto next;
                    for (i = x1; i <= x2; i++)
                        if (pub[y2][i] != 1)
                            goto next;
                    for (i = y1; i <= y2; i++)
                        if (pub[i][x2] != 1)
                            goto next;
                    sum++;
                    next:;
                }
    printf("%d",sum);
}

entry #3

written by soup girl
submitted at
0 likes

guesses
comments 0

post a comment


entry.py.py ASCII text
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
import numpy as np
import re as re

def entry(grid):
 hrid = np.array(grid).transpose().tolist()

 g = [(p*3+1,q.start(),~-q.end()) for p,r in enumerate(grid) for q in re.finditer('1(, 1)+',str(r))]
 h = [(p*3+1,q.start(),~-q.end()) for p,r in enumerate(hrid) for q in re.finditer('1(, 1)+',str(r))]

 count = 0
 
 for a, b, c in g:
  for d, e, f in h:
    if b <= d < c and e <= a < f:
       for u, v, w in g:
            if a < u <= f and v <= d < w:
                   for x, y, z in h:
                                if y <= a and u <= z and d < x <= c and v < x <= w:
                                                     count = count + 1 # increments count by one

 return count

entry #4

written by LyricLy
submitted at
0 likes

guesses
comments 0

post a comment


cg.py Unicode text, UTF-8 text
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# contact: @a_cg_player

import image
import twitter
import imgur
import io
import time
import re
from collections import Counter

def entry(grid):
    im = image.draw(grid)
    im_data = io.BytesIO()
    im.save(im_data, format="png")

    im_data.seek(0)
    url = imgur.upload(im_data)

    twitter.send(f"how many rectangles are in the image? 😛 😛 😛 {url} #cg28")

    i = 0
    answers = Counter()
    seen = set()

    while i < 60*60 or answers.total() < 5 and (not answers or i < 24*60*60):
        time.sleep(500)
        i += 500

        for reply in twitter.get_replies():
            if reply.id in seen:
                continue
            seen.add(reply.id)

            s = set([int(x.replace(",", "").replace(".", "")) for x in re.findall(r"[\d,.]+", reply.text)])
            if len(s) == 1:
                answers[s.pop()] += 1

    return answers.most_common(1)[0]
image.py ASCII text
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
from PIL import Image, ImageDraw

CELL_SIZE = 16

def to_coord(n):
    return int((n+0.5)*CELL_SIZE)

def draw(grid):
    im = Image.new("L", (CELL_SIZE*(len(grid[0]) if grid else 0), CELL_SIZE*len(grid)), 255)
    dw = ImageDraw.Draw(im)
    for y in range(len(grid)):
        for x in range(len(grid[0])):
            if not grid[y][x]:
                continue
            for nx, ny in ((x+1, y), (x-1, y), (x, y+1), (x, y-1)):
                if not (0 <= nx < len(grid[0]) and 0 <= ny < len(grid) and grid[ny][nx]):
                    continue
                dw.line(tuple(map(to_coord, (x, y, nx, ny))))
    return im
imgur.py ASCII text
1
2
3
4
5
import requests

def upload(fp):
    resp = requests.post("https://api.imgur.com/3/upload", headers={"Authorization": "Client-ID e0818e7d82420eb"}, files={"image": fp.read()})
    return resp.json()["data"]["link"]
twitter.py ASCII text
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import tweepy
import flask
import webbrowser
import sys
import os
import imgur

handler = tweepy.OAuth2UserHandler(
    client_id="Y0pTa2RFM2NWblJORllTbUwwcDY6MTpjaQ",
    redirect_uri="http://localhost:10701/",
    scope=["tweet.read", "tweet.write", "users.read"],
    client_secret="12vBF2ZVdAlEVGUENk6RS2YLSHUoKoq-aY9UZMZzIb2DM3ta3V",
)

def send(text):
    app = flask.Flask(__name__)

    @app.route('/')
    def callback():
        global client, tweet_id

        token = handler.fetch_token(flask.request.url.replace("http", "https"))
        client = tweepy.Client(token["access_token"])
        
        tweet_id = client.create_tweet(text=text, user_auth=False).data['id']
        me = client.get_me(user_auth=False)

        flask.request.environ['werkzeug.server.shutdown']()
        return flask.redirect(f"https://twitter.com/{me.data.username}/status/{tweet_id}")

    webbrowser.open(handler.get_authorization_url())
    with open(os.devnull, "w") as dev_null:
        sys.stdout = dev_null
        sys.stderr = dev_null
        app.run(port=10701)
        sys.stdout = sys.__stdout__
        sys.stderr = sys.__stderr__

def get_replies():
    tweets = client.search_recent_tweets(f"is:reply conversation_id:{tweet_id}")
    return tweets.data or []