Tutte le sfide
Media 0 risolte 0% di accettazione

Zigzag Wave Pattern

Draw a zigzag line of stars that bounces between the top and bottom rows of a grid.

Cosa imparerai

  • Turn a repeating motion into a formula with mod
  • Fill a grid column by column
  • Trim trailing spaces and keep empty rows

Problema

Mostra traduzione

Picture a grid with height rows and width columns, both numbered from 0. A line of stars starts in the top-left cell and moves one column right at every step, going one row down each time until it reaches the bottom row and then one row up each time until it reaches the top row, again and again. Exactly: let P = 2(height − 1) and p = c mod P. Column c has its only star in row p when p < height, and in row P − p otherwise. All other cells are spaces.

Implement zigzag_wave_pattern(width, height).

Input

width: The number of columns.

height: The number of rows.

Output

Return height strings from top to bottom with trailing spaces removed. A row that ends up with no star is an empty string.

Vincoli

1 ≤ width ≤ 80, 2 ≤ height ≤ 20

Esempi

Esempio 1
Input:
width = 9
height = 3

Output atteso:
expected = ["*   *   *", " * * * *", "  *   *"]
Input:
long long width = 9;
long long height = 3;

Output atteso:
std::vector<std::string> expected = {"*   *   *", " * * * *", "  *   *"};
Input:
long width = 9;
long height = 3;

Output atteso:
string[] expected = new string[] {"*   *   *", " * * * *", "  *   *"};

Spiegazione

P = 4, so columns 0 to 8 use rows 0, 1, 2, 1, 0, 1, 2, 1, 0: ["* * *", " * * * *", " * *"].

Esempio 2
Input:
width = 5
height = 2

Output atteso:
expected = ["* * *", " * *"]
Input:
long long width = 5;
long long height = 2;

Output atteso:
std::vector<std::string> expected = {"* * *", " * *"};
Input:
long width = 5;
long height = 2;

Output atteso:
string[] expected = new string[] {"* * *", " * *"};

Spiegazione

With two rows the star alternates top and bottom: ["* * *", " * *"].

Come affrontarlo

Prova prima da solo, poi apri un suggerimento alla volta.

Suggerimento 1

The movement repeats every 2(height − 1) columns.

Suggerimento 2

Inside one period the row goes down from 0 to height − 1 and back up.

Suggerimento 3

It can be easier to fill a 2D grid of spaces first and then turn each row into a string.

Complessità attesa

O(width * height) time, O(width * height) extra space

Riferimenti

Questa sfida è adattata per CodeUtility. Segui la traccia e i vincoli sopra.

La migliore soluzione superata di ogni programmatore. Le più veloci, leggere e meglio valutate stanno in alto.

Ancora nessuna soluzione superata. Risolvila e prendi il primo posto.

Impara dagli altri

Soluzioni della community

Nessuna soluzione pubblicata. Risolvi questa sfida per condividere la prima.