previndexinfo

code guessing, round #99, stage 2 (guessing)

started at ; stage 2 since . guess by

specification

hop on puyo puyo tetris 2! and help me count polyominoes. submissions may be written in any language.

polyominoes are geometric shapes formed of some number of unit squares put together edge-to-edge. they look like this. a group of pentominoes

the above are pentaminoes: polyominoes consisting of 5 squares. there are 12 free pentaminoes, 18 if you consider reflections distinct (one-sided), and 63 if you consider reflections and rotations distinct (fixed).

I want to know how many polyominoes there are of any size, not just 5. your challenge, given a non-negative integer, is to compute the number of polyominoes consisting of that number of squares. you may provide a free, one-sided, or fixed count. (or all 3!)

as any language is allowed, there is no fixed API.

players

  1. eh?
  2. essaie
  3. kimapr
  4. lychee
  5. melody
  6. Moja
  7. oleander
  8. Viken
  9. wind7

entries

you can download all the entries

entry #1

comments 0

post a comment


99.luau Unicode text, UTF-8 text, with CRLF line terminators
  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
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
-- https://play.luau.org/

-- I am absolutely losing it over this polyomino nonsense.
-- I swear these rotations are conspiring behind my back.
-- I may evaporate.
-- This code will either enumerate every polyomino or take me down with it.
-- I've decided to neglect reflections and rotations because I value survival.

type Polyomino = { { number } }

local known = {} :: { [number]: { Polyomino } }

local function doPolyominoesMatch(polyomino1: Polyomino, polyomino2: Polyomino): boolean
	if #polyomino1 ~= #polyomino2 then return false end
	if #polyomino1[1] ~= #polyomino2[1] then return false end

	for y = 1, #polyomino1 do
		for x = 1, #polyomino1[y] do
			if polyomino1[y][x] ~= polyomino2[y][x] then
				return false
			end
		end
	end

	return true
end

local function isUnique(polyominoToCheck: Polyomino, n: number): boolean
	for _, polyomino in known[n] do
		if doPolyominoesMatch(polyomino, polyominoToCheck) then
			return false
		end
	end

	return true
end

local function addToPolyomino(polyomino: Polyomino, posx: number, posy: number): Polyomino
	local height = #polyomino
	local width = #polyomino[1]

	local offsetX = if posx < 1 then 1 else 0
	local offsetY = if posy < 1 then 1 else 0
	local newWidth = math.max(width + offsetX, posx)
	local newHeight = math.max(height + offsetY, posy)

	local newPolyomino = table.create(newHeight)
	for y = 1, newHeight do
		newPolyomino[y] = table.create(newWidth, 0)
	end

	for y = 1, height do
		for x = 1, width do
			newPolyomino[y + offsetY][x + offsetX] = polyomino[y][x]
		end
	end

	newPolyomino[posy + offsetY][posx + offsetX] = 1

	return newPolyomino
end

local function polyominoes(n: number): number
	known[n] = {}

	if n == 0 then
		table.insert(known[n], { { 0 } })
	elseif n == 1 then
		table.insert(known[n], { { 1 } })
	else
		for _, polyomino in known[n - 1] do
			local height = #polyomino
			local width = #polyomino[1]

			for y = 1, height do
				for x = 1, width do
					if polyomino[y][x] == 0 then continue end

					local neighbors = {
						{x + 1, y},
						{x - 1, y},
						{x, y + 1},
						{x, y - 1}
					}

					for _, neighbor in neighbors do
						local neighborx, neighbory = neighbor[1], neighbor[2]

						local isEmpty = neighborx < 1 or neighbory < 1 or neighborx > width or neighbory > height or polyomino[neighbory][neighborx] == 0

						if isEmpty then
							local newPolyomino = addToPolyomino(polyomino, neighborx, neighbory)

							if isUnique(newPolyomino, n) then
								table.insert(known[n], newPolyomino)
							end
						end
					end
				end
			end
		end
	end

	return known[n] and #known[n] or 0
end


local function printPolyomino(polyomino: Polyomino)
	for y = 1, #polyomino do
		local row = ''
		for x = 1, #polyomino[y] do
			row ..= if polyomino[y][x] == 1 then '██' else '  '
		end
		print(`  {row}`)
	end
end

for i = 0, 4 do
	local count = polyominoes(i)

	print(('='):rep(40))
	print(`n = {i}  ({count} polyominoes)`)
	print(('='):rep(40))

	for j, polyomino in known[i] do
		print(`  #{j}`)
		printPolyomino(polyomino)
		if j < #known[i] then
			print(('-'):rep(20))
		end
	end

	print()
end

entry #2

comments 0

post a comment


multi-nominoes.ipynb JSON text data
 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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "ac0acd49",
   "metadata": {
    "vscode": {
     "languageId": "typescript"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "hello world of multi-nominoes!"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "console.log(\"hello world of multi-nominoes!\");"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "da28ef04",
   "metadata": {},
   "source": [
    "ok, so the idea here is to know that there are a few types of symmetry and these hyperpose. the algorithm to build them up comes in 2 steps if the first one is not enough, and is fairly simple. you take a n-stick nomino and you rotate one block about its neighbor in all possible positions, but where the next position would be symmetrical but different to the another you log only one, knowing to double-count it. obviously for one square/quad connecting one other, there are only 2 symmetries: vertical or horizontal"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3acf516f",
   "metadata": {},
   "source": [
    "we create a numerical representation of the nomino in binary as `0b0000` for a 5-stick or `0b111` for a 4-square (and a few other positions), where `0` means above-below current direction and `1` means left-right current direction. we must be careful to note when an arrangement by some interpretation is impossible, such as `0b00` where the last zero means below current (can't bend backwards into itself), or `0b0111` where all the `1`s are \"turn right\" (can't turn into itself)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f999ebb6",
   "metadata": {},
   "source": [
    "the two steps are to (1) collect symmetries from all possible bit-strings and (2) place the superpositions on a grid of prime numbers that are symmetrical in the ways you want to check symmetry then tally products of occupied squares"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e826b97d",
   "metadata": {},
   "source": [
    "#### notes\n",
    "- only need half the possible bit-strings by flipping the bit-string to check upside-down symmetry\n",
    "    - might be more complex than that though because some asymmetrical (non-palindrome) combinations might be late in the enumeration\n",
    "        - numerically represent those non-palindrome combinations and iterate them?\n",
    "    - negate the bit-string?\n",
    "- might be able to check multiple symmetries at the same time on the grid with clever factoring\n",
    "- in general if I write this out mathematically there might be a formula to generate combination count without having to compute each permutation if I can find a way to cancel out permutation generation if I can express some divisor within the with-permutations counter as a function of the permutations too\n",
    "- there might be a better way than primes (finite fields representing primes b0 -> first prime, b11 -> fourth prime)\n",
    "- could try priming the bit-strings\n",
    "- is flipping a prime gradient on the grid sufficient for catching symmetries and mirrors (as opposed to checking against multiple in-grid mirrror gradient)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "af0a59fa",
   "metadata": {
    "vscode": {
     "languageId": "typescript"
    }
   },
   "outputs": [],
   "source": [
    "// actual implementation"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}

entry #3

comments 0

post a comment


Autism-Questionnaire.pdf version 1.7, 1 page(s)

entry #4

comments 0

post a comment


Makefile ASCII text
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
CXXFLAGS=-O3
REQFLAGS=-std=c++23

generator: generator.o
	$(CXX) $(REQFLAGS) $(LDFLAGS) $< -o $@

generator.o: generator.cpp
	$(CXX) $(REQFLAGS) $(CXXFLAGS) -c $< -o $@

clean:
	rm -f generator.o generator

.PHONY: clean
generator.cpp 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
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
#include <algorithm>
#include <generator>
#include <stdexcept>
#include <vector>
#include <unordered_set>
#include <optional>

struct Polyomino {
	std::vector<bool> data {1};
	int width{1}, height{1};

	class indexerX;
	class indexerXY;

	indexerX operator[](int x);

	bool operator==(const Polyomino &other) const = default;
};

template<>
struct std::hash<Polyomino> {
	std::size_t operator()(const Polyomino& s) const noexcept
	{
		std::size_t h1 = std::hash<vector<bool>>{}(s.data);
		std::size_t h2 = std::hash<unsigned long>{}(
			((unsigned long)s.width) | ((((unsigned long)s.height) << 32))
		);
		return h1 ^ (h2 << 1);
	}
};

class Polyomino::indexerX {
protected:
	Polyomino &owner;
	int x;

public:
	indexerX(Polyomino &owner, int x) : owner(owner), x(x) {}

	Polyomino::indexerXY operator[](int y);
};

Polyomino::indexerX Polyomino::operator[](int x) {
	return { *this, x };
}

class Polyomino::indexerXY : Polyomino::indexerX {
	int y;

public:
	indexerXY(Polyomino &owner, int x, int y) : Polyomino::indexerX(owner, x), y(y) {}

	bool out_of_bounds() const {
		return x < 0 || y < 0 || x >= owner.width || y >= owner.height;
	}

	operator bool() const {
		if (out_of_bounds())
			return false;
		return owner.data[y * owner.width + x];
	}

	indexerXY operator=(const indexerXY &other) {
		bool v = other;
		return (*this = v);
	}

	indexerXY operator=(bool v) {
		if (out_of_bounds()) {
			int ox = 0, oy = 0;
			if (x < 0) ox = -x;
			if (y < 0) oy = -y;
			x += ox; y += oy;
			Polyomino tmp;
			tmp.data = {};
			tmp.width = std::max(owner.width, x + 1) + ox;
			tmp.height = std::max(owner.height, y + 1) + oy;
			tmp.data.resize(tmp.width * tmp.height);
			for (int ty = 0; ty < owner.height; ty++)
			for (int tx = 0; tx < owner.width; tx++) {
				tmp[tx + ox][ty + oy] = owner[tx][ty];
			}
			tmp[x][y] = v;
			owner = tmp;
			return *this;
		}
		owner.data[y * owner.width + x] = v;
		return *this;
	}
};

Polyomino::indexerXY Polyomino::indexerX::operator[](int y) {
	return { owner, x, y };
}

void print_polyo(Polyomino &v, const char *prefix = "") {
	for (int y = 0; y < v.height; y++) {
		printf("%s", prefix);
		for (int x = 0; x < v.width; x++) {
			printf("%s", v[x][y] ? "[]" : "  ");
		}
		printf("\n");
	}
}

std::generator<const std::pair<int, int>&> valid_pextend(Polyomino &v) {
	for (int y = -1; y <= v.height; y++)
	for (int x = -1; x <= v.width; x++) {
		if (v[x][y]) continue;
		bool ok = false;
		for (int oy = -1; oy <= 1; oy++)
		for (int ox = -1; ox <= 1; ox++) {
			if (!((!!ox) ^ (!!oy))) continue;
			if (v[x + ox][y + oy]) {
				ok = true;
				break;
			}
		}
		if (ok) {
			co_yield { x, y };
		}
	}
}

std::generator<Polyomino&> pvariants_fixed(Polyomino &v) {
	co_yield v;
}

std::generator<Polyomino&> pvariants_onesided(Polyomino &v) {
	Polyomino tmp = v;
	co_yield tmp;
	for (int i=0; i<3; i++) {
		Polyomino rot;
		rot.data = {};
		rot.width = tmp.height;
		rot.height = tmp.width;
		rot.data.resize(rot.width * rot.height);
		for (int y = 0; y < tmp.height; y++)
		for (int x = 0; x < tmp.width; x++) {
			rot[(tmp.height - 1) - y][x] = tmp[x][y];
		}
		tmp = rot;
		co_yield rot;
	}
}

std::generator<Polyomino&> pvariants_free(Polyomino &v) {
	for (auto &v : pvariants_onesided(v)) {
		for (int d = 0; d < 2; d++) {
			Polyomino flip;
			flip.data = {};
			flip.width = v.width;
			flip.height = v.height;
			flip.data.resize(flip.width * flip.height);
			for (int y = 0; y < v.height; y++)
			for (int x = 0; x < v.width; x++) {
				flip[x][y] = d
					? v[(v.width - 1) - x][y]
					: v[x][(v.height - 1) - y];
			}
			co_yield flip;
		}
		co_yield v;
	}
}

template<class F = decltype(pvariants_fixed)>
std::generator<Polyomino&> penumerate(int length, F pvariants = {}) {
	if (length == 1) {
		Polyomino v;
		co_yield v;
		co_return;
	}

	std::unordered_set<Polyomino> seen;

	for (auto &v : penumerate(length - 1, pvariants)) {
		for (auto [x, y] : valid_pextend(v)) {
			Polyomino ext = v;
			ext[x][y] = true;
			if (seen.contains(ext))
				continue;
			for (auto &v : pvariants(ext))
				seen.insert(v);
			co_yield ext;
		}
	}
}

struct Options {
	int length = -1;
	bool debug = false;
};

std::optional<Options> parse_args(int argc, char **argv) {
	Options opt;

	if (argc != 2)
		return {};

	char *arg = argv[1];
	if (arg[0] == 'd') {
		arg++;
		opt.debug = true;
	}

	try {
		opt.length = std::stoi(arg);
	} catch(const std::invalid_argument &e) {
		return {};
	}

	return opt;
}

int main(int argc, char **argv) {
	Options opt;
	{
		auto o = parse_args(argc, argv);
		if (!o) {
			fprintf(stderr, "Usage: generator <NUM>\n"
			                "       generator d<NUM>\n");
			return 1;
		}
		opt = *o;
	}

	struct {
		const char *name;
		const char *prefix;
		std::generator<Polyomino&> (*pvar)(Polyomino &v);
	} ptypes[3] = {
		{ .name = "free", .prefix=" * | ", .pvar = pvariants_free },
		{ .name = "one-sided", .prefix = " - | ", .pvar = pvariants_onesided },
		{ .name = "fixed", .prefix = " @ | ", .pvar = pvariants_fixed },
	};

	bool first = true;

	for (auto &t : std::span(&*ptypes, sizeof(ptypes) / sizeof (*ptypes))) {
		if (first) {
			first = false;
		} else {
			if (opt.debug)
				printf("\n\n\n");
		}

		int count = 0;

		if (opt.debug)
			printf("-----\n");

		for (auto &v : penumerate(opt.length, t.pvar)) {
			if (opt.debug) {
				print_polyo(v, t.prefix);
				printf("-----\n");
			}

			count++;
		}

		if (opt.debug)
			printf("\n");

		printf("%i %s\n", count, t.name);
	}

}

entry #5

comments 0

post a comment


performatn.lua ASCII text
1
2
3
4
5
6
7
function poly (n)
    fink = {1, 2 ,6, 19,63, 206,
    760,
    2725,
    9910,36446,   135268  , 505861
    ,1903890,7204804, 27394666,}
    return fink[n] end

entry #6

comments 0

post a comment


code guessing.py ASCII text, with CRLF line terminators
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
def polyominoes(squareCount):
  allBlocksSet = {frozenset({(0,0)})}
  for _ in range(1, squareCount):
    newAllBlocksSet = set()
    for tempBlockSet in allBlocksSet:
      for block in tempBlockSet:
        newBlockSet = [(block[0]-1,block[1]),(block[0],block[1]-1),(block[0]+1,block[1]),(block[0],block[1]+1)]
        for newBlock in newBlockSet:
          if not newBlock in tempBlockSet:
            newAllBlocksSet=newAllBlocksSet|{tempBlockSet|{newBlock}}
    allBlocksSet=newAllBlocksSet
  return len(allBlocksSet)//squareCount

entry #7

comments 0

post a comment


main.rs 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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
struct Polyomnio(Vec<(i8,i8)>);
impl Polyomnio {
	fn normalize_translation(&mut self) {
		let (min_x, min_y) = self.0.iter().fold((127,127),|(x,y),(z,w)| (x.min(*z),y.min(*w)));
		for (x, y) in &mut self.0 {
			*x -= min_x;
			*y -= min_y;
		}
	}
	fn push_superominos(&self, v: &mut Vec<Polyomnio>) {
		for xy in &self.0 {
			for dxy in [(0,-1),(0,1),(1,0),(-1,0)] {
				let new_xy = (xy.0+dxy.0, xy.1+dxy.1);
				if self.0.contains(&new_xy) { continue; }
				let mut new_polyomino = self.0.clone();
				new_polyomino.push(new_xy);
				v.push(Polyomnio(new_polyomino));
			}
		}
	}
}
impl PartialEq for Polyomnio {
	fn eq(&self, rhs: &Self) -> bool {
		if self.0.len() != rhs.0.len() {
			return false;
		}
		let (max_x, max_y) = self.0.iter().fold((0,0), |(x,y),(z,w)| (x.max(*z),y.max(*w)));
		fn test_under_transformation(a: &Polyomnio, b: &Polyomnio, f: impl Fn(i8,i8)->(i8,i8)) -> bool {
			for xy in &a.0 {
				if !b.0.contains(&f(xy.0, xy.1)) {
					return false;
				}
			}
			true
		}
		test_under_transformation(self, rhs, |x,y| (x,y))
		|| test_under_transformation(self, rhs, |x,y| (max_x-x,y))
		|| test_under_transformation(self, rhs, |x,y| (max_x-x,max_y-y))
		|| test_under_transformation(self, rhs, |x,y| (x,max_y-y))
		|| test_under_transformation(self, rhs, |x,y| (y,x))
		|| test_under_transformation(self, rhs, |x,y| (max_y-y,x))
		|| test_under_transformation(self, rhs, |x,y| (max_y-y,max_x-x))
		|| test_under_transformation(self, rhs, |x,y| (y,max_x-x))
	}
}

fn polyominos_of_size_n(n: usize) -> Vec<Polyomnio> {
	match n {
		0 => return vec![],
		1 => return vec![Polyomnio(vec![(0,0)])],
		_ => (),
	};
	let previous = polyominos_of_size_n(n-1);
	let mut polyominos = vec![];
	for p in previous {
		p.push_superominos(&mut polyominos);
	}
	// translate so min_x == 0 and min_y == 0
	for p in &mut polyominos {
		p.normalize_translation();
	}
	// deduplicate
	for i in (0..polyominos.len()).rev() {
		for j in 0..i {
			if polyominos[i] == polyominos[j] {
				polyominos.remove(i);
				break;
			}
		}
	}
	polyominos
}


fn main() {
	for n in 0..=10 {
		println!("number of {}-omnios: {}", n, polyominos_of_size_n(n).len());
	}
}

entry #8

comments 0

post a comment


cg99.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
from copy import deepcopy
from itertools import product

def is_valid_spot(n,m,i,j):
    if i==0 and j<n: return False
    if 0<i and m[i-1][j]: return True
    if i<n-1 and m[i+1][j]: return True
    if 0<j and m[i][j-1]: return True
    if j<2*n-2 and m[i][j+1]: return True
    return False

def f(n):
    m=tuple((0,)*(2*n-1) for _ in range(n-1))
    m=((0,)*(n-1)+(1,)+(0,)*(n-1),)+m
    s={m}
    for _ in range(n-1):
        s2=set()
        for m in s:
            for i, j in product(range(n), range(2*n-1)):
                if is_valid_spot(n,m,i,j) and m[i][j]==0:
                    m2=list(m)
                    m2[i]=tuple(1 if k==j else m[i][k] for k in range(2*n-1))
                    s2.add(tuple(m2))
        s=s2
    return len(s)

print(f(int(input("Enter the number of cells: "))))

entry #9

comments 0

post a comment


poly.py ASCII text, with CRLF line terminators
1
2
3
4
5
6
7
8
# no i dont think ill do this actually
# you can have a haiku though



# eggs eggs eggs eggs eggs
# eggs eggs eggs eggs eggs eggs eggs
# eggs eggs eggs eggs eggs