Programa para imprimir una string en forma de zigzag vertical

Dada una string , S de tamaño N , y un número de filas R , la tarea es imprimir la string dada en forma de zigzag vertical con respecto al número dado de filas, como se muestra en los ejemplos.

Ejemplos:

Entrada: S = “123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz”, R = 9
Salida:

Entrada: S = «¡Atención lectores! ¡No dejen de aprender! ¡Feliz aprendizaje!», R = 12
Salida:

Enfoque: para imprimir los caracteres línea por línea, la idea es encontrar el intervalo entre las columnas principales y el valor del paso para las columnas intermedias para imprimir los espacios hasta que se alcance el último carácter de la string. Siga los pasos a continuación para resolver este problema:

  • Inicialice un intervalo variable como 2*R-2 para almacenar el espacio entre las columnas principales.
  • Iterar en el rango [0, R-1] usando la variable i
    • Inicialice un paso variable como intervalo-2*i para almacenar valores de paso para cada fila.
    • Iterar en el rango [i, N-1] usando la variable j , incrementando j por intervalo en cada iteración,
      • Imprime el carácter, S[j] .
      • Si el valor del paso se encuentra en el rango [1, intervalo-1] y paso+j<N , entonces imprima (intervalo-Ri) el número de espacios, luego imprima s[j+paso] y finalmente imprima (i-1) espacios.
      • De lo contrario, imprima (intervalo-R) el número de espacios.
    • Imprime nueva línea después de cada iteración del bucle exterior.

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;
 
// Function to print any string
// in zigzag fashion
void zigzag(string s, int rows)
{
    // Store the gap between the major columns
    int interval = 2 * rows - 2;
 
    // Traverse through rows
    for (int i = 0; i < rows; i++) {
 
        // Store the step value for each row
        int step = interval - 2 * i;
 
        // Iterate in the range [1, N-1]
        for (int j = i; j < s.length(); j = j + interval) {
 
            // Print the character
            cout << s[j];
            if (step > 0 && step < interval
                && step + j < s.length()) {
 
                // Print the spaces before character
                // s[j+step]
                for (int k = 0; k < (interval - rows - i);
                     k++)
                    cout << " ";
 
                // Print the character
                cout << s[j + step];
 
                // Print the spaces after character
                // after s[j+step]
                for (int k = 0; k < i - 1; k++)
                    cout << " ";
            }
            else {
 
                // Print the spaces for first and last rows
                for (int k = 0; k < (interval - rows); k++)
                    cout << " ";
            }
        }
        cout << endl;
    }
}
 
// Driver Code
int main()
{
    // Given Input
    string s = "123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefgh"
               "ijklmnopqrstuvwxyz";
    int rows = 9;
 
    // Function Call
    zigzag(s, rows);
}

Java

// Java program for the above approach
 
public class GFG{
 
// Function to print any string
// in zigzag fashion
static void zigzag(String s, int rows)
{
     
    // Store the gap between the major columns
    int interval = 2 * rows - 2;
 
    // Traverse through rows
    for(int i = 0; i < rows; i++)
    {
         
        // Store the step value for each row
        int step = interval - 2 * i;
 
        // Iterate in the range [1, N-1]
        for(int j = i; j < s.length(); j = j + interval)
        {
             
            // Print the character
            System.out.print(s.charAt(j));
            if (step > 0 && step < interval &&
                step + j < s.length())
            {
                 
                // Print the spaces before character
                // s[j+step]
                for(int k = 0; k < (interval - rows - i); k++)
                    System.out.print(" ");
 
                // Print the character
                System.out.print(s.charAt(j + step));
 
                // Print the spaces after character
                // after s[j+step]
                for(int k = 0; k < i - 1; k++)
                    System.out.print(" ");
            }
            else
            {
                 
                // Print the spaces for first and last rows
                for(int k = 0; k < (interval - rows); k++)
                    System.out.print(" ");
            }
        }
        System.out.println();
    }
}
 
// Driver Code
public static void main(String args[])
{
     
    // Given Input
    String s = "123456789ABCDEFGHIJKLM" +
               "NOPQRSTUVWXYZabcdefghi" +
               "jklmnopqrstuvwxyz";
    int rows = 9;
 
    // Function Call
    zigzag(s, rows);
}
}
 
// This code is contributed by SoumikMondal

Python3

# Python3 program for the above approach
 
# Function to print any string
# in zigzag fashion
def zigzag(s, rows):
     
    # Store the gap between the major columns
    interval = 2 * rows - 2
 
    # Traverse through rows
    for i in range(rows):
         
        # Store the step value for each row
        step = interval - 2 * i
 
        # Iterate in the range [1, N-1]
        for j in range(i, len(s), interval):
             
            # Print the character
            print(s[j], end = "")
             
            if (step > 0 and step < interval and
                         step + j < len(s)):
 
                # Print the spaces before character
                # s[j+step]
                for k in range((interval - rows - i)):
                    print(end = " ")
 
                # Print the character
                print(s[j + step], end = "")
 
                # Print the spaces after character
                # after s[j+step]
                for k in range(i - 1):
                    print(end = " ")
            else:
 
                # Print the spaces for first and
                # last rows
                for k in range(interval - rows):
                    print(end = " ")
                     
        print()
 
# Driver Code
if __name__ == '__main__':
     
    # Given Input
    s = "123456789ABCDEFGHIJKL"\
        "MNOPQRSTUVWXYZabcdefghi"\
        "jklmnopqrstuvwxyz"
    rows = 9
 
    # Function Call
    zigzag(s, rows)
 
# This code is contributed by mohit kumar 29

C#

// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
// Function to print any string
// in zigzag fashion
static void zigzag(string s, int rows)
{
     
    // Store the gap between the major columns
    int interval = 2 * rows - 2;
 
    // Traverse through rows
    for(int i = 0; i < rows; i++)
    {
         
        // Store the step value for each row
        int step = interval - 2 * i;
 
        // Iterate in the range [1, N-1]
        for(int j = i; j < s.Length; j = j + interval)
        {
             
            // Print the character
            Console.Write(s[j]);
            if (step > 0 && step < interval &&
                step + j < s.Length)
            {
                 
                // Print the spaces before character
                // s[j+step]
                for(int k = 0; k < (interval - rows - i); k++)
                    Console.Write(" ");
 
                // Print the character
                Console.Write(s[j + step]);
 
                // Print the spaces after character
                // after s[j+step]
                for(int k = 0; k < i - 1; k++)
                    Console.Write(" ");
            }
            else
            {
                 
                // Print the spaces for first and last rows
                for(int k = 0; k < (interval - rows); k++)
                    Console.Write(" ");
            }
        }
        Console.WriteLine();
    }
}
 
// Driver Code
public static void Main()
{
     
    // Given Input
    string s = "123456789ABCDEFGHIJKLM" +
               "NOPQRSTUVWXYZabcdefghi" +
               "jklmnopqrstuvwxyz";
    int rows = 9;
 
    // Function Call
    zigzag(s, rows);
}
}
 
// This code is contributed by SURENDRA_GANGWAR

Javascript

<script>
 
// JavaScript program for the above approach
 
// Function to print any string
// in zigzag fashion
function zigzag(s,rows)
{
    // Store the gap between the major columns
    let interval = 2 * rows - 2;
  
    // Traverse through rows
    for(let i = 0; i < rows; i++)
    {
          
        // Store the step value for each row
        let step = interval - 2 * i;
  
        // Iterate in the range [1, N-1]
        for(let j = i; j < s.length; j = j + interval)
        {
              
            // Print the character
            document.write(s[j]);
            if (step > 0 && step < interval &&
                step + j < s.length)
            {
                  
                // Print the spaces before character
                // s[j+step]
                for(let k = 0; k < (interval - rows - i); k++)
                    document.write("  ");
  
                // Print the character
                document.write(s[j + step]);
  
                // Print the spaces after character
                // after s[j+step]
                for(let k = 0; k < i - 1; k++)
                    document.write("  ");
            }
            else
            {
                  
                // Print the spaces for first and last rows
                for(let k = 0; k < (interval - rows); k++)
                    document.write("  ");
            }
        }
        document.write("<br>");
    }
}
 
// Driver Code
// Given Input
let s = "123456789ABCDEFGHIJKLM" +
    "NOPQRSTUVWXYZabcdefghi" +
    "jklmnopqrstuvwxyz";
let rows = 9;
 
// Function Call
zigzag(s, rows);
 
 
// This code is contributed by patel2127
 
</script>
Producción

1       H       X       n       
2      GI      WY      mo       
3     F J     V Z     l p       
4    E  K    U  a    k  q       
5   D   L   T   b   j   r   z   
6  C    M  S    c  i    s  y    
7 B     N R     d h     t x     
8A      OQ      eg      uw      
9       P       f       v       

Complejidad de Tiempo: O(R 2 *N)
Espacio Auxiliar: O(1)

Publicación traducida automáticamente

Artículo escrito por vysandeep3 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 *