Skip to content
- Tutorials
- Python Tutorial
- Taking Input in Python
- Python Operators
- Python Data Types
- Python Loops and Control Flow
- Python Functions
- Python OOPS Concept
- Python Data Structures
- Python Exception Handling
- Python File Handling
- Python Exercises
- Java
- Java Programming Language
- Java Collections
- Java 8 Tutorial
- Java Programs
- Java Interview Questions
- Java Exercises
- Java Quiz
- Java Projects
- Advance Java
- Programming Languages
- System Design
- Interview Corner
- Computer Science Subjects
- DevOps
- Linux
- Software Testing
- Databases
- Android
- Excel
- Mathematics
- Python Tutorial
- DSA
- Data Structures
- Algorithms
- Analysis of Algorithms
- Searching Algorithms
- Sorting Algorithms
- Greedy Algorithms
- Dynamic Programming
- Graph Algorithms
- Pattern Searching
- Recursion
- Backtracking
- Divide and Conquer
- Mathematical Algorithms
- Geometric Algorithms
- Bitwise Algorithms
- Randomized Algorithms
- Branch and Bound
- Algorithms Tutorial
- DSA Tutorial
- Practice
- All DSA Problems
- Problem of the Day
- Company Wise Coding Practice
- GfG SDE Sheet
- Practice Problems Difficulty Wise
- Language Wise Coding Practice
- Curated DSA Lists
- Competitive Programming
- Company Wise SDE Sheets
- DSA Cheat Sheets
- Top Interview Questions
- Puzzles
- Data Science
- Web Tech
- Courses
-
Last Updated : 06 May, 2024
Summarize
Comments
Improve
Recommended Problem
Given a plain-text message and a numeric key, cipher/de-cipher the given text using Columnar Transposition Cipher The Columnar Transposition Cipher is a form of transposition cipher just like Rail Fence Cipher. Columnar Transposition involves writing the plaintext out in rows, and then reading the ciphertext off in columns one by one.
Examples:
EncryptionInput : Geeks for GeeksKey = HACKOutput : e kefGsGsrekoe_DecryptionInput : e kefGsGsrekoe_Key = HACKOutput : Geeks for Geeks EncryptionInput : Geeks on workKey = HACKOutput : e w_eoo_Gs kknr_DecryptionInput : e w_eoo_Gs kknr_Key = HACKOutput : Geeks on work
Encryption
In a transposition cipher, the order of the alphabets is re-arranged to obtain the cipher-text.
- The message is written out in rows of a fixed length, and then read out again column by column, and the columns are chosen in some scrambled order.
- Width of the rows and the permutation of the columns are usually defined by a keyword.
- For example, the word HACK is of length 4 (so the rows are of length 4), and the permutation is defined by the alphabetical order of the letters in the keyword. In this case, the order would be “3 1 2 4”.
- Any spare spaces are filled with nulls or left blank or placed by a character (Example: _).
- Finally, the message is read off in columns, in the order specified by the keyword.
Decryption
- To decipher it, the recipient has to work out the column lengths by dividing the message length by the key length.
- Then, write the message out in columns again, then re-order the columns by reforming the key word.
C++ // CPP program for illustrating// Columnar Transposition Cipher#include <bits/stdc++.h>using namespace std;// Encription functionstring Encryption(int no_rows, int len_key, int len_msg, string msg, int col_val[]){ int x = 0; char enc_mat[no_rows + 1][len_key]; // creating the matrix for (int i = 0; i < no_rows + 1; i++) { for (int j = 0; j < len_key; j++) { // initializes the positions with '_' after the // end of message if (x >= len_msg) { enc_mat[i][j] = '_'; } else { enc_mat[i][j] = msg[x]; } x++; } } int t = 1; string cipher = ""; // finding the cipher text according to the value of // col_val matrix while (t <= len_key) { for (int i = 0; i < len_key; i++) { int k = col_val[i]; if (k == t) { for (int j = 0; j < no_rows + 1; j++) { cipher += enc_mat[j][i]; } t++; } } } return cipher;}// decryption functionstring Decryption(int no_rows, int len_key, string cipher, int col_val[]){ char dec_mat[no_rows + 1][len_key]; int x = 0, t = 1; // rearrange the matrix according to the col_val while (t <= len_key) { for (int i = 0; i < len_key; i++) { int k = col_val[i]; if (k == t) { for (int j = 0; j < no_rows + 1; j++) { dec_mat[j][i] = cipher[x]; x++; } t++; } } } string message = ""; for (int i = 0; i < no_rows + 1; i++) { for (int j = 0; j < len_key; j++) { // replacing the '_' with space if (dec_mat[i][j] == '_') { dec_mat[i][j] = ' '; } message += dec_mat[i][j]; } } return message;}int main(){ // message string msg = "Geeks for Geeks"; // key string key = "HACK"; int len_key = key.length(); int len_msg = msg.length(); int val = 1, count = 0, ind; int col_val[len_key]; // intializing col_val matrix with 0 memset(col_val, 0, sizeof(col_val)); // numbering the key alphabets according to its ACII // value while (count < len_key) { int min = 999; for (int i = 0; i < len_key; i++) { if ((min > int(key[i])) && (col_val[i] == 0)) { min = int(key[i]); ind = i; } } col_val[ind] = val; count++; val++; } int no_rows = len_msg / len_key; // encrypted text string cipher_text = " "; cipher_text = Encryption(no_rows, len_key, len_msg, msg, col_val); cout << "Encrypted Message : " << cipher_text << endl; // decrypted text string original_msg = " "; original_msg = Decryption(no_rows, len_key, cipher_text, col_val); cout << "Decrypted Message : " << original_msg << endl;}// This code is contributed by Suchita Gond
Java import java.util.*;public class ColumnarTranspositionCipher { // Key for Columnar Transposition static final String key = "HACK"; static Map<Character, Integer> keyMap = new HashMap<>(); static void setPermutationOrder() { // Add the permutation order into the map for (int i = 0; i < key.length(); i++) { keyMap.put(key.charAt(i), i); } } // Encryption static String encryptMessage(String msg) { int row, col; StringBuilder cipher = new StringBuilder(); /* Calculate the number of columns in the matrix */ col = key.length(); /* Calculate the maximum number of rows in the matrix */ row = (int) Math.ceil((double) msg.length() / col); char[][] matrix = new char[row][col]; for (int i = 0, k = 0; i < row; i++) { for (int j = 0; j < col; ) { if (k < msg.length()) { char ch = msg.charAt(k); if (Character.isLetter(ch) || ch == ' ') { matrix[i][j] = ch; j++; } k++; } else { /* Add padding character '_' */ matrix[i][j] = '_'; j++; } } } for (Map.Entry<Character, Integer> entry : keyMap.entrySet()) { int columnIndex = entry.getValue(); // Get the cipher text from the matrix column-wise using the permuted key for (int i = 0; i < row; i++) { if (Character.isLetter(matrix[i][columnIndex]) || matrix[i][columnIndex] == ' ' || matrix[i][columnIndex] == '_') { cipher.append(matrix[i][columnIndex]); } } } return cipher.toString(); } // Decryption static String decryptMessage(String cipher) { /* Calculate the number of columns for the cipher matrix */ int col = key.length(); int row = (int) Math.ceil((double) cipher.length() / col); char[][] cipherMat = new char[row][col]; /* Add characters into the matrix column-wise */ int k = 0; for (int j = 0; j < col; j++) { for (int i = 0; i < row; i++) { cipherMat[i][j] = cipher.charAt(k); k++; } } /* Update the order of the key for decryption */ int index = 0; for (Map.Entry<Character, Integer> entry : keyMap.entrySet()) { entry.setValue(index++); } /* Arrange the matrix column-wise according to the permutation order */ char[][] decCipher = new char[row][col]; for (int l = 0; l < key.length(); l++) { int columnIndex = keyMap.get(key.charAt(l)); for (int i = 0; i < row; i++) { decCipher[i][l] = cipherMat[i][columnIndex]; } } /* Get the message using the matrix */ StringBuilder msg = new StringBuilder(); for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { if (decCipher[i][j] != '_') { msg.append(decCipher[i][j]); } } } return msg.toString(); } public static void main(String[] args) { /* Message */ String msg = "Geeks for Geeks"; setPermutationOrder(); // Calling encryption function String cipher = encryptMessage(msg); System.out.println("Encrypted Message: " + cipher); // Calling Decryption function System.out.println("Decrypted Message: " + decryptMessage(cipher)); }}
Python # Python3 implementation of# Columnar Transpositionimport mathkey = "HACK"# Encryptiondef encryptMessage(msg): cipher = "" # track key indices k_indx = 0 msg_len = float(len(msg)) msg_lst = list(msg) key_lst = sorted(list(key)) # calculate column of the matrix col = len(key) # calculate maximum row of the matrix row = int(math.ceil(msg_len / col)) # add the padding character '_' in empty # the empty cell of the matix fill_null = int((row * col) - msg_len) msg_lst.extend('_' * fill_null) # create Matrix and insert message and # padding characters row-wise matrix = [msg_lst[i: i + col] for i in range(0, len(msg_lst), col)] # read matrix column-wise using key for _ in range(col): curr_idx = key.index(key_lst[k_indx]) cipher += ''.join([row[curr_idx] for row in matrix]) k_indx += 1 return cipher# Decryptiondef decryptMessage(cipher): msg = "" # track key indices k_indx = 0 # track msg indices msg_indx = 0 msg_len = float(len(cipher)) msg_lst = list(cipher) # calculate column of the matrix col = len(key) # calculate maximum row of the matrix row = int(math.ceil(msg_len / col)) # convert key into list and sort # alphabetically so we can access # each character by its alphabetical position. key_lst = sorted(list(key)) # create an empty matrix to # store deciphered message dec_cipher = [] for _ in range(row): dec_cipher += [[None] * col] # Arrange the matrix column wise according # to permutation order by adding into new matrix for _ in range(col): curr_idx = key.index(key_lst[k_indx]) for j in range(row): dec_cipher[j][curr_idx] = msg_lst[msg_indx] msg_indx += 1 k_indx += 1 # convert decrypted msg matrix into a string try: msg = ''.join(sum(dec_cipher, [])) except TypeError: raise TypeError("This program cannot", "handle repeating words.") null_count = msg.count('_') if null_count > 0: return msg[: -null_count] return msg# Driver Codemsg = "Geeks for Geeks"cipher = encryptMessage(msg)print("Encrypted Message: {}". format(cipher))print("Decryped Message: {}". format(decryptMessage(cipher)))# This code is contributed by Aditya K
C# using System;using System.Collections.Generic;public class ColumnarTranspositionCipher { // Key for Columnar Transposition static readonly string key = "HACK"; static Dictionary<char, int> keyMap = new Dictionary<char, int>(); static void SetPermutationOrder() { // Add the permutation order into the dictionary for (int i = 0; i < key.Length; i++) { keyMap[key[i]] = i; } } // Encryption static string EncryptMessage(string msg) { int row, col; System.Text.StringBuilder cipher = new System.Text.StringBuilder(); /* Calculate the number of columns in the matrix */ col = key.Length; /* Calculate the maximum number of rows in the * matrix */ row = (int)Math.Ceiling((double)msg.Length / col); char[, ] matrix = new char[row, col]; for (int i = 0, k = 0; i < row; i++) { for (int j = 0; j < col;) { if (k < msg.Length) { char ch = msg[k]; if (char.IsLetter(ch) || ch == ' ') { matrix[i, j] = ch; j++; } k++; } else { /* Add padding character '_' */ matrix[i, j] = '_'; j++; } } } foreach( var entry in new Dictionary<char, int>(keyMap)) { int columnIndex = entry.Value; // Get the cipher text from the matrix // column-wise using the permuted key for (int i = 0; i < row; i++) { if (char.IsLetter(matrix[i, columnIndex]) || matrix[i, columnIndex] == ' ' || matrix[i, columnIndex] == '_') { cipher.Append(matrix[i, columnIndex]); } } } return cipher.ToString(); } // Decryption static string DecryptMessage(string cipher) { /* Calculate the number of columns for the cipher * matrix */ int col = key.Length; int row = (int)Math.Ceiling((double)cipher.Length / col); char[, ] cipherMat = new char[row, col]; /* Add characters into the matrix column-wise */ int k = 0; for (int j = 0; j < col; j++) { for (int i = 0; i < row; i++) { cipherMat[i, j] = cipher[k]; k++; } } /* Update the order of the key for decryption */ int index = 0; foreach( var entry in new Dictionary<char, int>(keyMap)) { keyMap[entry.Key] = index++; } /* Arrange the matrix column-wise according to the * permutation order */ char[, ] decCipher = new char[row, col]; foreach(var entry in keyMap) { int columnIndex = entry.Value; for (int i = 0; i < row; i++) { decCipher[i, columnIndex] = cipherMat[i, columnIndex]; } } /* Get the message using the matrix */ System.Text.StringBuilder msg = new System.Text.StringBuilder(); for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { if (decCipher[i, j] != '_') { msg.Append(decCipher[i, j]); } } } return msg.ToString(); } public static void Main(string[] args) { /* Message */ string msg = "Geeks for Geeks"; SetPermutationOrder(); // Calling encryption function string cipher = EncryptMessage(msg); Console.WriteLine("Encrypted Message: " + cipher); // Calling Decryption function Console.WriteLine("Decrypted Message: " + DecryptMessage(cipher)); }}
JavaScript // JavaScript implementation of // Columnar Transpositionconst key = "HACK";// Encryptionfunction encryptMessage(msg) { let cipher = ""; // track key indices let k_indx = 0; const msg_len = msg.length; const msg_lst = Array.from(msg); const key_lst = Array.from(key).sort(); // calculate column of the matrix const col = key.length; // calculate maximum row of the matrix const row = Math.ceil(msg_len / col); // add the padding character '_' in empty // the empty cell of the matrix const fill_null = (row * col) - msg_len; for (let i = 0; i < fill_null; i++) { msg_lst.push('_'); } // create Matrix and insert message and // padding characters row-wise const matrix = []; for (let i = 0; i < msg_lst.length; i += col) { matrix.push(msg_lst.slice(i, i + col)); } // read matrix column-wise using key for (let _ = 0; _ < col; _++) { const curr_idx = key.indexOf(key_lst[k_indx]); for (const row of matrix) { cipher += row[curr_idx]; } k_indx++; } return cipher;}// Decryptionfunction decryptMessage(cipher) { let msg = ""; // track key indices let k_indx = 0; // track msg indices let msg_indx = 0; const msg_len = cipher.length; const msg_lst = Array.from(cipher); // calculate column of the matrix const col = key.length; // calculate maximum row of the matrix const row = Math.ceil(msg_len / col); // convert key into list and sort // alphabetically so we can access // each character by its alphabetical position. const key_lst = Array.from(key).sort(); // create an empty matrix to // store deciphered message const dec_cipher = []; for (let i = 0; i < row; i++) { dec_cipher.push(Array(col).fill(null)); } // Arrange the matrix column wise according // to permutation order by adding into a new matrix for (let _ = 0; _ < col; _++) { const curr_idx = key.indexOf(key_lst[k_indx]); for (let j = 0; j < row; j++) { dec_cipher[j][curr_idx] = msg_lst[msg_indx]; msg_indx++; } k_indx++; } // convert decrypted msg matrix into a string try { msg = dec_cipher.flat().join(''); } catch (err) { throw new Error("This program cannot handle repeating words."); } const null_count = (msg.match(/_/g) || []).length; if (null_count > 0) { return msg.slice(0, -null_count); } return msg;}// Driver Codeconst msg = "Geeks for Geeks";const cipher = encryptMessage(msg);console.log("Encrypted Message: " + cipher);console.log("Decrypted Message: " + decryptMessage(cipher));// This code is contributed by phasing17
Output
Encrypted Message : e kefGsGsrekoe_Decrypted Message : Geeks for Geeks
Please Login to comment...
Similar Reads
Transposition Cipher Techniques in Cryptography
Transposition Ciphers are an essential part of cryptography that uses systematic shuffling of plain text characters or bits to secure data by altering their positions based on some defined way or algorithm. Moreover, unlike substitutive codes where different letters substitute others, in these, you just shift about original letters hence it does no
5 min read
Difference between Monoalphabetic Cipher and Polyalphabetic Cipher
A Monoalphabetic Cipher is a cipher where each letter in the plaintext is always mapped to the same letter in the ciphertext While a Polyalphabetic Cipher is a cipher where each letter in the plaintext can be encrypted to multiple possible letters in the ciphertext, depending on its position and a more complex algorithm. In this article, we will se
3 min read
Odd Even Transposition Sort / Brick Sort using pthreads
Odd-Even Transposition Sort is a parallel sorting algorithm. It is based on the Bubble Sort technique, which compares every 2 consecutive numbers in the array and swap them if first is greater than the second to get an ascending order array. It consists of 2 phases - the odd phase and even phase: Odd phase: Every odd indexed element is compared wit
8 min read
Latin alphabet cipher
The Latin Alphabet Cipher Encryption Technique is one of the earliest and simplest techniques of encrypting data. It’s simply a type of substitution cipher technique, i.e., each letter of a given text is substituted by its corresponding number as represented in its alphabetical order. For Example, we have given a string as "hello everyone", then it
5 min read
Bifid Cipher in Cryptography
This cipher technique considered more secure compared to other substitution algorithms reason being it breaks the message apart into two separate streams and then recombines them. It is a combination of the Polybius square with the transposition and uses fractionation to achieve diffusion. This encrypting technique invented by Felin Delastelle. It
4 min read
Feistel Cipher
Feistel Cipher model is a structure or a design used to develop many block ciphers such as DES. Feistel cipher may have invertible, non-invertible and self invertible components in its design. Same encryption as well as decryption algorithm is used. A separate key is used for each round. However same round keys are used for encryption as well as de
3 min read
Autokey Cipher | Symmetric Ciphers
Autokey Cipher is a polyalphabetic substitution cipher. It is closely related to the Vigenere cipher but uses a different method of generating the key. It was invented by Blaise de Vigenère in 1586. In general, more secure than the Vigenere cipher. Example-1: Plaintext = "HELLO" Autokey = N Ciphertext = "ULPWZ" Example-2: Plaintext = "GEEKSFORGEEKS
4 min read
Encrypt using XOR Cipher with Repeating Key
Computer Architectures have predefined ASCII values & Binary forms for all printable characters, which allows us to operate bit-wise logic like XOR and most encryption/decryption algorithms depend on. The Key is XOR-operated on the plain text to produce the encrypted text. Only Parameters required to encrypt a plain text using this technique: P
2 min read
Program to perform a letter frequency attack on a monoalphabetic substitution cipher
Given a string S of size N representing a monoalphabetic cipher, the task is to print the top five possible plain texts that can be decrypted from the given monoalphabetic cipher using a letter frequency attack. Examples: Input: S = "ETAOINSHRDLCUMWFGYPBVKJXQZ"Output: A SIMPLE MESSAGE B TJNQMF NFTTBHF A SIMPLE MESSAGE C UKORNG OGUUCIG C UKORNG OGUU
13 min read
Implementation of Vernam Cipher or One Time Pad Algorithm
One Time Pad algorithm is the improvement of the Vernam Cipher, proposed by An Army Signal Corp officer, Joseph Mauborgne. It is the only available algorithm that is unbreakable(completely secure). It is a method of encrypting alphabetic plain text. It is one of the Substitution techniques which converts plain text into ciphertext. In this mechanis
13 min read
Vernam Cipher in Cryptography
Vernam Cipher is a method of encrypting alphabetic text. It is one of the Substitution techniques for converting plain text into cipher text. In this mechanism, we assign a number to each character of the Plain-Text, like (a = 0, b = 1, c = 2, ... z = 25). Method to take key: In the Vernam cipher algorithm, we take a key to encrypt the plain text w
6 min read
XOR Cipher
XOR Encryption is an encryption method used to encrypt data and is hard to crack by brute-force method, i.e generating random encryption keys to match with the correct one. Below is a simple implementation in C++. The concept of implementation is to first define XOR - encryption key and then to perform XOR operation of the characters in the String
5 min read
Rail Fence Cipher - Encryption and Decryption
Given a plain-text message and a numeric key, cipher/de-cipher the given text using Rail Fence algorithm.The rail fence cipher (also called a zigzag cipher) is a form of transposition cipher. It derives its name from the way in which it is encoded.Examples: EncryptionInput : "GeeksforGeeks "Key = 3Output : GsGsekfrek eoeDecryptionInput : GsGsekf
15 min read
Implementation of Affine Cipher
The Affine cipher is a type of monoalphabetic substitution cipher, wherein each letter in an alphabet is mapped to its numeric equivalent, encrypted using a simple mathematical function, and converted back to a letter. The formula used means that each letter encrypts to one other letter, and back again, meaning the cipher is essentially a standard
10 min read
ROT13 cipher
ROT13 cipher(read as - "rotate by 13 places") is a special case of the Ceaser cipher in which the shift is always 13. So every letter is shifted 13 places to encrypt or to decrypt the message. You must think that it is just another caesar cipher so what's different this time? Well the difference is in its implementation. The approach is to use two
10 min read
Implementing Atbash Cipher
Definition: Atbash cipher is a substitution cipher with just one specific key where all the letters are reversed that is A to Z and Z to A. It was originally used to encode the Hebrew alphabets but it can be modified to encode any alphabet. Relationship to Affine: Atbash cipher can be thought of as a special case of Affine cipher with both the keys
7 min read
Keyword Cipher
Keyword cipher is a form of monoalphabetic substitution. A keyword is used as the key, and it determines the letter matchings of the cipher alphabet to the plain alphabet. Repeats of letters in the word are removed, then the cipher alphabet is generated with the keyword matching to A, B, C, etc. until the keyword is used up, whereupon the rest of t
15+ min read
Null Cipher
A null cipher, also known as concealment cipher, is an ancient form of encryption where the plaintext is mixed with a large amount of non-cipher material. Today it is regarded as a simple form of steganography, which can be used to hide ciphertext. There are various options of using the Null Cipher. Here we are taking the first letter from each wor
6 min read
What is Round Cipher?
Round ciphers are also known as block ciphers, and they are a classification of encryption algorithms that work systematically, converting the plaintext into ciphertext. These algorithms work on a limited number of bits at a time and subject them to a set of mathematical processes called rounds which are used to bring about the act of encryption. I
10 min read
What is Cipher?
Ciphers are the most vital components of cryptography, as it is through them that the protection of information is made possible in the ever-growing digital environment. In the present generation, given the technological advancement especially in the field of communication, the aspect of security is critical. Cipher is used in securing financial tr
7 min read
Caesar Cipher in Cryptography
The Caesar Cipher is one of the simplest and oldest methods of encrypting messages, named after Julius Caesar, who reportedly used it to protect his military communications. This technique involves shifting the letters of the alphabet by a fixed number of places. For example, with a shift of three, the letter 'A' becomes 'D', 'B' becomes 'E', and s
12 min read
What is Monoalphabetic Cipher?
Monoalphabetic Cipher is a part of the substitution technique in which a single cipher alphabet is used per message (mapping is done from plain alphabet to cipher alphabet). Monoalphabetic cipher converts plain text into cipher text and re-convert a cipher text to plain text. Monoalphabetic Cipher eliminates the brute-force techniques for cryptanal
4 min read
Vigenère Cipher
Vigenere Cipher is a method of encrypting alphabetic text. It uses a simple form of polyalphabetic substitution. A polyalphabetic cipher is any cipher based on substitution, using multiple substitution alphabets. The encryption of the original text is done using the Vigenère square or Vigenère table. The table consists of the alphabets written out
9 min read
Playfair Cipher with Examples
The Playfair cipher was the first practical digraph substitution cipher. The scheme was invented in 1854 by Charles Wheatstone but was named after Lord Playfair who promoted the use of the cipher. In playfair cipher unlike traditional cipher we encrypt a pair of alphabets(digraphs) instead of a single alphabet.It was used for tactical purposes by B
15+ min read
What is Multiplicative Cipher in Cryptography?
A multiplicative cipher is a type of cipher that comes under a monoalphabetic cipher, in which each letter that is present in the plaintext is replaced by a corresponding letter of the ciphertext, according to a fixed multiplication key. In this article, we will learn about the multiplicative cipher and its working for the encryption and decryption
9 min read
Polybius Square Cipher
A Polybius Square is a table that allows someone to convert letters into numbers. To make the encryption little harder, this table can be randomized and shared with the recipient. In order to fit the 26 letters of the alphabet into the 25 cells created by the table, the letters 'i' and 'j' are usually combined into a single cell. Originally there w
5 min read
Substitution Cipher
Hiding some data is known as encryption. When plain text is encrypted it becomes unreadable and is known as ciphertext. In a Substitution cipher, any character of plain text from the given fixed set of characters is substituted by some other character from the same set depending on a key. For example with a shift of 1, A would be replaced by B, B w
6 min read
Learn Data Structures and Algorithms | DSA Tutorial
Data Structures and Algorithms (DSA) refer to the study of methods for organizing and storing data and the design of procedures (algorithms) for solving problems, which operate on these data structures. DSA is one of the most important skills that every computer science student must have. It is often seen that people with good knowledge of these te
15+ min read
Bubble Sort Algorithm
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity is quite high. Bubble Sort AlgorithmIn Bubble Sort algorithm, traverse from left and compare adjacent elements and the
9 min read
Quick Sort
QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. Table of Content How does QuickSort work? Details of Partition Algorithm and Illustration : Illustration of QuickSort: Code impleme
14 min read
Article Tags :
Practice Tags :
Trending in News
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
'); $('.spinner-loading-overlay').show(); jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id, check: true }), success:function(result) { jQuery.ajax({ url: writeApiUrl + 'suggestions/auth/' + `${post_id}/`, type: "GET", dataType: 'json', xhrFields: { withCredentials: true }, success: function (result) { $('.spinner-loading-overlay:eq(0)').remove(); var commentArray = result; if(commentArray === null || commentArray.length === 0) { // when no reason is availaible then user will redirected directly make the improvment. // call to api create-improvement-post $('body').append('
'); $('.spinner-loading-overlay').show(); jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id, }), success:function(result) { $('.spinner-loading-overlay:eq(0)').remove(); $('.improve-modal--overlay').hide(); $('.unlocked-status--improve-modal-content').css("display","none"); $('.create-improvement-redirection-to-write').attr('href',writeUrl + 'improve-post/' + `${result.id}` + '/', '_blank'); $('.create-improvement-redirection-to-write')[0].click(); }, error:function(e) { $('.spinner-loading-overlay:eq(0)').remove(); var result = e.responseJSON; if(result.detail.non_field_errors.length){ $('.improve-modal--improve-content .improve-modal--improve-content-modified').text(`${result.detail.non_field_errors}.`); jQuery('.improve-modal--overlay').show(); jQuery('.improve-modal--improvement').show(); $('.locked-status--impove-modal').css("display","block"); $('.unlocked-status--improve-modal-content').css("display","none"); $('.improve-modal--improvement').attr("status","locked"); $('.improvement-reason-modal').hide(); } }, }); return; } var improvement_reason_html = ""; for(var comment of commentArray) { // loop creating improvement reason list markup var comment_id = comment['id']; var comment_text = comment['suggestion']; improvement_reason_html += `
${comment_text}
`; } $('.improvement-reasons_wrapper').html(improvement_reason_html); $('.improvement-bottom-btn').html("Create Improvement"); $('.improve-modal--improvement').hide(); $('.improvement-reason-modal').show(); }, error: function(e){ $('.spinner-loading-overlay:eq(0)').remove(); // stop loader when ajax failed; }, }); }, error:function(e) { $('.spinner-loading-overlay:eq(0)').remove(); var result = e.responseJSON; if(result.detail.non_field_errors.length){ $('.improve-modal--improve-content .improve-modal--improve-content-modified').text(`${result.detail.non_field_errors}.`); jQuery('.improve-modal--overlay').show(); jQuery('.improve-modal--improvement').show(); $('.locked-status--impove-modal').css("display","block"); $('.unlocked-status--improve-modal-content').css("display","none"); $('.improve-modal--improvement').attr("status","locked"); $('.improvement-reason-modal').hide(); } }, }); } else { if(loginData && !loginData.isLoggedIn) { $('.improve-modal--overlay').hide(); if ($('.header-main__wrapper').find('.header-main__signup.login-modal-btn').length) { $('.header-main__wrapper').find('.header-main__signup.login-modal-btn').click(); } return; } } }); $('.left-arrow-icon_wrapper').on('click',function(){ if($('.improve-modal--suggestion').is(":visible")) $('.improve-modal--suggestion').hide(); else{ $('.improvement-reason-modal').hide(); } $('.improve-modal--improvement').show(); }); function loadScript(src, callback) { var script = document.createElement('script'); script.src = src; script.onload = callback; document.head.appendChild(script); } function suggestionCall() { var suggest_val = $.trim($("#suggestion-section-textarea").val()); var array_String= suggest_val.split(" ") var gCaptchaToken = $("#g-recaptcha-response-suggestion-form").val(); var error_msg = false; if(suggest_val != "" && array_String.length >=4){ if(suggest_val.length <= 2000){ var payload = { "gfg_post_id" : `${post_id}`, "suggestion" : `
${suggest_val}
`, } if(!loginData || !loginData.isLoggedIn) // User is not logged in payload["g-recaptcha-token"] = gCaptchaToken jQuery.ajax({ type:'post', url: "https://apiwrite.geeksforgeeks.org/suggestions/auth/create/", xhrFields: { withCredentials: true }, crossDomain: true, contentType:'application/json', data: JSON.stringify(payload), success:function(data) { jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-section-textarea').val(""); jQuery('.suggest-bottom-btn').css("display","none"); // Update the modal content const modalSection = document.querySelector('.suggestion-modal-section'); modalSection.innerHTML = `
Thank You!
Your suggestions are valuable to us.
You can now also contribute to the GeeksforGeeks community by creating improvement and help your fellow geeks.
`; }, error:function(data) { jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-modal-alert').html("Something went wrong."); jQuery('#suggestion-modal-alert').show(); error_msg = true; } }); } else{ jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-modal-alert').html("Minimum 5 Words and Maximum Character limit is 2000."); jQuery('#suggestion-modal-alert').show(); jQuery('#suggestion-section-textarea').focus(); error_msg = true; } } else{ jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-modal-alert').html("Enter atleast four words !"); jQuery('#suggestion-modal-alert').show(); jQuery('#suggestion-section-textarea').focus(); error_msg = true; } if(error_msg){ setTimeout(() => { jQuery('#suggestion-section-textarea').focus(); jQuery('#suggestion-modal-alert').hide(); }, 3000); } } document.querySelector('.suggest-bottom-btn').addEventListener('click', function(){ jQuery('body').append('
'); jQuery('.spinner-loading-overlay').show(); if(loginData && loginData.isLoggedIn) { suggestionCall(); return; } // load the captcha script and set the token loadScript('https://www.google.com/recaptcha/api.js?render=6LdMFNUZAAAAAIuRtzg0piOT-qXCbDF-iQiUi9KY',[], function() { setGoogleRecaptcha(); }); }); $('.improvement-bottom-btn.create-improvement-btn').click(function() { //create improvement button is clicked $('body').append('
'); $('.spinner-loading-overlay').show(); // send this option via create-improvement-post api jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id }), success:function(result) { $('.spinner-loading-overlay:eq(0)').remove(); $('.improve-modal--overlay').hide(); $('.improvement-reason-modal').hide(); $('.create-improvement-redirection-to-write').attr('href',writeUrl + 'improve-post/' + `${result.id}` + '/', '_blank'); $('.create-improvement-redirection-to-write')[0].click(); }, error:function(e) { $('.spinner-loading-overlay:eq(0)').remove(); var result = e.responseJSON; if(result.detail.non_field_errors.length){ $('.improve-modal--improve-content .improve-modal--improve-content-modified').text(`${result.detail.non_field_errors}.`); jQuery('.improve-modal--overlay').show(); jQuery('.improve-modal--improvement').show(); $('.locked-status--impove-modal').css("display","block"); $('.unlocked-status--improve-modal-content').css("display","none"); $('.improve-modal--improvement').attr("status","locked"); $('.improvement-reason-modal').hide(); } }, }); });