Posted on by Kalkicode
Code Pattern

Print zigzag string pattern

The Zigzag String Pattern is a pattern that arranges characters in a string in a zigzag shape. This pattern can be useful for various applications, such as displaying text in a visually appealing manner or encoding messages. In this article, we will explore the problem statement, provide a suitable example, discuss the algorithm and pseudocode, and explain the resultant output along with the time complexity of the code.

Problem Statement

The task is to print a given string in a zigzag pattern based on the specified height. The height determines the number of rows in the zigzag pattern. Characters from the string are placed in the pattern in a zigzag manner, moving both vertically and horizontally. The pattern starts from the top-left corner and moves down until the specified height is reached, then it changes direction and moves upwards until the top-right corner is reached.

Example

Let's consider the string "HELLO" and a height of 4.

H       O
  E   L
    L

In this example, the string "HELLO" is printed in a zigzag pattern with a height of 4. The characters are placed in a zigzag manner, moving downwards and then upwards to create the pattern.

Algorithm

The following algorithm outlines the steps to print the zigzag string pattern:

  1. Check if the height is less than or equal to zero or the length of the string is zero. If true, return.
  2. Check if the height is equal to 1. If true, print the string as is and return.
  3. Check if the height is greater than or equal to the length of the string. If true, print each character in a separate row, increasing the row number.
  4. Create a 2D character array of size [height][length] to store the zigzag pattern.
  5. Initialize variables: direction = 1 (downward), point = 0 (row position).
  6. Iterate through each character in the string:
    • Store the character in the corresponding row (point) and column (character index) of the record array.
    • Update the direction based on the current row position (point).
    • If the direction is downward, increment the row position (point). Otherwise, decrement it.
  7. Print the resulting zigzag pattern by iterating through each row and column of the record array.

Pseudocode

Here's the pseudocode representing the algorithm:

space(size):
    for i from 0 to size:
        print " "

wave_pattern(text, n, height):
    if height <= 0 or n == 0:
        return
    else if height == 1:
        print "\n" + text
        return
    else if height >= n:
        for i from 0 to n:
            space(i)
            print text[i] + "\n"
        return

    record[height][n]
    direction = 1
    point = 0

    for i from 0 to height:
        for j from 0 to n:
            record[i][j] = ' '

    for i from 0 to n:
        record[point][i] = text[i]

        if point == 0:
            direction = 1
        else if point + 1 == height:
            direction = 0

        if direction == 1:
            point++
        else:
            point--

    for i from 0 to height:
        for j from 0 to n:
            print " " + record[i][j]

        print "\n"

Code Solution

// C Program 
// Print zigzag string pattern
#include <stdio.h>
#include <string.h>

// Display space
void space(int size)
{
    for (int i = 0; i < size; ++i)
    {
        printf(" ");
    }
}
void wave_pattern(char *text, int n, int height)
{
    if (height <= 0 || n == 0)
    {
        return;
    }
    else if (height == 1)
    {
        printf("\n %s", text);
    }
    else if (height >= n)
    {
        for (int i = 0; i < n; ++i)
        {
            space(i);
            printf("%c\n", text[i]);
        }
    }
    else
    {
        printf("\n\n Given height : %d \n\n", height);
        char record[height][n];
        int direction = 1;
        int point = 0;
        // Set default value 
        for (int i = 0; i < height; ++i)
        {
            for (int j = 0; j < n; ++j)
            {
                record[i][j] = ' ';
            }
        }
        for (int i = 0; i < n; ++i)
        {
            record[point][i] = text[i];
            if (point == 0)
            {
                // Down move
                direction = 1;
            }
            else if (point + 1 == height)
            {
                // Up move
                direction = 0;
            }
            if (direction == 1)
            {
                // Increase row point
                point++;
            }
            else
            {
                // Decrease the row point
                point--;
            }
        }
        // Display calculated result
        for (int i = 0; i < height; i++)
        {
            for (int j = 0; j < n; j++)
            {
                printf(" %c", record[i][j]);
            }
            // Add new line
            printf("\n");
        }
    }
}
int main()
{
    char *text = "ABCDEFGHIGKLMNOPQRSTUVWXYZ";
    int n = strlen(text);
    // Test Cases
    wave_pattern(text, n, 4);
    wave_pattern(text, n, 5);
    return 0;
}

input

 Given height : 4

 A           G           M           S           Y
   B       F   H       L   N       R   T       X   Z
     C   E       I   K       O   Q       U   W
       D           G           P           V


 Given height : 5

 A               I               Q               Y
   B           H   G           P   R           X   Z
     C       G       K       O       S       W
       D   F           L   N           T   V
         E               M               U
/*
    Java Program for
    Print zigzag string pattern
*/
public class WavePatterns
{
    // Display space
    public void space(int size)
    {
        for (int i = 0; i < size; ++i)
        {
            System.out.print(" ");
        }
    }
    public void wavePattern(String text, int n, int height)
    {
        if (height <= 0 || n == 0)
        {
            return;
        }
        else if (height == 1)
        {
            System.out.print("\n " + text);
        }
        else if (height >= n)
        {
            for (int i = 0; i < n; ++i)
            {
                space(i);
                System.out.print(" " + text.charAt(i) + "\n");
            }
        }
        else
        {
            // Display given height
            System.out.print("\n\n Given height : " + height + " \n\n");
            // Auxiliary space to store result
            char[][] record = new char[height][n];
            // Direction indicator Up or down
            boolean direction = true;

            int point = 0;
            // Set default value 
            for (int i = 0; i < height; ++i)
            {
                for (int j = 0; j < n; ++j)
                {
                    record[i][j] = ' ';
                }
            }
            for (int i = 0; i < n; ++i)
            {
                record[point][i] = text.charAt(i);
                if (point == 0)
                {
                    // Down move
                    direction = true;
                }
                else if (point + 1 == height)
                {
                    // Up move
                    direction = false;
                }
                if (direction == true)
                {
                    // Increase row point
                    point++;
                }
                else
                {
                    // Decrease the row point
                    point--;
                }
            }
            // Display calculated result
            for (int i = 0; i < height; i++)
            {
                for (int j = 0; j < n; j++)
                {
                    System.out.print(" " + record[i][j]);
                }
                // Add new line
                System.out.print("\n");
            }
        }
    }
    public static void main(String[] args)
    {
        WavePatterns task = new WavePatterns();
        String text = "ABCDEFGHIGKLMNOPQRSTUVWXYZ";
        int n = text.length();
        // Test Cases
        task.wavePattern(text, n, 4);
        task.wavePattern(text, n, 5);
    }
}

input

 Given height : 4

 A           G           M           S           Y
   B       F   H       L   N       R   T       X   Z
     C   E       I   K       O   Q       U   W
       D           G           P           V


 Given height : 5

 A               I               Q               Y
   B           H   G           P   R           X   Z
     C       G       K       O       S       W
       D   F           L   N           T   V
         E               M               U
// Include header file
#include <iostream>
#include <string>

using namespace std;
/*
    C++ Program for
    Print zigzag string pattern
*/
class WavePatterns
{
	public:
		// Display space
		void space(int size)
		{
			for (int i = 0; i < size; ++i)
			{
				cout << " ";
			}
		}
	void wavePattern(string text, int n, int height)
	{
		if (height <= 0 || n == 0)
		{
			return;
		}
		else if (height == 1)
		{
			cout << "\n " << text;
		}
		else if (height >= n)
		{
			for (int i = 0; i < n; ++i)
			{
				this->space(i);
				cout << " " << text[i] << "\n";
			}
		}
		else
		{
			// Display given height
			cout << "\n\n Given height : " << height << " \n\n";
			// Auxiliary space to store result
			char record[height][n];
			// Direction indicator Up or down
			bool direction = true;
			int point = 0;
			// Set default value 
			for (int i = 0; i < height; ++i)
			{
				for (int j = 0; j < n; ++j)
				{
					record[i][j] = ' ';
				}
			}
			for (int i = 0; i < n; ++i)
			{
				record[point][i] = text[i];
				if (point == 0)
				{
					// Down move
					direction = true;
				}
				else if (point + 1 == height)
				{
					// Up move
					direction = false;
				}
				if (direction == true)
				{
					// Increase row point
					point++;
				}
				else
				{
					// Decrease the row point
					point--;
				}
			}
			// Display calculated result
			for (int i = 0; i < height; i++)
			{
				for (int j = 0; j < n; j++)
				{
					cout << " " << record[i][j];
				}
				// Add new line
				cout << "\n";
			}
		}
	}
};
int main()
{
	WavePatterns *task = new WavePatterns();
	string text = "ABCDEFGHIGKLMNOPQRSTUVWXYZ";
	int n = text.length();
	// Test Cases
	task->wavePattern(text, n, 4);
	task->wavePattern(text, n, 5);
	return 0;
}

input

 Given height : 4

 A           G           M           S           Y
   B       F   H       L   N       R   T       X   Z
     C   E       I   K       O   Q       U   W
       D           G           P           V


 Given height : 5

 A               I               Q               Y
   B           H   G           P   R           X   Z
     C       G       K       O       S       W
       D   F           L   N           T   V
         E               M               U
// Include namespace system
using System;
/*
    Csharp Program for
    Print zigzag string pattern
*/
public class WavePatterns
{
	// Display space
	public void space(int size)
	{
		for (int i = 0; i < size; ++i)
		{
			Console.Write(" ");
		}
	}
	public void wavePattern(String text, int n, int height)
	{
		if (height <= 0 || n == 0)
		{
			return;
		}
		else if (height == 1)
		{
			Console.Write("\n " + text);
		}
		else if (height >= n)
		{
			for (int i = 0; i < n; ++i)
			{
				this.space(i);
				Console.Write(" " + text[i] + "\n");
			}
		}
		else
		{
			// Display given height
			Console.Write("\n\n Given height : " + height + " \n\n");
			// Auxiliary space to store result
			char[,] record = new char[height,n];
			// Direction indicator Up or down
			Boolean direction = true;
			int point = 0;
			// Set default value 
			for (int i = 0; i < height; ++i)
			{
				for (int j = 0; j < n; ++j)
				{
					record[i,j] = ' ';
				}
			}
			for (int i = 0; i < n; ++i)
			{
				record[point,i] = text[i];
				if (point == 0)
				{
					// Down move
					direction = true;
				}
				else if (point + 1 == height)
				{
					// Up move
					direction = false;
				}
				if (direction == true)
				{
					// Increase row point
					point++;
				}
				else
				{
					// Decrease the row point
					point--;
				}
			}
			// Display calculated result
			for (int i = 0; i < height; i++)
			{
				for (int j = 0; j < n; j++)
				{
					Console.Write(" " + record[i,j]);
				}
				// Add new line
				Console.Write("\n");
			}
		}
	}
	public static void Main(String[] args)
	{
		WavePatterns task = new WavePatterns();
		String text = "ABCDEFGHIGKLMNOPQRSTUVWXYZ";
		int n = text.Length;
		// Test Cases
		task.wavePattern(text, n, 4);
		task.wavePattern(text, n, 5);
	}
}

input

 Given height : 4

 A           G           M           S           Y
   B       F   H       L   N       R   T       X   Z
     C   E       I   K       O   Q       U   W
       D           G           P           V


 Given height : 5

 A               I               Q               Y
   B           H   G           P   R           X   Z
     C       G       K       O       S       W
       D   F           L   N           T   V
         E               M               U
<?php
/*
    Php Program for
    Print zigzag string pattern
*/
class WavePatterns
{
	// Display space
	public	function space($size)
	{
		for ($i = 0; $i < $size; ++$i)
		{
			echo(" ");
		}
	}
	public	function wavePattern($text, $n, $height)
	{
		if ($height <= 0 || $n == 0)
		{
			return;
		}
		else if ($height == 1)
		{
			echo("\n ".$text);
		}
		else if ($height >= $n)
		{
			for ($i = 0; $i < $n; ++$i)
			{
				$this->space($i);
				echo(" ".$text[$i]."\n");
			}
		}
		else
		{
			// Display given height
			echo("\n\n Given height : ".$height.
				" \n\n");
			// Auxiliary space to store result
			$record = array_fill(0, $n, array_fill(0, $height, ' '));
			// Direction indicator Up or down
			$direction = true;
			$point = 0;
			// Set default value 
			for ($i = 0; $i < $height; ++$i)
			{
				for ($j = 0; $j < $n; ++$j)
				{
					$record[$i][$j] = ' ';
				}
			}
			for ($i = 0; $i < $n; ++$i)
			{
				$record[$point][$i] = $text[$i];
				if ($point == 0)
				{
					// Down move
					$direction = true;
				}
				else if ($point + 1 == $height)
				{
					// Up move
					$direction = false;
				}
				if ($direction == true)
				{
					// Increase row point
					$point++;
				}
				else
				{
					// Decrease the row point
					$point--;
				}
			}
			// Display calculated result
			for ($i = 0; $i < $height; $i++)
			{
				for ($j = 0; $j < $n; $j++)
				{
					echo(" ".$record[$i][$j]);
				}
				// Add new line
				echo("\n");
			}
		}
	}
}

function main()
{
	$task = new WavePatterns();
	$text = "ABCDEFGHIGKLMNOPQRSTUVWXYZ";
	$n = strlen($text);
	// Test Cases
	$task->wavePattern($text, $n, 4);
	$task->wavePattern($text, $n, 5);
}
main();

input

 Given height : 4

 A           G           M           S           Y
   B       F   H       L   N       R   T       X   Z
     C   E       I   K       O   Q       U   W
       D           G           P           V


 Given height : 5

 A               I               Q               Y
   B           H   G           P   R           X   Z
     C       G       K       O       S       W
       D   F           L   N           T   V
         E               M               U
/*
    Node JS Program for
    Print zigzag string pattern
*/
class WavePatterns
{
	// Display space
	space(size)
	{
		for (var i = 0; i < size; ++i)
		{
			process.stdout.write(" ");
		}
	}
	wavePattern(text, n, height)
	{
		if (height <= 0 || n == 0)
		{
			return;
		}
		else if (height == 1)
		{
			process.stdout.write("\n " + text);
		}
		else if (height >= n)
		{
			for (var i = 0; i < n; ++i)
			{
				this.space(i);
				process.stdout.write(" " + text.charAt(i) + "\n");
			}
		}
		else
		{
			// Display given height
			process.stdout.write("\n\n Given height : " + height + " \n\n");
			// Auxiliary space to store result
			var record = Array(height).fill(' ').map(() => new Array(n).fill(' '));
			// Direction indicator Up or down
			var direction = true;
			var point = 0;
			// Set default value 
			for (var i = 0; i < height; ++i)
			{
				for (var j = 0; j < n; ++j)
				{
					record[i][j] = ' ';
				}
			}
			for (var i = 0; i < n; ++i)
			{
				record[point][i] = text.charAt(i);
				if (point == 0)
				{
					// Down move
					direction = true;
				}
				else if (point + 1 == height)
				{
					// Up move
					direction = false;
				}
				if (direction == true)
				{
					// Increase row point
					point++;
				}
				else
				{
					// Decrease the row point
					point--;
				}
			}
			// Display calculated result
			for (var i = 0; i < height; i++)
			{
				for (var j = 0; j < n; j++)
				{
					process.stdout.write(" " + record[i][j]);
				}
				// Add new line
				process.stdout.write("\n");
			}
		}
	}
}

function main()
{
	var task = new WavePatterns();
	var text = "ABCDEFGHIGKLMNOPQRSTUVWXYZ";
	var n = text.length;
	// Test Cases
	task.wavePattern(text, n, 4);
	task.wavePattern(text, n, 5);
}
main();

input

 Given height : 4

 A           G           M           S           Y
   B       F   H       L   N       R   T       X   Z
     C   E       I   K       O   Q       U   W
       D           G           P           V


 Given height : 5

 A               I               Q               Y
   B           H   G           P   R           X   Z
     C       G       K       O       S       W
       D   F           L   N           T   V
         E               M               U
#    Python 3 Program for
#    Print zigzag string pattern
class WavePatterns :
	#  Display space
	def space(self, size) :
		i = 0
		while (i < size) :
			print(" ", end = "")
			i += 1
		
	
	def wavePattern(self, text, n, height) :
		if (height <= 0 or n == 0) :
			return
		elif (height == 1) :
			print("\n ", text, end = "")
		elif (height >= n) :
			i = 0
			while (i < n) :
				self.space(i)
				print(" ", text[i] )
				i += 1
			
		else :
			#  Display given height
			print("\n\n Given height : ", height ," \n")
			#  Auxiliary space to store result
			record = [[ ' '] * (n) for _ in range(height) ]
			#  Direction indicator Up or down
			direction = True
			point = 0
			i = 0
			#  Set default value 
			while (i < height) :
				j = 0
				while (j < n) :
					record[i][j] = ' '
					j += 1
				
				i += 1
			
			i = 0
			while (i < n) :
				record[point][i] = text[i]
				if (point == 0) :
					#  Down move
					direction = True
				elif (point + 1 == height) :
					#  Up move
					direction = False
				
				if (direction == True) :
					#  Increase row point
					point += 1
				else :
					#  Decrease the row point
					point -= 1
				
				i += 1
			
			i = 0
			#  Display calculated result
			while (i < height) :
				j = 0
				while (j < n) :
					print(" ", record[i][j], end = "")
					j += 1
				
				#  Add new line
				print(end = "\n")
				i += 1
			
		
	

def main() :
	task = WavePatterns()
	text = "ABCDEFGHIGKLMNOPQRSTUVWXYZ"
	n = len(text)
	#  Test Cases
	task.wavePattern(text, n, 4)
	task.wavePattern(text, n, 5)

if __name__ == "__main__": main()

input

 Given height :  4

  A                 G                 M                 S                 Y
     B           F     H           L     N           R     T           X     Z
        C     E           I     K           O     Q           U     W
           D                 G                 P                 V


 Given height :  5

  A                       I                       Q                       Y
     B                 H     G                 P     R                 X     Z
        C           G           K           O           S           W
           D     F                 L     N                 T     V
              E                       M                       U
#    Ruby Program for
#    Print zigzag string pattern
class WavePatterns 
	#  Display space
	def space(size) 
		i = 0
		while (i < size) 
			print(" ")
			i += 1
		end

	end

	def wavePattern(text, n, height) 
		if (height <= 0 || n == 0) 
			return
		elsif (height == 1) 
			print("\n ", text)
		elsif (height >= n) 
			i = 0
			while (i < n) 
				self.space(i)
				print(" ", text[i] ,"\n")
				i += 1
			end

		else
 
			#  Display given height
			print("\n\n Given height : ", height ," \n\n")
			#  Auxiliary space to store result
			record = Array.new(height) {Array.new(n) { ' '}}
			#  Direction indicator Up or down
			direction = true
			point = 0
			i = 0
			#  Set default value 
			while (i < height) 
				j = 0
				while (j < n) 
					record[i][j] = ' '
					j += 1
				end

				i += 1
			end

			i = 0
			while (i < n) 
				record[point][i] = text[i]
				if (point == 0) 
					#  Down move
					direction = true
				elsif (point + 1 == height) 
					#  Up move
					direction = false
				end

				if (direction == true) 
					#  Increase row point
					point += 1
				else
 
					#  Decrease the row point
					point -= 1
				end

				i += 1
			end

			i = 0
			#  Display calculated result
			while (i < height) 
				j = 0
				while (j < n) 
					print(" ", record[i][j])
					j += 1
				end

				#  Add new line
				print("\n")
				i += 1
			end

		end

	end

end

def main() 
	task = WavePatterns.new()
	text = "ABCDEFGHIGKLMNOPQRSTUVWXYZ"
	n = text.length
	#  Test Cases
	task.wavePattern(text, n, 4)
	task.wavePattern(text, n, 5)
end

main()

input


 Given height : 4 

 A           G           M           S           Y  
   B       F   H       L   N       R   T       X   Z
     C   E       I   K       O   Q       U   W      
       D           G           P           V        


 Given height : 5 

 A               I               Q               Y  
   B           H   G           P   R           X   Z
     C       G       K       O       S       W      
       D   F           L   N           T   V        
         E               M               U          
import scala.collection.mutable._;
/*
    Scala Program for
    Print zigzag string pattern
*/
class WavePatterns()
{
	// Display space
	def space(size: Int): Unit = {
		var i: Int = 0;
		while (i < size)
		{
			print(" ");
			i += 1;
		}
	}
	def wavePattern(text: String, n: Int, height: Int): Unit = {
		if (height <= 0 || n == 0)
		{
			return;
		}
		else if (height == 1)
		{
			print("\n " + text);
		}
		else if (height >= n)
		{
			var i: Int = 0;
			while (i < n)
			{
				space(i);
				print(" " + text.charAt(i) + "\n");
				i += 1;
			}
		}
		else
		{
			// Display given height
			print("\n\n Given height : " + height + " \n\n");
			// Auxiliary space to store result
			var record: Array[Array[Char]] = Array.fill[Char](height, n)(' ');
			// Direction indicator Up or down
			var direction: Boolean = true;
			var point: Int = 0;
			var i: Int = 0;
			// Set default value 
			while (i < height)
			{
				var j: Int = 0;
				while (j < n)
				{
					record(i)(j) = ' ';
					j += 1;
				}
				i += 1;
			}
			i = 0;
			while (i < n)
			{
				record(point)(i) = text.charAt(i);
				if (point == 0)
				{
					// Down move
					direction = true;
				}
				else if (point + 1 == height)
				{
					// Up move
					direction = false;
				}
				if (direction == true)
				{
					// Increase row point
					point += 1;
				}
				else
				{
					// Decrease the row point
					point -= 1;
				}
				i += 1;
			}
			i = 0;
			// Display calculated result
			while (i < height)
			{
				var j: Int = 0;
				while (j < n)
				{
					print(" " + record(i)(j));
					j += 1;
				}
				// Add new line
				print("\n");
				i += 1;
			}
		}
	}
}
object Main
{
	def main(args: Array[String]): Unit = {
		var task: WavePatterns = new WavePatterns();
		var text: String = "ABCDEFGHIGKLMNOPQRSTUVWXYZ";
		var n: Int = text.length();
		// Test Cases
		task.wavePattern(text, n, 4);
		task.wavePattern(text, n, 5);
	}
}

input

 Given height : 4

 A           G           M           S           Y
   B       F   H       L   N       R   T       X   Z
     C   E       I   K       O   Q       U   W
       D           G           P           V


 Given height : 5

 A               I               Q               Y
   B           H   G           P   R           X   Z
     C       G       K       O       S       W
       D   F           L   N           T   V
         E               M               U
import Foundation;
/*
    Swift 4 Program for
    Print zigzag string pattern
*/
class WavePatterns
{
	// Display space
	func space(_ size: Int)
	{
		var i = 0;
		while (i < size)
		{
			print(" ", terminator: "");
			i += 1;
		}
	}
	func wavePattern(_ data: String, _ n: Int, _ height: Int)
	{
      	let text = Array(data);
		if (height <= 0 || n == 0)
		{
			return;
		}
		else if (height == 1)
		{
			print("\n ", data, terminator: "");
		}
		else if (height >= n)
		{
			var i = 0;
			while (i < n)
			{
				self.space(i);
				print(" ", text[i] );
				i += 1;
			}
		}
		else
		{
			// Display given height
			print("\n\n Given height : ", height ," \n");
			// Auxiliary space to store result
			var record = Array(repeating: Array(repeating: " ", 
                               count: n), count: height);
			// Direction indicator Up or down
			var direction = true;
			var point = 0;
			var i = 0;
			// Set default value 
			while (i < height)
			{
				var j = 0;
				while (j < n)
				{
					record[i][j] = " ";
					j += 1;
				}
				i += 1;
			}
			i = 0;
			while (i < n)
			{
				record[point][i] = String(text[i]);
				if (point == 0)
				{
					// Down move
					direction = true;
				}
				else if (point + 1 == height)
				{
					// Up move
					direction = false;
				}
				if (direction == true)
				{
					// Increase row point
					point += 1;
				}
				else
				{
					// Decrease the row point
					point -= 1;
				}
				i += 1;
			}
			i = 0;
			// Display calculated result
			while (i < height)
			{
				var j = 0;
				while (j < n)
				{
					print(" ", record[i][j], terminator: "");
					j += 1;
				}
				// Add new line
				print(terminator: "\n");
				i += 1;
			}
		}
	}
}
func main()
{
	let task = WavePatterns();
	let text = "ABCDEFGHIGKLMNOPQRSTUVWXYZ";
	let n = text.count;
	// Test Cases
	task.wavePattern(text, n, 4);
	task.wavePattern(text, n, 5);
}
main();

input

 Given height :  4

  A                 G                 M                 S                 Y
     B           F     H           L     N           R     T           X     Z
        C     E           I     K           O     Q           U     W
           D                 G                 P                 V


 Given height :  5

  A                       I                       Q                       Y
     B                 H     G                 P     R                 X     Z
        C           G           K           O           S           W
           D     F                 L     N                 T     V
              E                       M                       U
/*
    Kotlin Program for
    Print zigzag string pattern
*/
class WavePatterns
{
	// Display space
	fun space(size: Int): Unit
	{
		var i: Int = 0;
		while (i < size)
		{
			print(" ");
			i += 1;
		}
	}
	fun wavePattern(text: String, n: Int, height: Int): Unit
	{
		if (height <= 0 || n == 0)
		{
			return;
		}
		else if (height == 1)
		{
			print("\n " + text);
		}
		else if (height >= n)
		{
			var i: Int = 0;
			while (i < n)
			{
				this.space(i);
				print(" " + text.get(i) + "\n");
				i += 1;
			}
		}
		else
		{
			// Display given height
			print("\n\n Given height : " + height + " \n\n");
			// Auxiliary space to store result
			val record: Array < Array < Char >> = Array(height)
			{
				Array(n)
				{
					' '
				}
			};
			// Direction indicator Up or down
			var direction: Boolean = true;
			var point: Int = 0;
			var i: Int = 0;
			// Set default value 
			while (i < height)
			{
				var j: Int = 0;
				while (j < n)
				{
					record[i][j] = ' ';
					j += 1;
				}
				i += 1;
			}
			i = 0;
			while (i < n)
			{
				record[point][i] = text.get(i);
				if (point == 0)
				{
					// Down move
					direction = true;
				}
				else if (point + 1 == height)
				{
					// Up move
					direction = false;
				}
				if (direction == true)
				{
					// Increase row point
					point += 1;
				}
				else
				{
					// Decrease the row point
					point -= 1;
				}
				i += 1;
			}
			i = 0;
			// Display calculated result
			while (i < height)
			{
				var j: Int = 0;
				while (j < n)
				{
					print(" " + record[i][j]);
					j += 1;
				}
				// Add new line
				print("\n");
				i += 1;
			}
		}
	}
}
fun main(args: Array < String > ): Unit
{
	val task: WavePatterns = WavePatterns();
	val text: String = "ABCDEFGHIGKLMNOPQRSTUVWXYZ";
	val n: Int = text.length;
	// Test Cases
	task.wavePattern(text, n, 4);
	task.wavePattern(text, n, 5);
}

input

 Given height : 4

 A           G           M           S           Y
   B       F   H       L   N       R   T       X   Z
     C   E       I   K       O   Q       U   W
       D           G           P           V


 Given height : 5

 A               I               Q               Y
   B           H   G           P   R           X   Z
     C       G       K       O       S       W
       D   F           L   N           T   V
         E               M               U

Resultant Output

Running the provided code with the example input "ABCDEFGHIGKLMNOPQRSTUVWXYZ" and two test cases, the following outputs are obtained:

Given height: 4

A           G           M           S           Y
  B       F   H       L   N       R   T       X   Z
    C   E       I   K       O   Q       U   W
      D           G           P           V

Given height: 5

A               I               Q               Y
  B           H   G           P   R           X   Z
    C       G       K       O       S       W
      D   F           L   N           T   V
        E               M               U

Time Complexity

The time complexity of the provided code is O(n * height), where n is the length of the string and height is the specified height of the zigzag pattern. This is because the code iterates through each character in the string and performs operations based on the height value.

Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment