Imprimir string en el patrón más ‘+’ en la array

Dada una string, imprímala dentro de una array de tal manera que se forme un ‘más’.

Ejemplos: 

Input: TOP
Output:  
X    T    X
T    O    P
X    P    X

Input: FEVER
Output:
X    X    F    X    X
X    X    E    X    X
F    E    V    E    R
X    X    E    X    X
X    X    R    X    X

Acercarse: 

La idea es sencilla. Primero podemos acceder a cada elemento de la array y convertirlo en ‘X’. Luego, insertaremos los caracteres de la string en la fila central y en la columna central de la array. Por ejemplo, tenemos una string de longitud 5. Entonces necesitaremos una array (5X5) para ella.

Para acceder a la columna central de la array, el índice de columna se hace constante y es igual a (n/2), donde n es la longitud de la string. El índice de fila irá de 0 a (n-1) para ello. 
Para acceder a la fila del medio, el índice de la fila se hará constante e igual a (n/2) y el índice de la columna irá de 0 a (n-1).

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

C++

// CPP program to print the
// string in 'plus' pattern
#include <bits/stdc++.h>
#define max 100
using namespace std;
 
// Function to make a cross in the matrix
void carveCross(string str)
{
    int n = str.length();
    if (n % 2 == 0)
    { 
        /* As, it is not possible to make
        the cross exactly in the middle of
        the matrix with an even length string.*/
        cout << "Not possible. Please enter "
             << "odd length string.\n";
    }
    else {
 
        // declaring a 2D array i.e a matrix
        char arr[max][max];
        int m = n / 2;
 
        /* Now, we will fill all the
        elements of the array with 'X'*/
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                arr[i][j] = 'X';
            }
        }
 
        /* Now, we will place the characters
        of the string in the matrix, such
        that a cross is formed in it.*/
        for (int i = 0; i < n; i++)
        {
            /* here the characters of the
            string will be added in the
            middle column of our array.*/
            arr[i][m] = str[i];
        }
         
        for (int i = 0; i < n; i++)
        {
            // here the characters of the
            // string will be added in the
            // middle row of our array.
            arr[m][i] = str[i];
        }
 
        /* Now finally, we will print
        the array*/
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                cout << arr[i][j] << " ";
            }
            cout << "\n";
        }
    }
}
 
// driver code
int main()
{
    string str = "PICTURE";
    carveCross(str);
    return 0;
}

Java

// Java program to print the
// string in 'plus' pattern
class GFG {
static final int max = 100;
 
// Function to make a cross in the matrix
static void carveCross(String str) {
    int n = str.length();
    if (n % 2 == 0) {
         
        // As, it is not possible to make
        // the cross exactly in the middle of
        // the matrix with an even length string.
        System.out.print("Not possible. Please enter "
                             + "odd length string.\n");
    }
    else {
 
        // declaring a 2D array i.e a matrix
        char arr[][] = new char[max][max];
        int m = n / 2;
 
        // Now, we will fill all the
        // elements of the array with 'X'
        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < n; j++)
            {
                arr[i][j] = 'X';
        }
    }
 
    // Now, we will place the characters
    // of the string in the matrix, such
    // that a cross is formed in it.
    for (int i = 0; i < n; i++) {
         
        // here the characters of the
        // string will be added in the
        // middle column of our array.
        arr[i][m] = str.charAt(i);
    }
 
    for (int i = 0; i < n; i++) {
         
        // here the characters of the
        // string will be added in the
        // middle row of our array.
        arr[m][i] = str.charAt(i);
    }
 
    // Now finally, we will print
    // the array
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < n; j++)
        {
            System.out.print(arr[i][j] + " ");
        }
        System.out.print("\n");
    }
    }
}
 
// Driver code
public static void main(String[] args) {
    String str = "PICTURE";
    carveCross(str);
}
}
// This code is contributed by Anant Agarwal.

Python 3

# Python 3 program to print the
# string in 'plus' pattern
max = 100
 
# Function to make a cross
# in the matrix
def carveCross(str):
     
    n = len(str)
    if (n % 2 == 0) :
     
        ''' As, it is not possible to make
        the cross exactly in the middle of
        the matrix with an even length string.'''
        print("Not possible. Please enter "
            , "odd length string.\n")
     
    else :
 
        # declaring a 2D array i.e a matrix
        arr = [[ False for x in range(max)]
                       for y in range(max)]
        m = n // 2
 
        ''' Now, we will fill all the
        elements of the array with 'X'''
        for i in range( n) :
            for j in range(n) :
                arr[i][j] = 'X'
 
        '''Now, we will place the characters
        of the string in the matrix, such
        that a cross is formed in it.'''
        for i in range(n):
         
            ''' here the characters of the
            string will be added in the
            middle column of our array.'''
            arr[i][m] = str[i]
         
        for i in range(n):
         
            # here the characters of the
            # string will be added in the
            # middle row of our array.
            arr[m][i] = str[i]
 
        # Now finally, we will print
        # the array
        for i in range(n):
            for j in range(n):
                print( arr[i][j] , end=" ")
             
            print()
 
# Driver Code
if __name__ == "__main__":
    str = "PICTURE"
    carveCross(str)
 
# This code is contributed
# by ChitraNayal

C#

// C# program to print the
// string in 'plus' pattern
using System;
class GFG {
static  int max = 100;
   
// Function to make a cross in the matrix
static void carveCross(String str) {
    int n = str.Length;
    if (n % 2 == 0) {
           
        // As, it is not possible to make
        // the cross exactly in the middle of
        // the matrix with an even length string.
        Console.Write("Not possible. Please enter "
                            + "odd length string.");
    } 
    else {
   
        // declaring a 2D array i.e a matrix
        char [,]arr = new char[max,max];
        int m = n / 2;
   
        // Now, we will fill all the
        // elements of the array with 'X'
        for (int i = 0; i < n; i++) 
        {
            for (int j = 0; j < n; j++) 
            {
                arr[i,j] = 'X';
        }
    }
   
    // Now, we will place the characters
    // of the string in the matrix, such
    // that a cross is formed in it.
    for (int i = 0; i < n; i++) {
           
        // here the characters of the
        // string will be added in the
        // middle column of our array.
        arr[i,m] = str[i];
    }
   
    for (int i = 0; i < n; i++) {
           
        // here the characters of the
        // string will be added in the
        // middle row of our array.
        arr[m,i] = str[i];
    }
   
    // Now finally, we will print
    // the array
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < n; j++)
        {
            Console.Write(arr[i,j] + " ");
        }
           Console.WriteLine();
    }
    }
}
   
// Driver code
public static void Main() {
    string str = "PICTURE";
    carveCross(str);
}
}
// This code is contributed by vt_m.

PHP

<?php
// PHP program to print the string
// in 'plus' pattern
 
// Function to make a cross
// in the matrix
function carveCross($str)
{
    $n = strlen($str);
    if ($n % 2 == 0)
    {
        /* As, it is not possible to make
        the cross exactly in the middle of
        the matrix with an even length string.*/
        echo ("Not possible. Please enter ");
        echo( "odd length string.\n");
    }
    else
    {
 
        // declaring a 2D array i.e a matrix
        $arr = array();
        $m = $n / 2;
 
        /* Now, we will fill all the
        elements of the array with 'X'*/
        for ($i = 0; $i < $n; $i++)
        {
            for ($j = 0; $j < $n; $j++)
            {
                $arr[$i][$j] = 'X';
            }
        }
 
        /* Now, we will place the characters
        of the string in the matrix, such
        that a cross is formed in it.*/
        for ($i = 0; $i < $n; $i++)
        {
            /* here the characters of the
            string will be added in the
            middle column of our array.*/
            $arr[$i][$m] = $str[$i];
        }
         
        for ($i = 0; $i < $n; $i++)
        {
            // here the characters of the
            // string will be added in the
            // middle row of our array.
            $arr[$m][$i] = $str[$i];
        }
 
        /* Now finally, we will print
        the array*/
        for ($i = 0; $i < $n; $i++)
        {
            for ($j = 0; $j < $n; $j++)
            {
                echo ($arr[$i][$j] . " " );
            }
            echo ("\n");
        }
    }
}
 
// Driver Code
$str = "PICTURE";
carveCross($str);
     
// This code is contributed
// by Shivi_Aggarwal
?>

Javascript

<script>
 
// JavaScript program to print the
// string in 'plus' pattern
 
const max = 100
 
// Function to make a cross in the matrix
function carveCross(str)
{
    let n = str.length;
    if (n % 2 == 0)
    {
        /* As, it is not possible to make
        the cross exactly in the middle of
        the matrix with an even length string.*/
        document.write("Not possible. Please enter odd length string.","</br>");
    }
    else {
 
        // declaring a 2D array i.e a matrix
        let arr = new Array(max);
        for(let i=0;i<max;i++){
            arr[i] = new Array(max);
        }
        let m = Math.floor(n / 2);
 
        /* Now, we will fill all the
        elements of the array with 'X'*/
        for (let i = 0; i < n; i++) {
            for (let j = 0; j < n; j++) {
                arr[i][j] = 'X';
            }
        }
 
        /* Now, we will place the characters
        of the string in the matrix, such
        that a cross is formed in it.*/
        for (let i = 0; i < n; i++)
        {
            /* here the characters of the
            string will be added in the
            middle column of our array.*/
            arr[i][m] = str[i];
        }
         
        for(let i = 0; i < n; i++)
        {
            // here the characters of the
            // string will be added in the
            // middle row of our array.
            arr[m][i] = str[i];
        }
 
        /* Now finally, we will print
        the array*/
        for (let i = 0; i < n; i++) {
            for (let j = 0; j < n; j++) {
                document.write(arr[i][j] + " ");
            }
            document.write("</br>");
        }
    }
}
 
// driver code
 
let str = "PICTURE";
carveCross(str);
 
// This code is contributed by shinjanpatra
</script>

Producción: 

X X X P X X X 
X X X I X X X 
X X X C X X X 
P I C T U R E 
X X X U X X X 
X X X R X X X 
X X X E X X X

Complejidad de tiempo: O(n 2 )
Espacio auxiliar: O(MAX 2 ) donde MAX es una constante definida

Este artículo es una contribución de Aarti_Rathi . Si te gusta GeeksforGeeks y te gustaría contribuir, también puedes escribir un artículo usando write.geeksforgeeks.org o enviar tu artículo por correo a review-team@geeksforgeeks.org. Vea su artículo que aparece en la página principal de GeeksforGeeks y ayude a otros Geeks. 

Publicación traducida automáticamente

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