Ir ao conteúdo
  • Cadastre-se

C Labirinto - Divisão Recursiva Exception


Conixs

Posts recomendados

Boa noite, estava tentando implementar um programa que seja capaz de gerar de forma recursiva um labirinto, como descrito pelo Recursive Division Method.

No entanto, quando chamo a recursividade está me dando FLOATING POINT EXCEPTION.

Poderiam me dar uma dica nesse problema?

 

Aqui está o meu código:

#include <stdio.h>
#define HORIZONTAL 1
#define VERTICAL 2
 
const int ROWS = 5;
const int COLS = 5;
 
int main()
{
    int chamber[ROWS][COLS];
    for (int i = 0; i < ROWS; i++) {
        for (int j = 0; j < COLS; j++) {
            chamber[i][j] = 0;
        }
    }
    addOuterWalls(chamber, sizeof(chamber)/sizeof(chamber[0]), sizeof(chamber[0])/sizeof(chamber[0][0]));
    addEntrance(chamber, sizeof(chamber)/sizeof(chamber[0]));
    addExit(chamber, sizeof(chamber)/sizeof(chamber[0]));
    addInnerWalls(chamber, 1, 1, sizeof(chamber)/sizeof(chamber[0]) - 1, sizeof(chamber[0])/sizeof(chamber[0][0]) - 1);
    
    for (int i = 0; i < ROWS; i++) {
        for (int j = 0; j < COLS; j++) {
            printf("%d ", chamber[i][j]);
        }
        printf("\n");
    }
 
    return 0;
}

void addOuterWalls(int chamber[ROWS][COLS], int rows, int cols)
{
    for (int i = 0; i < rows; i++) {
        if (i == 0 || i == (rows - 1)) {
            for (int j = 0; j < cols; j++) {
                chamber[i][j] = 1;
            }
        } else {
            chamber[i][0] = 1;
            chamber[i][cols - 1] = 1;
        }
    }
}

void addEntrance(int chamber[ROWS][COLS], int rows)
{
    int random = 0 + (rand() % ((rows - 1) - 0) + 1);
    chamber[0][random] = 2;
}

void addExit(int chamber[ROWS][COLS], int rows)
{
    int random = 0 + (rand() % ((rows - 1) - 0) + 1);
    chamber[rows - 1][random] = 2;
}
 
void addInnerWalls(int chamber[ROWS][COLS], int startRow, int startCol, int endRow, int endCol)
{
    int orientation, randR, randC, i, j, randPR, randPC;
   
    if (endRow < 2 || endCol < 2) {
        return;
    }
   
    if (endCol < endRow) {
        orientation = HORIZONTAL;
    } else if (endCol > endRow) {
        orientation = VERTICAL;
    } else {
        orientation = 0 + (rand() % (1 - 0) + 1) == 0 ? HORIZONTAL : VERTICAL;
    }
   
    randR = startRow + (rand() % ((endRow - 1) - startRow) + 1);
    randC = startCol + (rand() % ((endCol - 1) - startCol) + 1);
   
    if (orientation == HORIZONTAL) {
        for(i = startRow; i < endRow; i++) {
            if(i == randR) {
                randPR = startRow + (rand() % ((endRow - 1) - startRow) + 1);
                for(j = startCol; j < endCol; j++) {
                    if(j == randPR) {
                        chamber[i][j] = 8;
                    } else {
                        chamber[i][j] = 1;
                    }
                }
            }
        }
        addInnerWalls(chamber, startRow, startCol, randR - 1, endCol);
        addInnerWalls(chamber, randR + 1, startCol, endRow, endCol);
    } else {
        for(j = startCol; j < endCol; j++) {
            if(j == randC) {
                randPC = startCol + (rand() % ((endCol - 1) - startCol) + 1);
                for(i = startRow; i < endRow; i++) {
                    if(i == randPC) {
                        chamber[i][j] = 8;
                    } else {
                        chamber[i][j] = 1;
                    }
                }
            }
        }
        addInnerWalls(chamber, startRow, startCol, randC - 1, randC - 1);
        addInnerWalls(chamber, randC + 1, randC + 1, endRow, endCol);
    }
   
}

Grato!

  • Amei 1
Link para o comentário
Compartilhar em outros sites

@Conixs    seu código está bom , apenas você precisa colocar as funções antes da main , ou se você quiser deixar elas lá embaixo mesmo , então faça a declaração delas no início antes da main , rodei o código mas ele não apresentou nenhum outro erro não ,  então seu código com algumas modificações  ficaria assim  :

#include <stdio.h>
#include <time.h>
#include <conio.h>
#include <windows.h>
#include <iostream>
#define HORIZONTAL 1
#define VERTICAL 2
using namespace std;
const int linhas = 5;
const int colunas = 5;
/*             0     1    2     3   4      5      6      7         8  */
typedef enum{BLACK,BLUE,GREEN,CYAN,RED,MAGENTA,BROWN,LIGHTGRAY,DARKGRAY,   /* nome das cores */
LIGHTBLUE,LIGHTGREEN,LIGHTCYAN,LIGHTRED,LIGHTMAGENTA,YELLOW,WHITE} COLORS;
/*  9         10         11        12        13         14    15 */

static int __BACKGROUND = 1/*BLUE*/;   /*pode ser o numero ou o nome da cor*/
static int __FOREGROUND = LIGHTGRAY;

void textcolor (int letras, int fundo){/*para mudar a cor de fundo mude o background*/
    __FOREGROUND = letras;
    __BACKGROUND = fundo;
    SetConsoleTextAttribute (GetStdHandle (STD_OUTPUT_HANDLE),
    letras + (__BACKGROUND << 4));
}
                  /* y = linha de 0 a 24 , x = coluna de 0 a 80 */
void gotoxy(int x, int y){/*imprimir na linha e coluna desejada */
  COORD c;
  c.X = x;
  c.Y = y;
  SetConsoleCursorPosition (GetStdHandle(STD_OUTPUT_HANDLE), c);
}
void addOuterWalls(int chamber[linhas][colunas], int rows, int cols){
    for (int i = 0; i < rows; i++){
        if (i == 0 || i == (rows - 1)){
            for (int j = 0; j < cols; j++){
                chamber[i][j] = 1;
            }
        }
        else {
            chamber[i][0] = 1;
            chamber[i][cols - 1] = 1;
        }
    }
}
void addEntrance(int chamber[linhas][colunas], int rows){
    int random = 0 + (rand() % ((rows - 1) - 0) + 1);
    chamber[0][random] = 2;
}
void addExit(int chamber[linhas][colunas], int rows){
    int random = 0 + (rand() % ((rows - 1) - 0) + 1);
    chamber[rows - 1][random] = 2;
}
void addInnerWalls(int chamber[linhas][colunas], int startRow, int startCol, int endRow, int endCol){
    int orientation, randR, randC, i, j, randPR, randPC;
    if (endRow < 2 || endCol < 2) {
        return;
    }
    if (endCol < endRow){
        orientation = HORIZONTAL;
    }
    else{
        if (endCol > endRow){
            orientation = VERTICAL;
        }
        else{
            orientation = 0 + (rand() % (1 - 0) + 1) == 0 ? HORIZONTAL : VERTICAL;
        }
    }
    randR = startRow + (rand() % ((endRow - 1) - startRow) + 1);
    randC = startCol + (rand() % ((endCol - 1) - startCol) + 1);
    if (orientation == HORIZONTAL){
        for(i = startRow; i < endRow; i++){
            if(i == randR) {
                randPR = startRow + (rand() % ((endRow - 1) - startRow) + 1);
                for(j = startCol; j < endCol; j++){
                    if(j == randPR){
                        chamber[i][j] = 8;
                    }
                    else {
                        chamber[i][j] = 1;
                    }
                }
            }
        }
        addInnerWalls(chamber, startRow, startCol, randR - 1, endCol);
        addInnerWalls(chamber, randR + 1, startCol, endRow, endCol);
    }
    else {
        for(j = startCol; j < endCol; j++){
            if(j == randC){
                randPC = startCol + (rand() % ((endCol - 1) - startCol) + 1);
                for(i = startRow; i < endRow; i++){
                    if(i == randPC){
                        chamber[i][j] = 8;
                    }
                    else {
                        chamber[i][j] = 1;
                    }
                }
            }
        }
        addInnerWalls(chamber, startRow, startCol, randC - 1, randC - 1);
        addInnerWalls(chamber, randC + 1, randC + 1, endRow, endCol);
    }
}
int main(){
    int camara[linhas][colunas],i,j,L=10;
    for(i = 0; i < linhas; i++){
        for(j = 0; j < colunas; j++){
            camara[i][j] = 0;
        }
    }
    addOuterWalls(camara, sizeof(camara)/sizeof(camara[0]),
                  sizeof(camara[0])/sizeof(camara[0][0]));
    addEntrance(camara, sizeof(camara)/sizeof(camara[0]));
    addExit(camara, sizeof(camara)/sizeof(camara[0]));
    addInnerWalls(camara, 1, 1, sizeof(camara)/sizeof(camara[0]) - 1,
                  sizeof(camara[0])/sizeof(camara[0]) - 1);
    textcolor(14,0);
    for(i = 0; i < linhas; i++){
        gotoxy(25,L);
        for(j = 0; j < colunas; j++){
            cout<<camara[i][j]<<" ";
        }
        L++;
        cout<<endl;
    }
    textcolor(7,0);
    cout<<"\n\n"<<endl;
    return 0;
}

 

Link para o comentário
Compartilhar em outros sites

@devair1010, no seu código quando você chama a função addInnerWalls o último parametro está errado:

addInnerWalls(camara, 1, 1, sizeof(camara)/sizeof(camara[0]) - 1, sizeof(camara[0])/sizeof(camara[0]) - 1);

Deveria ser:

addInnerWalls(camara, 1, 1, sizeof(camara)/sizeof(camara[0]) - 1, sizeof(camara[0])/sizeof(camara[0][0]) - 1);

Com essa mudança, o código roda, mas não imprimi nada!

 

Obrigado.

  • Amei 1
Link para o comentário
Compartilhar em outros sites

@Conixs Olá. Pelo q vi aqui, um dos problemas em seu código é q o fluxo do programa não chega até o final da função addInnerWalls. Faz o teste aí p ver

Seria interessante repensar a lógica dessa função

adicionado 17 minutos depois

Tem um outro ponto q gostaria de frizar:

Na operação onde está sendo usado operador ternário o resultado vai ser sempre 2, ou seja, VERTICAL:

orientation = 0 + (rand() % (1 - 0) + 1) == 0 ? HORIZONTAL : VERTICAL;

O q você está fazendo basicamente é isso:

orientation = (rand() % 1 + 1) == 0 ? HORIZONTAL : VERTICAL;

rand() % 1 vai sempre resultar em 0, somado com 1 => 1. Ou seja, a condição resultará em falso e aí o valor atribuído a orientation será sempre 2 (VERTICAL)

Link para o comentário
Compartilhar em outros sites

@Conixs      na função addInnerWalls  ele está imprimindo o que tem na matriz  .    e para gerar um número entre zero e hum , você pode gerar números  entre zero e dez e dividir esse número por dez , assim você terá o número entre zero e hum como resultado .    aqui um exemplo para obter um número entre zero e hum   :

#include <iostream>
#include <ctime>
int main(){
    int a;
    float b;
    srand(time(NULL));
    a=rand()%10;
    b=(float)a/10;
    printf("valor de a= %d  \n",a);
    printf("valor de b= %.1f\n",b);
    return 0;
}

 

Link para o comentário
Compartilhar em outros sites

@devair1010 Mas perceba o seguinte no código dele: Ele está definindo a orientação nessa operação.

No início do código ele criou duas constantes com a diretiva define:

#define HORIZONTAL 1
#define VERTICAL 2

Essas constantes ele usa nesse operador ternário:

orientation = 0 + (rand() % (1 - 0) + 1) == 0 ? HORIZONTAL : VERTICAL;

Corrigindo o código dele nessa operação, ficaria assim:

orientation = (rand() % 2) == 0 ? HORIZONTAL : VERTICAL;

Logo. Se o número sorteado for o 0, a condição é verdadeira e a variável orientation recebe o valor HORIZONTAL

Se o nº sorteado for o 1, a condição returna falsa e aí seria VERTICAL.

Entendeu em q contexto ele está procurando gerar esses números?

com relação ao erro na lógica dele comentei acima

Obs: Se fosse para gerar números aleatórios entre 0 e 1 aí seu código estaria correto. Mas no exercício ele quer q seja gerado ou o número 0 ou o número 1

 

ele procurou corrigir a lógica nessa operação dessa forma:

0 + (rand() % (1 - 0 + 1))

Como ele postou acima.

Esse cálculo, de maneira resumida, ficaria assim:

(rand() % 2)

Creio q ele tenha se expressado de forma errônea ao falar números entre 0 e 1

 

Link para o comentário
Compartilhar em outros sites

Crie uma conta ou entre para comentar

Você precisa ser um usuário para fazer um comentário

Criar uma conta

Crie uma nova conta em nossa comunidade. É fácil!

Crie uma nova conta

Entrar

Já tem uma conta? Faça o login.

Entrar agora

Sobre o Clube do Hardware

No ar desde 1996, o Clube do Hardware é uma das maiores, mais antigas e mais respeitadas comunidades sobre tecnologia do Brasil. Leia mais

Direitos autorais

Não permitimos a cópia ou reprodução do conteúdo do nosso site, fórum, newsletters e redes sociais, mesmo citando-se a fonte. Leia mais

×
×
  • Criar novo...