中級 0件解決済み 正答率0%

Zigzag Wave Pattern

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

このチャレンジで学べること

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

問題

翻訳を表示

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.

制約

1 ≤ width ≤ 80, 2 ≤ height ≤ 20

例

例 1
入力:
width = 9
height = 3

期待される出力:
expected = ["*   *   *", " * * * *", "  *   *"]
入力:
long long width = 9;
long long height = 3;

期待される出力:
std::vector<std::string> expected = {"*   *   *", " * * * *", "  *   *"};
入力:
long width = 9;
long height = 3;

期待される出力:
string[] expected = new string[] {"*   *   *", " * * * *", "  *   *"};

解説

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

例 2
入力:
width = 5
height = 2

期待される出力:
expected = ["* * *", " * *"]
入力:
long long width = 5;
long long height = 2;

期待される出力:
std::vector<std::string> expected = {"* * *", " * *"};
入力:
long width = 5;
long height = 2;

期待される出力:
string[] expected = new string[] {"* * *", " * *"};

解説

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

解き方のヒント

まずは自分で考えてから、ヒントを 1 つずつ開いてみましょう。

ヒント 1

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

ヒント 2

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

ヒント 3

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

目安の計算量

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

参考資料

この課題はCodeUtility用に調整されています。上記の説明と制約に従ってください。

ランキング

全体ランキング

コーダーごとのいちばん良い合格解答です。速く、メモリが少なく、評価が高い解答ほど上位になります。

まだ合格した解答はありません。解いて 1 位になりましょう。

他の人の解答から学ぶ

コミュニティの解答

まだ公開された解答がありません。この課題を解いて最初の解答を共有しましょう。