-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsolve.c
120 lines (109 loc) · 2.75 KB
/
solve.c
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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* solve.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: rhallste <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/11/03 15:37:57 by rhallste #+# #+# */
/* Updated: 2017/11/18 15:13:25 by rhallste ### ########.fr */
/* */
/* ************************************************************************** */
#include <stdlib.h>
#include "libft/inc/libft.h"
#include "fillit.h"
static int smallest_map(t_piece **pieces)
{
int size;
int width;
int height;
int pc;
width = 0;
height = 0;
pc = 0;
while (*pieces)
{
width = MAX(width, (int)(*pieces)->width);
height = MAX(height, (int)(*pieces)->height);
pieces++;
pc++;
}
size = 2;
while (size * size < pc * 4)
size++;
size = MAX(size, width);
size = MAX(size, height);
return (size);
}
static t_map *new_map(int map_size)
{
t_map *map;
if (!(map = ft_memalloc(sizeof(t_map))))
return (NULL);
map->size = map_size;
map->placement = 0;
return (map);
}
static char *fill_with_pieces(t_piece **pieces, t_map *map, char *map_str)
{
t_piece *cur;
long long pad_shape;
int pos;
int rel;
while (*pieces)
{
cur = *pieces;
pad_shape = modify_shape_to(cur, map->size, cur->position);
pos = 0;
while (pos <= map->size * map->size)
{
if ((pad_shape >> ((map->size * map->size) - pos)) & 1)
{
rel = (pos / map->size) * (map->size + 1);
rel += (pos % map->size) - 1;
if (pos % map->size == 0)
rel--;
map_str[rel] = cur->id;
}
++pos;
}
pieces++;
}
return (map_str);
}
static char *build_map_string(t_piece **pieces, t_map *map)
{
char *map_str;
int map_len;
int pos;
map_len = (map->size * map->size) + map->size;
if (!(map_str = malloc(map_len + 1)))
return (NULL);
ft_memset(map_str, '.', map_len);
map_str[map_len] = '\0';
pos = 0;
while (pos < map->size)
{
map_str[(pos * (map->size + 1)) + map->size] = '\n';
pos++;
}
return (fill_with_pieces(pieces, map, map_str));
}
char *solve(t_piece **pieces)
{
int map_size;
int solved;
t_map *map;
map_size = smallest_map(pieces);
solved = 0;
map = NULL;
while (!solved)
{
if (map)
free(map);
map = new_map(map_size);
solved = try(pieces, map);
map_size++;
}
return (build_map_string(pieces, map));
}