satyacode
Background
Back to js-loops

11-rangoli-pattern.js

JavaScript
1/**
2 * 🎨 Priya ki Diwali Rangoli
3 *
4 * Priya Diwali pe rangoli banati hai. Uska pattern ek diamond shape mein
5 * hota hai stars (*) ka. Tu usse help kar pattern generate karne mein!
6 *
7 * Rules (use nested for loops):
8 *   - Input n determines the size of the diamond
9 *   - The diamond has 2n - 1 rows total
10 *   - Row i (1-indexed) of the top half has i stars
11 *   - Row i of the bottom half mirrors the top
12 *   - Stars are separated by a single space
13 *   - Each row has leading spaces for center alignment
14 *   - The widest row has n stars: "* * * ... *" (2n-1 chars wide)
15 *   - No trailing spaces on any row
16 *
17 * Pattern for n=3:
18 *       *
19 *     * *
20 *   * * *
21 *     * *
22 *       *
23 *
24 * (Each row is a string in the returned array)
25 *
26 * Validation:
27 *   - Agar n positive integer nahi hai (0, negative, decimal, non-number),
28 *     return empty array []
29 *
30 * @param {number} n - Size of the diamond (number of stars in the widest row)
31 * @returns {string[]} Array of strings forming the diamond pattern
32 *
33 * @example
34 *   rangoli(1) // => ["*"]
35 *   rangoli(2) // => [" *", "* *", " *"]
36 *   rangoli(3) // => ["  *", " * *", "* * *", " * *", "  *"]
37 */
38export function rangoli(n) {
39  if(n <= 0 || typeof n !== "number" || Number.isNaN(n) || !Number.isInteger(n)){
40    return []
41  }
42  let diamond = []
43  for(let i = 1; i <= n; i++){
44    let row = ""
45    
46    for(let s = 0; s < n-i; s++){
47      row += " ";
48    }
49    for(let j= 0; j< i; j++){
50      row += "*";
51      if(j < i -1){
52        row += " "
53      }
54    }
55    diamond.push(row)
56  } 
57
58for(let i = n - 1; i >= 1; i--){
59    let row = ""
60    
61    for(let s = 0; s < n-i; s++){
62      row += " ";
63    }
64    for(let j= 0; j< i; j++){
65      row += "*";
66      if(j < i -1){
67        row +=" "
68      }
69    }
70    diamond.push(row)
71  } 
72
73return diamond
74}
75