Benutzer-Werkzeuge

Webseiten-Werkzeuge


spielplatz:student:42:rusg1

Dies ist eine alte Version des Dokuments!


/* */ /* */ /* ::: :::::::: */ /* Untitled-1.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dkrkalic dkrkalic@student.42.fr +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2026/02/04 15:54:56 by dkrkalic #+# #+# */ /* Updated: 2026/02/05 23:07:26 by dkrkalic ### ########.fr */ /* */ /* */

#include <unistd.h>

#define SIZE 4

void ft_putstr(char *str) {

while (*str)
	write(1, str++, 1);

}

void ft_putchar(char c) {

write(1, &c, 1);

}

int parse_clues(char *input, int clues[16]) {

int	i;
i = 0;
while (*input && i < 16)
{
	if (*input == ' ')
		input++;
	else if (*input >= '1' && *input <= '4')
	{
		clues[i] = *input - '0';
		i++;
		input++;
	}
	else
		return (0);
}
if (i != 16 || *input)
	return (0);
return (1);

}

int is_unique(int grid[SIZE][SIZE], int row, int col, int num) {

int	i;
i = 0;
while (i < SIZE)
{
	if (grid[row][i] == num || grid[i][col] == num)
		return (0);
	i++;
}
return (1);

}

int check_line(int grid[SIZE][SIZE], int clues[16], int dir, int idx) {

int	max;
int	vis;
int	i;
max = 0;
vis = 0;
i = (dir % 2 == 0) ? 0 : SIZE - 1;
while (i >= 0 && i < SIZE)
{
	if ((dir < 2 && grid[idx][i] > max) || (dir > 1 && grid[i][idx] > max))
	{
		max = (dir < 2) ? grid[idx][i] : grid[i][idx];
		vis++;
	}
	i += (dir % 2 == 0) ? 1 : -1;
}
if (dir == 0)
	return (vis == clues[8 + idx]);
if (dir == 1)
	return (vis == clues[12 + idx]);
if (dir == 2)
	return (vis == clues[idx]);
return (vis == clues[4 + idx]);

}

int check_all(int grid[SIZE][SIZE], int clues[16]) {

int	i;
i = 0;
while (i < SIZE)
{
	if (!check_line(grid, clues, 0, i) || !check_line(grid, clues, 1, i)
		|| !check_line(grid, clues, 2, i) || !check_line(grid, clues, 3, i))
		return (0);
	i++;
}
return (1);

}

int solve(int grid[SIZE][SIZE], int clues[16], int pos) {

int	row;
int	col;
int	n;
if (pos == SIZE * SIZE)
	return (check_all(grid, clues));
row = pos / SIZE;
col = pos % SIZE;
n = 1;
while (n <= SIZE)
{
	if (is_unique(grid, row, col, n))
	{
		grid[row][col] = n;
		if (solve(grid, clues, pos + 1))
			return (1);
		grid[row][col] = 0;
	}
	n++;
}
return (0);

}

void print_grid(int grid[SIZE][SIZE]) {

int	r;
int	c;
r = 0;
while (r < SIZE)
{
	c = 0;
	while (c < SIZE)
	{
		ft_putchar(grid[r][c] + '0');
		if (c < SIZE - 1)
			ft_putchar(' ');
		c++;
	}
	ft_putchar('\n');
	r++;
}

}

int main(int argc, char **argv) {

int grid[SIZE][SIZE];
int clues[16];
int r;
int c;
r = 0;
while (r < SIZE)
{
	c = 0;
	while (c < SIZE)
	{
		grid[r][c] = 0;
		c++;
	}
	r++;
}
if (argc != 2 || !parse_clues(argv[1], clues))
	ft_putstr("Error\n");
else if (solve(grid, clues, 0))
	print_grid(grid);
else
	ft_putstr("Error\n");
return (0);

}

/volume1/web/dokuwiki/data/attic/spielplatz/student/42/rusg1.1771091041.txt.gz · Zuletzt geändert: 2026/02/14 18:44 von 89.246.128.70