Imprime un patrón sin usar ningún loop

Dado un número n, imprime siguiendo un patrón sin usar ningún bucle.

Ejemplos: 

Input: n = 16
Output: 16, 11, 6, 1, -4, 1, 6, 11, 16

Input: n = 10
Output: 10, 5, 0, 5, 10

Básicamente, primero reducimos 5 uno por uno hasta llegar a un negativo o 0. Después de llegar a 0 o negativo, sumamos uno 5 hasta llegar a n.
Fuente: pregunta de la entrevista de Microsoft.

Le recomendamos encarecidamente que haga clic aquí y lo practique antes de pasar a la solución.

La idea es usar la recursividad. Es una pregunta interesante para probar por su cuenta. 
A continuación se muestra el Código. El código usa una variable indicadora para indicar si nos estamos moviendo hacia 0 o si nos estamos moviendo hacia atrás a n. 

C++

// C++ program to print pattern that first reduces 5 one
// by one, then adds 5. Without any loop
#include <iostream>
using namespace std;
 
// Recursive function to print the pattern.
// n indicates input value
// m indicates current value to be printed
// flag indicates whether we need to add 5 or
// subtract 5. Initially flag is true.
void printPattern(int n, int m, bool flag)
{
    // Print m.
    cout << m << " ";
     
    // If we are moving back toward the n and
    // we have reached there, then we are done
    if (flag == false && n ==m)
        return;
     
    // If we are moving toward 0 or negative.
    if (flag)
    {
    // If m is greater, then 5, recur with true flag
    if (m-5 > 0)
        printPattern(n, m-5, true);
    else // recur with false flag
        printPattern(n, m-5, false);
    }
    else // If flag is false.
        printPattern(n, m+5, false);
}
 
// Recursive function to print the pattern
// variance where m is the input int32 value
void PrintPattern(int m)
{
    if (m > 0)
    {
        cout << m << '\n';
        PrintPattern(m - 5);
    }
 
    cout << m << '\n';
}
 
// Driver Program
int main()
{
    int n = 16;
    //printPattern(n, n, true);
    PrintPattern(n);
    return 0;
}

Java

// Java program to print pattern that first reduces 5 one
// by one, then adds 5. Without any loop
import java.io.*;
 
class GFG {
     
    // Recursive function to print the pattern.
    // n indicates input value
    // m indicates current value to be printed
    // flag indicates whether we need to add 5 or
    // subtract 5. Initially flag is true.
    static void printPattern(int n, int m, boolean flag)
    {
         
        // Print m.
        System.out.print(m + " ");
 
        // If we are moving back toward the n and
        // we have reached there, then we are done
        if (flag == false && n == m)
            return;
 
        // If we are moving toward 0 or negative.
        if (flag) {
 
            // If m is greater, then 5, recur with
            // true flag
            if (m - 5 > 0)
                printPattern(n, m - 5, true);
 
            else // recur with false flag
                printPattern(n, m - 5, false);
        }
 
        else // If flag is false.
            printPattern(n, m + 5, false);
    }
 
    // Driver Program
    public static void main(String[] args)
    {
        int n = 16;
        printPattern(n, n, true);
    }
}
// This code is contributed by vt_m

Python3

# Python program to print pattern
# that first reduces 5 one by one,
# then adds 5. Without any loop.
 
# Recursive function to print
# the pattern.n indicates
# input value m indicates
# current value to be printed
# flag indicates whether we
# need to add 5 or subtract 5.
# Initially flag is True.
def printPattern(n, m, flag):
     
    # Print m.
    print(m)
     
    # If we are moving back
    # toward the n and we
    # have reached there,
    # then we are done
    if flag == False and n == m:
        return
    # If we are moving
    # toward 0 or negative.
    if flag:
    # If m is greater, then 5,
    # recur with true flag
        if m - 5 > 0:
            printPattern(n, m - 5, True)
        else: # recur with false flag
            printPattern(n, m - 5, False)
    else: # If flag is false.
        printPattern(n, m + 5, False)
 
# Driver Code
n = 16
printPattern(n, n, True)
 
# This code is contributed
# by HrushikeshChoudhary

C#

// C# program to print pattern that first reduces 5 one
// by one, then adds 5. Without any loop
using System;
 
class GFG {
     
    // Recursive function to print the pattern.
    // n indicates input value
    // m indicates current value to be printed
    // flag indicates whether we need to add 5 or
    // subtract 5. Initially flag is true.
    static void printPattern(int n, int m, bool flag)
    {
         
        // Print m.
        Console.Write(m + " ");
 
        // If we are moving back toward the n and
        // we have reached there, then we are done
        if (flag == false && n == m)
            return;
 
        // If we are moving toward 0 or negative.
        if (flag) {
 
            // If m is greater, then 5, recur with
            // true flag
            if (m - 5 > 0)
                printPattern(n, m - 5, true);
 
            else // recur with false flag
                printPattern(n, m - 5, false);
        }
 
        else // If flag is false.
            printPattern(n, m + 5, false);
    }
 
    // Driver Program
    public static void Main()
    {
        int n = 16;
        printPattern(n, n, true);
    }
}
// This code is contributed by vt_m

PHP

<?php
// PHP program to print pattern
// that first reduces 5 one by one,
// then adds 5. Without any loop
 
// Recursive function to print
// the pattern. n indicates input
// value m indicates current value
// to be printed flag indicates whether
// we need to add 5 or subtract 5.
// Initially flag is true.
function printPattern($n, $m, $flag)
{
    // Print m.
    echo $m ," ";
     
    // If we are moving back
    // toward the n and we
    // have reached there,
    // then we are done
    if ($flag == false && $n == $m)
        return;
     
    // If we are moving
    // toward 0 or negative.
    if ($flag)
    {
    // If m is greater, then 5,
    // recur with true flag
    if ($m - 5 > 0)
        printPattern($n, $m - 5, true);
     
    // recur with false flag
    else
        printPattern($n, $m - 5, false);
    }
     
    // If flag is false.
    else
        printPattern($n, $m + 5, false);
}
 
// Driver Code
$n = 16;
printPattern($n, $n, true);
 
// This code is contributed by m_kit
?>

Javascript

<script>
 
// Javascript program to print pattern that
// first reduces 5 one by one, then adds 5.
// Without any loop
 
// Recursive function to print the pattern.
// n indicates input value m indicates current
// value to be printed flag indicates whether
// we need to add 5 or subtract 5. Initially
// flag is true.
function printPattern(n, m, flag)
{
     
    // Print m.
    document.write(m + " ");
 
    // If we are moving back toward the n and
    // we have reached there, then we are done
    if (flag == false && n == m)
        return;
 
    // If we are moving toward 0 or negative.
    if (flag)
    {
         
        // If m is greater, then 5, recur with
        // true flag
        if (m - 5 > 0)
            printPattern(n, m - 5, true);
             
        // Recur with false flag
        else
            printPattern(n, m - 5, false);
    }
     
    // If flag is false.
    else
        printPattern(n, m + 5, false);
}
 
// Driver code
let n = 16;
printPattern(n, n, true);
 
// This code is contributed by divyeshrabadiya07
 
</script>

Producción : 

16, 11, 6, 1, -4, 1, 6, 11, 16

¿Cómo imprimir el patrón anterior sin ninguna variable adicional ni bucle?  
El programa anterior funciona bien e imprime lo deseado pero usa variables adicionales. Podemos usar dos sentencias de impresión. El primero antes de la llamada recursiva que imprime toda la secuencia decreciente. El segundo después de la llamada recursiva para imprimir secuencia creciente.

A continuación se muestra la implementación de la idea.

C++

// C++ program to print pattern that first reduces 5 one
// by one, then adds 5. Without any loop an extra variable.
#include <iostream>
using namespace std;
 
// Recursive function to print the pattern without any extra
// variable
void printPattern(int n)
{
    // Base case (When n becomes 0 or negative)
    if (n ==0 || n<0)
    {
        cout << n << " ";
        return;
    }
     
    // First print decreasing order
    cout << n << " ";
    printPattern(n-5);
 
    // Then print increasing order
    cout << n << " ";
}
 
// Driver Program
int main()
{
    int n = 16;
    printPattern(n);
    return 0;
}

Java

// Java program to print pattern that first
// reduces 5 one by one, then adds 5.
// Without any loop an extra variable.
 
import java.io.*;
 
class GFG {
     
    // Recursive function to print the
    // pattern without any extra variable
    static void printPattern(int n)
    {
         
        // Base case (When n becomes 0 or
        // negative)
        if (n == 0 || n < 0) {
             
            System.out.print(n + " ");
             
            return;
        }
 
        // First print decreasing order
        System.out.print(n + " ");
         
        printPattern(n - 5);
 
        // Then print increasing order
        System.out.print(n + " ");
    }
 
    // Driver Program
    public static void main(String[] args)
    {
         
        int n = 16;
         
        printPattern(n);
    }
}
 
// This code is contributed by vt_m

Python3

# Python3 program to print pattern that
# first reduces 5 one by one, then adds 5.
# Without any loop an extra variable.
 
# Recursive function to print the pattern
# without any extra variable
def printPattern(n):
 
    # Base case (When n becomes 0 or negative)
    if (n == 0 or n < 0):
        print(n, end = ", ")
        return
     
    # First print decreasing order
    print(n, end = ", ")
    printPattern(n - 5)
 
    # Then print increasing order
    print(n, end = ", ")
 
# Driver Code
n = 16
printPattern(n)
 
# This code is contributed by
# Mohit kumar 29

C#

// C# program to print pattern that first
// reduces 5 one by one, then adds 5.
// Without any loop an extra variable.
 
using System;
 
class GFG {
     
    // Recursive function to print the
    // pattern without any extra variable
    static void printPattern(int n)
    {
         
        // Base case (When n becomes 0 or
        // negative)
        if (n == 0 || n < 0) {
             
            Console.Write(n + " ");
             
            return;
        }
 
        // First print decreasing order
        Console.Write(n + " ");
         
        printPattern(n - 5);
 
        // Then print increasing order
        Console.Write(n + " ");
    }
 
    // Driver Program
    public static void Main()
    {
         
        int n = 16;
         
        printPattern(n);
    }
}
 
// This code is contributed by vt_m

PHP

<?php
// PHP program to print pattern
// that first reduces 5 one
// by one, then adds 5. Without
// any loop an extra variable.
 
// Recursive function to print the
// pattern without any extra variable
function printPattern( $n)
{
     
    // Base case (When n becomes
    // 0 or negative)
    if ($n == 0 or $n < 0)
    {
        echo $n , " ";
        return;
    }
     
    // First print decreasing order
    echo $n , " ";
    printPattern($n-5);
 
    // Then print increasing order
    echo $n , " ";
}
 
    // Driver Code
    $n = 16;
    printPattern($n);
 
// This code is contributed by anuj_67.
?>

Javascript

<script>
    // Javascript program to print pattern that first reduces 5 one
    // by one, then adds 5. Without any loop an extra variable.
     
    // Recursive function to print the pattern without any extra
    // variable
    function printPattern(n)
    {
     
        // Base case (When n becomes 0 or negative)
        if (n == 0 || n < 0)
        {
            document.write(n + ", ");
            return;
        }
 
        // First print decreasing order
        document.write(n + ", ");
        printPattern(n - 5);
 
        // Then print increasing order
        document.write(n + ", ");
    }
     
    let n = 16;
    printPattern(n);
     
    // This code is contributed by suresh07.
</script>

Producción: 

16, 11, 6, 1, -4, 1, 6, 11, 16

Gracias a AKSHAY RATHORE por sugerir la solución anterior.
Este artículo es una contribución de Gautham . Escriba comentarios si encuentra algo incorrecto o si desea compartir más información sobre el tema tratado anteriormente.
 

Publicación traducida automáticamente

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