ปานกลาง 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

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 กรุณาทำตามคำชี้แจงและข้อจำกัดด้านบน

คำตอบที่ผ่านดีที่สุดของแต่ละคน คำตอบที่เร็วกว่า ใช้หน่วยความจำน้อยกว่า และได้คะแนนดีกว่าจะอยู่ด้านบน

ยังไม่มีคำตอบที่ผ่าน แก้โจทย์นี้แล้วคว้าอันดับหนึ่งไปเลย

เรียนรู้จากคนอื่น

แนวทางจากชุมชน

ยังไม่มีวิธีทำที่เผยแพร่ ลองแก้โจทย์นี้เพื่อแชร์วิธีแรก