Ad

Looping Arrays : While Loops And 2D Arrays

Some context: This program reads lines of Stone and puts them onto the map.

The program should first ask for the number of lines of STONEs as an integer. Then, the program will scan the locations of the lines as a group of four integers in the following format:

row column length value

The row and column represent the left-most block of a horizontal line of blocks to the placed on the map. The length tells you how many stones should be in this horizontal line. In this example, assume the fourth integer to always be 1 representing a stone.

Example: CommandMeaning

0 0 5 1 Place a line of stone starting at [0][0] and ending at [0][4]. All 5 squares in the line will be set to 1 (STONE).

My issue to trying to code in the length aspect, i cant figure out the pattern:

  • also, we are only allowed to use while loops, no for loops
#define SIZE 15
#define EMPTY 0
#define STONE 1

void printMap(int map[SIZE][SIZE], int playerX);


int main (void) {
    // This line creates our 2D array called "map" and sets all
    // of the blocks in the map to EMPTY.
    int map[SIZE][SIZE] = {EMPTY};


    // This line creates out playerX variable.
    int playerX = SIZE / 2;

    printf("How many lines of stone? ");
    int linesOfStone; 
    scanf("%d", &linesOfStone);

    printf("Enter lines of stone:\n");
 
    int rowPos; 
    int columnPos; 
    int stoneLength; 
    int stoneValue; 
   
    int i = 0; 
    while (i < linesOfStone) {
        scanf("%d %d %d %d", &rowPos, &columnPos, &stoneLength, &stoneValue); 
        map[rowPos][columnPos]++; //pos for position
      
//ERROR: This was my attempt to incorporate the length aspect, i think my logic got lost along the way... 
  
            int j = 0; 
            while (j < stoneLength) {
            rowPos++; 
            j++; 
            }
    i++; 
    }

    printMap(map, playerX);

    return 0;
}

// Print out the contents of the map array. Then print out the player line
// which will depends on the playerX variable.
void printMap(int map[SIZE][SIZE], int playerX) {
    
    // Print values from the map array.
    int i = 0;
    while (i < SIZE) {
        int j = 0;
        while (j < SIZE) {
            printf("%d ", map[i][j]);
            j++;
        }
        printf("\n");
        i++;
    }    
    
    // Print the player line.
    i = 0;
    while (i < player
Ad

Answer

Replace your second while loop with this one:

for (int j=0; j < stoneLength; j++)  // Iterate over all affected map tiles
    map[rowPos + j][columnPos] = 1;  // Make this map tile STONE

This set all map tiles from [rowPos][columnPos] up to [rowPos + stoneLength - 1][columnPos]

Ad
source: stackoverflow.com
Ad