Patrón de secuencia de montaña

Dado un número N , la tarea es generar el patrón de secuencia piramidal que contiene N pirámides una tras otra, como se muestra en los ejemplos a continuación.
Ejemplos: 

Input: N = 3
Output:
  *    *    *
 ***  ***  ***
***************

Input: N = 4
Output: 
  *    *    *    *
 ***  ***  ***  ***
********************

Enfoque iterativo: los pasos para un enfoque iterativo para imprimir el patrón de secuencia de montaña para un número N dado :

  1. Ejecute dos bucles anidados .
  2. El lazo exterior cuidará la fila del patrón.
  3. El bucle interior cuidará la columna del patrón.
  4. Tome tres variables k1, k2 y gap que ayudan a generar un patrón.
  5. Después de imprimir la fila del patrón, actualice el valor de k1 y k2 como: 
    • k1 = k1 + brecha
    • k2 = k2 + brecha

A continuación se muestra la implementación del enfoque iterativo:
 

C++

// C++ program for the above approach
#include <iostream>
using namespace std;
 
// Function to create the mountain
// sequence pattern
void printPatt(int n)
{
    int k1 = 3;
    int k2 = 3;
    int gap = 5;
 
    // Outer loop to handle the row
    for (int i = 1; i <= 3; i++) {
 
        // Inner loop to handle the
        // Column
        for (int j = 1;
             j <= (5 * n); j++) {
 
            if (j > k2 && i < 3) {
                k2 += gap;
                k1 += gap;
            }
 
            // Condition to print the
            // star in mountain pattern
            if (j >= k1 && j <= k2) {
                cout << "*";
            }
            else {
                cout << " ";
            }
        }
 
        // Condition to adjust the value of
        // K1 and K2 for printing desire
        // Pattern
        if (i + 1 == 3) {
            k1 = 1;
            k2 = (5 * n);
        }
        else {
            k1 = 3;
            k2 = 3;
            k1--;
            k2++;
        }
        cout << endl;
    }
}
 
// Driver Code
int main()
{
    // Given Number N
    int N = 5;
 
    // Function call
    printPatt(N);
}

Java

// Java implementation of the above approach
class GFG{
 
// Function to create the mountain
// sequence pattern
static void printPatt(int n)
{
    int k1 = 3;
    int k2 = 3;
    int gap = 5;
 
    // Outer loop to handle the row
    for(int i = 1; i <= 3; i++)
    {
         
       // Inner loop to handle the
       // Column
       for(int j = 1; j <= (5 * n); j++)
       {
          if (j > k2 && i < 3)
          {
              k2 += gap;
              k1 += gap;
          }
           
          // Condition to print the
          // star in mountain pattern
          if (j >= k1 && j <= k2)
          {
              System.out.print("*");
          }
          else
          {
              System.out.print(" ");
          }
       }
        
       // Condition to adjust the value of
       // K1 and K2 for printing desire
       // Pattern
       if (i + 1 == 3)
       {
           k1 = 1;
           k2 = (5 * n);
       }
       else
       {
           k1 = 3;
           k2 = 3;
           k1--;
           k2++;
       }
       System.out.println();
    }
}
     
// Driver code
public static void main (String[] args)
{
     
    // Given Number N
    int N = 5;
 
    // Function call
    printPatt(N);
}
}
 
// This code is contributed by Pratima Pandey

Python3

# Python3 program for the above approach
 
# Function to create the mountain
# sequence pattern
def printPatt(n):
 
    k1 = 3; k2 = 3; gap = 5;
 
    # Outer loop to handle the row
    for i in range(1, 4):
 
        # Inner loop to handle the
        # Column
        for j in range(1, (5 * n) + 1):
 
            if (j > k2 and i < 3):
                k2 += gap;
                k1 += gap;
             
            # Condition to print the
            # star in mountain pattern
            if (j >= k1 and j <= k2):
                print("*", end = "");
            else:
                print(" ", end = "");
        print("\n", end = "");
             
        # Condition to adjust the value of
        # K1 and K2 for printing desire
        # Pattern
        if (i + 1 == 3):
            k1 = 1;
            k2 = (5 * n);
         
        else:
            k1 = 3;
            k2 = 3;
            k1 -= 1;
            k2 += 1;
    print(end = "");
     
# Driver Code
 
# Given Number N
N = 5;
 
# Function call
printPatt(N);
 
# This code is contributed by Code_Mech

C#

// C# implementation of the above approach
using System;
class GFG{
 
// Function to create the mountain
// sequence pattern
static void printPatt(int n)
{
    int k1 = 3;
    int k2 = 3;
    int gap = 5;
 
    // Outer loop to handle the row
    for(int i = 1; i <= 3; i++)
    {
         
        // Inner loop to handle the
        // Column
        for(int j = 1; j <= (5 * n); j++)
        {
            if (j > k2 && i < 3)
            {
                k2 += gap;
                k1 += gap;
            }
             
            // Condition to print the
            // star in mountain pattern
            if (j >= k1 && j <= k2)
            {
                Console.Write("*");
            }
            else
            {
                Console.Write(" ");
            }
        }
             
        // Condition to adjust the value of
        // K1 and K2 for printing desire
        // Pattern
        if (i + 1 == 3)
        {
            k1 = 1;
            k2 = (5 * n);
        }
        else
        {
            k1 = 3;
            k2 = 3;
            k1--;
            k2++;
        }
        Console.WriteLine();
    }
}
     
// Driver code
public static void Main (String[] args)
{
     
    // Given Number N
    int N = 5;
 
    // Function call
    printPatt(N);
}
}
 
// This code is contributed by shivanisinghss2110

Javascript

<!--  Javascript program for the above approach. -->
 
<script>
 
// Function to create the mountain
// sequence pattern
function printPatt( n)
{
    var k1 = 3;
    var k2 = 3;
    var gap = 5;
 
    // Outer loop to handle the row
    for(let i = 1; i <= 3; i++)
    {
         
        // Inner loop to handle the
        // Column
        for(let j = 1; j <= (5 * n); j++)
        {
            if (j > k2 && i < 3)
            {
                k2 += gap;
                k1 += gap;
            }
             
            // Condition to print the
            // star in mountain pattern
            if (j >= k1 && j <= k2)
            {   document.write("*");
            }
            else
            {
                document.write("  ");
            }
        }
             
        // Condition to adjust the value of
        // K1 and K2 for printing desire
        // Pattern
        if (i + 1 == 3)
        {
            k1 = 1;
            k2 = (5 * n);
        }
        else
        {
            k1 = 3;
            k2 = 3;
            k1--;
            k2++;
        }
        document.write("<br>");
    }
}
 
//Driver Code
var N=3;
printPatt(N);
 
</script>
 
<!--  This code in contributed by nirajgusain5 -->
Producción: 

  *    *    *    *    *  
 ***  ***  ***  ***  *** 
*************************

 

Complejidad de tiempo: O(N)
Enfoque recursivo: El patrón se puede generar usando Recursión . A continuación se muestran los pasos:

  1. Ejecute dos bucles anidados .
  2. El lazo exterior cuidará la fila del patrón.
  3. El bucle interior cuidará la columna del patrón.
  4. Además de estas, se necesitan las variables K1 , K2 y gap .
  5. K1, K2 cubrirán los casos en los que se va a imprimir * .
  6. Gap cubrirá los casos en los que se impriman espacios.
  7. Llame recursivamente a la función fun(i, j + 1) para manejar columnas.
  8. Llamada recursiva a la función fun(i + 1, 0) para manejar filas.

A continuación se muestra la implementación del enfoque anterior:
 

C++

// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
int k1 = 2;
int k2 = 2;
int gap = 5;
 
// Function to print pattern
// recursively
int printPattern(
    int i, int j, int n)
{
 
    // Base Case
    if (j >= n) {
        k1 = 2;
        k2 = 2;
        k1--;
        k2++;
        if (i == 2) {
            k1 = 0;
            k2 = n - 1;
        }
        return 0;
    }
 
    // Condition to check row limit
    if (i >= 3) {
        return 1;
    }
 
    // Condition for assigning gaps
    if (j > k2) {
        k1 += gap;
        k2 += gap;
    }
 
    // Conditions to print *
    if (j >= k1
            && j <= k2
        || i == 2) {
 
        cout << "*";
    }
 
    // Else print ' '
    else {
 
        cout << " ";
    }
 
    // Recursive call for columns
    if (printPattern(i, j + 1, n)
        == 1) {
        return 1;
    }
 
    cout << endl;
 
    // Recursive call for rows
    return printPattern(i + 1,
                        0, n);
}
 
// Driver Code
int main()
{
    // Given Number N
    int N = 3;
 
    // Function Call
    printPattern(0, 0, N * 5);
    return 0;
}

Java

// Java program for the
// above approach
class GFG{
 
static int k1 = 2;
static int k2 = 2;
static int gap = 5;
     
// Function to print pattern
// recursively
public static int printPattern(int i,
                               int j,
                               int n)
{      
  // Base Case
  if (j >= n)
  {
    k1 = 2;
    k2 = 2;
    k1--;
    k2++;
    if (i == 2)
    {
      k1 = 0;
      k2 = n - 1;
    }
    return 0;
  }
 
  // Condition to check
  // row limit
  if (i >= 3)
  {
    return 1;
  }
 
  // Condition for assigning gaps
  if (j > k2)
  {
    k1 += gap;
    k2 += gap;
  }
 
  // Conditions to print *
  if (j >= k1 && j <= k2 || i == 2)
  {
    System.out.print("*");
  }
 
  // Else print ' '
  else
  {
    System.out.print(" ");
  }
 
  // Recursive call for columns
  if (printPattern(i, j + 1, n) == 1)
  {
    return 1;
  }
 
  System.out.println();
 
  // Recursive call for rows
  return printPattern(i + 1, 0, n);
}
 
// Driver code
public static void main(String[] args)
{
  // Given Number N
  int N = 3;
 
  // Function Call
  printPattern(0, 0, N * 5);
}
}
 
// This code is contributed by divyeshrabadiya07

Python3

# Python3 program for the
# above approach
k1 = 2
k2 = 2
gap = 5
 
# Function to print pattern
# recursively
def printPattern(i, j, n):
   
    global k1
    global k2
    global gap
 
    # Base Case
    if(j >= n):
        k1 = 2
        k2 = 2
        k1 -= 1
        k2 += 1
        if(i == 2):
            k1 = 0
            k2 = n - 1
        return 0
 
    # Condition to check row limit
    if(i >= 3):
        return 1
 
    # Condition for assigning gaps
    if(j > k2):
        k1 += gap
        k2 += gap
 
    # Conditions to print *
    if(j >= k1 and j <= k2 or
       i == 2):
        print("*", end = "")
 
    # Else print ' '
    else:
        print(" ", end = "")
 
    # Recursive call for columns
    if(printPattern(i, j + 1, n) == 1):
        return 1
 
    print()
 
    # Recursive call for rows
    return (printPattern(i + 1, 0, n))
 
# Driver Code
 
# Given Number N
N = 3
 
# Function Call
printPattern(0, 0, N * 5)
 
#This code is contributed by avanitrachhadiya2155

C#

// C# program for the
// above approach
using System;
using System.Collections.Generic;
class GFG {
     
    static int k1 = 2;
    static int k2 = 2;
    static int gap = 5;
 
    // Function to print pattern
    // recursively
    static int printPattern(int i, int j, int n)
    {      
      // Base Case
      if (j >= n)
      {
        k1 = 2;
        k2 = 2;
        k1--;
        k2++;
        if (i == 2)
        {
          k1 = 0;
          k2 = n - 1;
        }
        return 0;
      }
      
      // Condition to check
      // row limit
      if (i >= 3)
      {
        return 1;
      }
      
      // Condition for assigning gaps
      if (j > k2)
      {
        k1 += gap;
        k2 += gap;
      }
      
      // Conditions to print *
      if (j >= k1 && j <= k2 || i == 2)
      {
        Console.Write("*");
      }
      
      // Else print ' '
      else
      {
        Console.Write(" ");
      }
      
      // Recursive call for columns
      if (printPattern(i, j + 1, n) == 1)
      {
        return 1;
      }
      
      Console.WriteLine();
      
      // Recursive call for rows
      return printPattern(i + 1, 0, n);
    } 
   
  // Driver code
  static void Main()
  {
     
      // Given Number N
      int N = 3;
      
      // Function Call
      printPattern(0, 0, N * 5);
  }
}
 
// This code is contributed by divyeshrabadiya07
Producción: 

  *    *    *  
 ***  ***  *** 
***************

 

Complejidad de tiempo: O(N)

Publicación traducida automáticamente

Artículo escrito por MohammadMudassir y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *