- Practice
- Algorithms
- Implementation
- Encryption
- Discussions

# Encryption

# Encryption

Schuetzl + 47 comments I see a lot of people in the discussions are using a 2d array, did anyone else solve it by simply iterating through the input string? Is there a difference in efficiency? All of my submissions were 0.09s of quicker (using Java). Is there a better way to do it?

dan_mar_042 + 1 comment 0s in every case without using 2d array (c++). It was a great hint! Thanks!

vishalbty + 1 comment I used python and man it was very easy. You can find the answer here. Hackerrank - Encryption Solution

sourav_singhh98 + 0 comments [deleted]

xXGoziXx + 1 comment I did it like this and got all submissions 0.06. Great hint! :D https://www.hackerrank.com/challenges/encryption/submissions/code/16330491

cangktvn + 5 comments I have the same approach with you, why everybody have to do it the hard way?

`int main(){ string s; cin >> s; auto n = s.size(); int row = round(sqrt(n)); int column; if (row >= sqrt(n)) column = row; else column = row + 1; for(int j=0;j<column;++j) { for(int i=j; i<n;i+=column)cout << s[i]; cout << ' '; } return 0; }`

vidushig2 + 2 comments int main(){ char s[10000]; cin >> s; int l = strlen(s); int rows = floor(sqrt(l)); int columns = ceil(sqrt(l)); if((rows*columns)

`return 0;`

}

please tell why test case 1 and 2 are failing.

slash331erock + 5 comments same problem my output and expected output is exactly the same still it is showing wrong answer

Vardhan + 2 comments Yes same problem with me. Any idea how to rectify that?

B1ack + 0 comments maybe problem with an extra space in your result

scan2 + 0 comments Problem is that task had been given wrong. Let's say 8 char string. floor = 2, ceiling = 3 and yeah, we have 2x3 chars = 6 maximum. Just round as ussual sqrt and it start to work (and add 1 for columns if needed of course)

lkrajcsovicz + 0 comments I had a same error, the root cause for me was java char to String encoding.

2019201057_anur + 1 comment because u need to append '\0' extra and while looping ...just break when \0 occurs

Nishvick + 0 comments try to upload code as file rather than coding on the website

yanto_wendy98 + 0 comments If you are using c++, use '\0' to check for NULL character in string rather than using default value (it's been replaced)

if (output[j][i] != '\0') { cout<<output[j][i]; }

decodefreak + 0 comments it works fine for me

`int n=s.size(); int jump=sqrt(n); if(jump*jump!=n){ jump++; } string ans=""; for(int i=0;i<jump;i++){ for(int j=i;j<n;j+=jump){ ans+=s[j]; } ans+=" "; } return ans;`

ganeshmukesh111 + 9 comments how you manage to skip spaces from orignal string (s)?

beshm + 1 comment if you are using java, you could use trim method.

vyavaharkardeve1 + 0 comments trim() removes only the spaces before and after the string.

beastieric + 0 comments There are no spaces in the original string.

knivendha + 0 comments usre replace()

s=s.replace(" ", "");

naeemalicious + 0 comments s.replaceAll(" ", "");

tthrash + 0 comments [deleted]tthrash + 0 comments s = s.replaceAll("\\s+","");

vishal_nimavat + 0 comments in java string.replaceAll("\\s+", "");

B1ack + 1 comment you can use replace method - > str.replace(" ","")

Vardhan + 1 comment The answers are matching, still the TestCases are not passing. I used the replace Method.

B1ack + 0 comments i used the replace method not sure why your test cases are failing , write your code on local machine and match the length , case of your output. or just forward the code i ll check it out.

faizancassim + 0 comments If you are using C++, you can use the string::substr() method where you specify the start as 0 and the end as string.length()-2; for 1 char of space.

tarabahadur_tha1 + 1 comment Could you please explain the logic behind determining the noOfRows and noOfCols

vishal_nimavat + 1 comment in java

`final double length = string.length(); int row = (int) Math.floor(Math.sqrt(length)); final int column = (int) Math.ceil(Math.sqrt(length));`

17zimmermane + 1 comment In some cases this will not work. For example, a string of length 8 will get a row of 2 and a column of 3. 2 * 3 = 6 is less than 8 so it will not fit the string.

minsarangi + 0 comments [deleted]

abkumar192000 + 0 comments clap;

prajwalparve33 + 0 comments # We think same bro

`def encryption(s): n = len(s) row = math.ceil(math.sqrt(n)) colm = 0 if row >= math.sqrt(n): colm = row else: colm = row+1 for i in range(colm): for j in range(i,n,colm): print(s[j],end='') print(' ',end='')`

Kthompso + 4 comments Sure:

`#!/bin/python3 import sys from math import ceil, sqrt s = input().strip() c = ceil(sqrt(len(s))) print(' '.join(map(lambda x: s[x::c], range(c))))`

Anyone see a way to turn this into a 1-liner without calculating c twice?

qu4ku + 3 comments but you will need s in the separate line using this method

import sys from math import ceil, sqrt s=input().strip() exec("print(' '.join(map(lambda x: s[x::{0}], range({0}))))".format(ceil(sqrt(len(s)))))

FilipF + 3 comments Hi! Your improvement got me thinking, how to combine those statements into one, and this seems to work? Rather than wrap your statement inside of another string and format, I wrapped the exec with a lambda, and applied it to the input. There's a copy online to play with.

from math import ceil, sqrt (lambda s: exec("print(' '.join(map(lambda x: \"{1}\"[x::{0}], range({0}))))".format(ceil(sqrt(len(s))),s)))(input().strip())

I also tried to use

`"+s+"`

instead of`{1}`

and`,s`

, but both use five characters, so there's not a big improvement.## =====

That got me thinking though... what about using another nested lambda instead of format and exec? I tweaked it again, and got a new version. Cool. But what about the import statement? With a little syntactic trickery, we can turn

`sqrt`

into`n**0.5`

, and I learned you can replicate the`ceil`

function by doing`-(-n//1)`

instead. Finally! A single statement.# This is all one line, I swear. Only three spaces total. (lambda s:(lambda r:print(' '.join(map(lambda x:s[x::r],range(r)))))(int(-(-(len(s)**0.5)//1))))(input().strip())

# Here's the statement blown up to make things clearer. Maybe. (lambda s: (lambda r: print( ' '.join( map( lambda x: s[x::r], range(r) ) ) ) ) ( int(-(-(len(s)**0.5)//1)) ) ) ( input().strip() )

# And here's that second parameter, blown up too. int( -( -( len(s)**0.5 ) // 1 ) )

I hope some one gets a kick out of that like I did. ;) It's not great code golf, but it is satisfying to put it all together on one line. Especially since it's, well, python, hehe.

### References: Python grammar, Ceiling function.

dangerDon + 1 comment This is what i am searching for, One liner

You have just teach me a new way to make more one liners :)

aymansubbagh + 0 comments seriously yeah, my code is horrific

Dragg + 1 comment this is awesome! :D

ganeshmukesh111 + 0 comments thanks

the_insomniac + 0 comments how does the r in range get its value??? please someone explain. @filipF

mridula_bvs + 1 comment Could anyone please explain this line in detail?

exec("print(' '.join(map(lambda x: s[x::{0}], range({0}))))".format(ceil(sqrt(len(s)))))

shawnkmeier + 0 comments The methodo "exec" runs the string as if it were python code.

`>>> a = 2 >>> exec("a = a + 1") >>> a 3`

The "format" method replaces occurances of "{n}"

`>>> "foo {0} {1}".format("bar","baz") 'foo bar baz'`

I think the reason they did it may have something to do with formatting the input to range into an integer combined with a functional style "let" binding, but the formatting aspect doesn't seem to work for me. Range throws an error that it got a float.

But honestly you shouldn't write code like this. If a user can get a string into the "format" method then you have a security vulnerability. Also it is unreadable even if you know what the methods do.

ashutoshdikshit1 + 1 comment [deleted]ashutoshdikshit1 + 1 comment import math def encryption(s):

`str1="".join(s.split()) print(str1) #ashutoshdikshit len1=len(str1) # 15 sq=math.sqrt(len1) #3 r=int(sq) #row =3 c=int(sq)+1 #coloumn=4 p=[(str1[i:i+c]) for i in range(0,len(str1),c)] print("p",p) #p ['ashu', 'tosh', 'diks', 'hit'] final=[] for i in range(len(p)-1): print(len(p)-1) fc=[] for j in p: # print(j) fc.append(j[i]) final.append(fc) #print(fc) print(final)`

s=input() encryption(s)

can u help me with this code problem i am getting is last coloumns dont print eg: ifmanwas

meanttos

tayonthe

groundgo

dwouldha

vegivenu

sroots in this aohddn and sseoa wont print .bala12901 + 1 comment `def encryption(s): arr=[] answerarray=[] rows=math.floor(math.sqrt(len(s))) cols=math.ceil(math.sqrt(len(s))) if rows*cols<len(s): rows=cols for j in range(rows): arr.append(s[cols*j:(cols*j)+cols]) for x in range(cols): string="" for y in range(rows): ** if x<len(arr[y]):** string+=arr[y][x] answerarray.append(string+" ") return "".join(answerarray)`

bala12901 + 0 comments `** if x<len(arr[y]):**`

if you add this it will work... i faced the same problem bro...

adityasrb + 0 comments [deleted]manishmeshram51 + 0 comments can you please explain how you used lambda in your code?

yashzawar2000 + 0 comments **s[x::c]**

didnt understand the meaning of this term!

qu4ku + 3 comments once you said it it actually seems to be stupid to solve it with arrays :D

MichaelDsa + 0 comments Yeah, the hint was great! :D

viigihabe + 0 comments Actually I used array. A virtual one. One may calculate these indexes by hand but if language allows let the compiler do the job:

using encoding_table_t = char const[rows][cols]; encoding_table_t * encoded = reinterpret_cast< encoding_table_t*>( str.c_str() );

But still, to prevent out of bounds access I had to check by hand:

// break inner loop if(i + j * cols >= str.size()) break;

The calculation may be avoided if we are allowed to modify input string. In real life - not here. If we are, then we can just fill zeros to end of string. It may or may not result in memory allocation if reserved space is all used allready. In C-string context we didn't change anything. But changed the size! It might matter. We could then check if index contains char(0).

Note: because encoded is pointer to array not array itself it has to be dereferenced before indexing:

ret_val.push_back( (*encoded)[j][i] );

Note: I used approach where we are expeted to fill the provided function. Thus the name "ret_val" and it is going to be returned.

CristianNaziru + 1 comment ... I solved it with a matrix, feelsbad...

smitparekh1995 + 0 comments [deleted]

Epshita + 0 comments int main() { string s;

`cin >> s; auto n = s.size(); int row, column; row = = round(sqrt(n)); if( row >= sqrt(n) ) column = row; else column = row + 1; for( int j = 0; j < column; j++ ) { for( int i = j; i < n; i += column ) cout << s[i]; cout << ' '; }`

}

Sure, I did it this way.

shouki + 1 comment 0.02s or quicker in C#. Didn't even bother with the grid approach but it's got to be slower because of the extra iteration and memory writes. The additional space requirements of allocating a grid also impacts overall performance. And if we're talking about cryptography here, you want it to be as performant as possible.

AndreaR + 1 comment yes, C# .02s, no array, using StringBuilder

KUTlime + 0 comments A C# solution without anything ;)

using System; class Solution { static void Main(String[] args) { string s = Console.ReadLine(); Int32 Lmax = (Int32)Math.Ceiling(Math.Sqrt(s.Length)); for(Int32 i = 0; i < Lmax; i++){ Console.Write(s[i]); for(Int32 j = i+Lmax; j < s.Length; j+=Lmax){Console.Write(s[j]);} Console.Write(" "); } } }

mayank_k_jha + 2 comments public class Solution { public static void main(String[] args) { Scanner in=new Scanner(System.in); String s=in.next(); double row=Math.floor(Math.pow(s.length(),0.5)); double col=Math.ceil(Math.pow(s.length(),0.5)); String ans =""; for(int i=0;i<col;i++){ int j=0; while(i+j<s.length()){ ans=ans+s.substring(i+j,i+j+1); j=(int) (j+col);} ans=ans+" ";} System.out.println(ans);}}

naeemalicious + 0 comments You forgot to remove the spaces between the words.

svworld01 + 0 comments use this to replace all spaces

s = s.replaceAll("\\s+", "");

lifekills + 0 comments Honestly, using a 2D array barely even crossed my mind. I spent too long making binary trees in C++ to be afraid of some simple index math.

0.1 seconds in Java on every test.

ashsingh1 + 3 comments sometimes people overthink, I was going with the array approach then I saw this, thanks for the hint. here is my implementation in java

static void message(String string){ int row = (int)Math.floor(Math.sqrt(string.length())); int column = (int)Math.ceil(Math.sqrt(string.length())); if(row * column < string.length()) row = column; for(int i = 0; i < column; i++){ for(int j = i; j < string.length(); j = j + column ){ System.out.print(string.charAt(j)); } System.out.print(" "); } }

Code_Crush + 2 comments what is the use of this line in your code.....

if(row * column < string.length()) row = column;

zmingxie + 0 comments I don't see why this line is needed either...

_Nitin_Verma_ + 0 comments take case of string length=8 we will have row=2,col=3 condition 1 of ques states that row*col should be greater then length (which is false here) so take extreme case(i.e row=column)

chabrecek + 0 comments Yuo don't need to compute and use row at all :) It is not used in the loop ;)

Vishesh_Sanghani + 0 comments [deleted]

meyer_greg_pro + 1 comment How can you the computation time?

lifekills + 0 comments The submissions tab then View Results

avasilev + 0 comments `std::string sentence; getline(cin, sentence); int length = sentence.length(), columns = ceil(sqrt(length)), rows = floor(sqrt(length)); if(rows*columns < length) rows = columns; for(int i = 0; i < columns; ++i) { for(int j = 0; j < rows; ++j) { if(i + j * columns < length) cout << sentence[i + j * columns]; } cout << ' '; }`

nagavenkatara + 0 comments Thank you for the hint. O(s.Length)

string s = Console.ReadLine().Trim(); var rowLength = (int)Math.Sqrt(s.Length)+1; if(Math.Sqrt(s.Length)-(int)Math.Sqrt(s.Length) == 0) rowLength = (int)Math.Sqrt(s.Length); for(int index = 0; index < rowLength;index++){ var verticalStrip = string.Empty; var k = index; while( k < s.Length){ verticalStrip += s[k]; k += rowLength; } Console.Write(verticalStrip+ " "); }

ryanfehr18 + 0 comments A solution to this question has been provided on the HackerRank solution repo! If you are interested in solutions to HackerRank problems as well as gaining some experience working on an GitHub open source project, check out HackerRank Solutions. We are working to make a repository of solutions to every HackerRank question.

AGRN96 + 1 comment Did it in this manner and got 0s in all test cases. https://www.hackerrank.com/challenges/encryption/forum/comments/280014

dangerDon + 0 comments Ya, I did the same just in python, you can also use ceil here

int coloumn = sqrt(length);

to remove this

if(row * coloumn < length){ coloumn+=1; }

i did that

Coder_AMiT + 0 comments I did :)

s = list(input().strip()) L = len(s) row = math.floor(L**(1/2)) col = math.ceil(L**(1/2)) for i in range(col): x = 0 while True: try: print(s[i+x],end='') x+= col except: break print(' ',end='')

Rys23 + 1 comment I did it this way

int main(){ char* s = (char *)malloc(10240 * sizeof(char)); scanf("%s",s); int len = strlen(s); int columns = ceil(sqrt(len)); for(int i = 0; i < columns; i++) { for(int j = i; j < len; j += columns) { printf("%c", s[j]); } printf(" "); } return 0; }

all of the test cases take 0s

yarpit90 + 4 comments I did it this way, simlar to what you have done

But its showing wrong answer, even though my output is same as was expected, same is happening for testcase1 as well, "feedthedog".

vkumarjjp123 + 1 comment that exactly what is happening with me too...

CometLi + 0 comments To solve this problem, just stop outputting when it reaches the length of the string. Hope it will help.

mrunalidhenge99 + 3 comments same issue. hv u solve it?

CometLi + 0 comments [deleted]CometLi + 0 comments To solve this problem, just stop outputting when it reaches the length of the string. Hope it will help.

HarryPotter_421 + 0 comments same issue with me also

CometLi + 0 comments [deleted]snoisingla + 1 comment This happens beacuse you are adding undefined character into the string. If a char in the array is not set it will be undefined. When you are building the string don't add those charcters which are not set.

harshilajadiya + 0 comments a great help thank you.

sandyboy + 0 comments without 2d array

#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; int main() { int r,c; string s; cin>>s; int l=s.length(); r=floor(sqrt(l)); c=ceil(sqrt(l)); if((r*c)<l) r++; for(int i=0;i<c;i++) { for(int j=i;j<l;j+=c) { cout<<s[j]; } cout<<" "; } return 0; }

[deleted] + 1 comment How are checking the running time of your solution?

vishu006 + 1 comment If you are asking about running time in general, reading about Time Complexity will definitely help.

If this is related to time that test cases take for running your code, just hover on them and you would see their respective time.

Hope this helps

[deleted] + 0 comments This is related to test case run time. I tried hovering over test cases, but i am unable to see the run time of that case.

vishu006 + 0 comments Hey that was a great tip!! Passed all test cases in 0s in Python.

Check it out https://www.hackerrank.com/challenges/encryption/submissions/code/50674389

ahmad_abu_sheikh + 0 comments yep, 2D array is very unnecessary.

ravikumar_2402_1 + 0 comments # include

# include

# include

# include

# include

using namespace std;

int main(){ string s; cin >> s; int count=0; int l=s.length(); int rows=floor(sqrt(l)); int col=ceil(sqrt(l)); if(rows*col

`for(int i=0;i<rows&&m<l;i++){ cout<<s[m]; count++; m=m+col;}k++;n++; if(count<l) cout<<" ";} return 0;`

}

y_aitloutou + 1 comment how do you check the time per subimssion ?

CometLi + 0 comments Sorry I don't know how to do this either. :( If you figure it out could you please let me know too? Thx a lot.

smitparekh1995 + 0 comments [deleted]smitparekh1995 + 0 comments [deleted]will_whyang + 0 comments Don't need to use a 2d array.

package main import ( "fmt" "math" ) func main() { var text string fmt.Scan(&text) l := len(text) m := math.Sqrt(float64(l)) lower := int(math.Floor(m)) upper := int(math.Ceil(m)) // upper * upper must be >= l, so it safe to do following. Or just simply do one lower += 1 for lower * upper < l { lower += 1 } index := 0 for i := 0; i < upper; i++ { for j := 0; j < lower; j++ { index = i + j * upper if index >= l { break } fmt.Printf("%c", text[index]) } fmt.Printf(" ") } }

danglingP0inter + 0 comments [deleted]_dec0der_ + 0 comments int n=str.length(); int col=ceil(sqrt(n)); for(int i=0;i<col;i++) { for(int j=0;i+j<n;j+=col) { cout<<str[i+j]; } cout<<" "; }

sahulrajhansa + 0 comments *My code without using two dimensional array.*import java.io.

*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*;public class Solution { public static void main(String[] args) { Scanner in = new Scanner(System.in); String s = in.next(); int hop = (int)Math.ceil(Math.sqrt(s.length())); int i = 0, j = 1,count = 0; while ( j <= hop ){ while( i < s.length()){ System.out.print(s.charAt(i)); i+=hop; } System.out.print(" "); i = j; j++; } in.close(); } }

JJJason + 0 comments My Python3 solution. Do not have to use 2-d array.

#!/bin/python3 import sys s = input().strip() rows = int(len(s) ** 0.5) if rows < len(s) ** 0.5: columns = rows + 1 else: columns = rows for i in range(columns): print(s[i::columns], end = ' ')

rahulkalita8 + 0 comments [deleted]rahulkalita8 + 0 comments Without any 2D array.

void encryption(string s) { int n = s.length(); int x = floor(sqrt(n)); int y = ceil(sqrt(n)); int k=0; if((x*y)<n) x++; for(int i=0; i<y; i++){ for(int j=0; j<x; j++){ k=i+(j*y); if(s[k]!='\0') cout<<s[k]; } cout<<" "; } }

d_kunal96 + 0 comments This worked for me..

int rows = 0, cols = 0, i, j = 0; StringBuffer sb = new StringBuffer();

`//rows = (int)Math.floor(Math.pow(s.length(), 0.5)); cols = (int)Math.ceil(Math.pow(s.length(), 0.5)); for(i = 0; i < cols; i++) { for(j = i; j < s.length(); j += cols) { sb.append(s.charAt(j)); } sb.append(" "); } return sb.toString();`

aniketnath283 + 0 comments solution without using 2d array https://www.hackerrank.com/challenges/encryption/forum/comments/483060

alimobasshir21 + 1 comment you mean like this '#include

using namespace std;

int main() {

`string s; getline(cin, s); int length=s.length(); int ul=0,ll=0; for(int i=1; i<=9; i++) { if(i*i>length) { ul=i; ll=i-1; break; } else if(i*i==length) { ul=i; ll=i; break; } } //cout<<ul<<" "<<ll<<endl; int i=0; while(i<ul && i<s.length()) { int j=i; while(j<s.length()) { cout<<s[j]; j=j+ul; //cout<<j; } cout<<" "; i=i+1; } return 0;`

}

aniketnath283 + 0 comments Yea something like that. The main logic is first find out the square root of length of the string. Then round of the square root value. Then take a loop upto the round of value and take an inner loop where you will append the result characters by jumping the round of value. Eg: hihowareyou. This string has 11 characters. Now its square root is 3.3166.... now if we round of this values are it will be 4. So the maximum no of append will be 4

Thinkster + 0 comments How about Ruby?

def sqrt(l); Math.sqrt l end def encryption(s) # strip off any whitespaces s.gsub! /\s+/, '' # length of the string without whitespaces len = s.length # let us set the (rows, cols) based on floor & ceil of the string length rows, cols = sqrt(len).floor, sqrt(len).ceil # if the product of rows and cols is less than string length, set both to same rows = cols = sqrt(len).ceil if rows * cols < len # each index of this array will hold chars (c..row), where for each c, # we get all the values until row encrypted = [] (0...rows).each do |i| encrypted << s[((i % rows) * cols)..((i % rows) * cols) + cols - 1].chars end # we use the first entry and zip it with the rest of entries, # and join them to make a complete string encrypted[0].zip(*encrypted[1..-1]).map do |cipher| cipher.compact.join + ' ' end.join end

hellomici + 1 comment I solved it without arrays, too in Python. A very simple Python3 code aka Python at its best :)

import math def encryption(s): s = s.replace(" ", "") sr = len(s) ** 0.5 # which is square root col = int(sr) if math.ceil(sr) == int(sr) else int(sr)+1 word = '' for i in range(col): p = i while p < len(s): word = word + s[p] p += col word = word + ' ' return word

gebrishab + 0 comments Excellent!

noeleom + 0 comments Definitely did not use 2d array. Makes more sense it grab string at indexes when you know it's needed :+1:

fran_rabljenovi1 + 0 comments Yes

for(int i = 0; i < w; i++) { for(int j = 0; j < h; j++) { if(j w + i < z.length()) o += z.charAt(j * w + i); else break; } o += ' '; }

Edit: multiplication sign got removed for some reason.

nipunaluthge4815 + 1 comment [deleted]nipunaluthge4815 + 0 comments static String encryption(String s) { s = s.replaceAll("\\s",""); String st = ""; int ceil = (int)Math.ceil(Math.sqrt(s.length())); for(int i = 0; i < ceil; i++){ for(int j = i; j < s.length(); j+=ceil){ st += s.charAt(j); } st += " "; } return st.trim(); }

0xpurpl3 + 0 comments **i tried this and it passed all cases:**static String encryption(String s) { int len=s.length(); System.out.println(len); String s1 =""; for(int i = 0 ; irow) row+=1; System.out.println(col); for(int i=0 ; i s2+=" "; } return s2; }

abhishekagarwa15 + 0 comments k=len(s) w=[] r=int(math.sqrt(k)) f=r+1 for i in range(0,r+1): for j in range(i,len(s),f): w.append(s[j]) w.append(" ") w.pop() w="".join(w) return(w)

ahmetcan_ozturk + 0 comments Pseudo-code to solve using iteration (without 2d array):

`sn = replace spaces of s L = length of sn rows = math.floor(math.sqrt(L)) cols = math.ceil(math.sqrt(L)) if (rows * cols < L) then rows = cols accumulate array arr of size rows * cols let row = -1 for i = 0 to L: if (i % cols == 0) then row++ arr[((i % cols) * rows) + row] = sn[i] set result to an empty list for i = 0 to length of arr: if (i % rows == 0 and i > 0) then result.append(" ") result.append(arr[i]) return string.join("", result)`

bobthisawesome + 0 comments Iterative is a little hard to get but here is my way:

`String e = new String(""); int r= (int)Math.sqrt(s.length()); if(r*r!=s.length()) r++; for(int i=0;i<r;i++){ int j=0; while(j*r+i<s.length()){ e = e+s.charAt(j*r+i); j++; } e=e+" "; } return e;`

rutvikumak + 0 comments I haven't use 2d array in my solution

static String encryption(String s) {

`char arr[] = s.toCharArray(); String ans = new String(); int length = 0; if(Math.sqrt(arr.length) % 1 == 0){ length = (int)(Math.sqrt(arr.length)); }else{ length = (int)(Math.sqrt(arr.length)+1); } System.out.println(arr.length+" "+length); for(int i = 0; i < length ; i++) { for(int j=i; j < arr.length ; j++){ if(j < arr.length){ ans+=arr[j]; j+=(length-1); } } if(i != length){ ans += ' '; } } return ans; }`

shiplu + 0 comments I did it with single array. Just calcualte the index and print.

saurabh_jasper + 16 comments why is this happening?

aditya_avs + 1 comment It may be due to trailing spaces. Add a check for iter less than length, print only then. You might be using a direct cout.

magician03 + 0 comments [deleted]

saurabh_jasper + 0 comments Sir,I took care about trailing spaces, but irrespective of no. of trailing spaces result was same, ie.it passed few test cases but failed is some.

akankshakunwar81 + 0 comments have you solved this ??? Iam getting the same problem

s_w_zzang + 0 comments Have you resolved? Same problem for me. I also checked trailing space

magician03 + 1 comment same issue for me, did u solve it ?

avkumar_19 + 0 comments the problem is you are printing '\0',try applying an if condition and print only if it's not '\0';

vinesh9876 + 0 comments same issue here

abhinavdayal + 1 comment It is because you need to ensure that rows*cols >= Lemgth of string.

We need to keep rows <= cols so we keep rows as the floor of squareroot and cols as the ceiling.

now if rows*cols < L then you need to add another row to make things fit.

vinesh9876 + 0 comments why dose it matter if I'm getting the same output

louisehmbc + 1 comment I'm having the same problem, did you solve it? What's stranger is that the first testcase doesn't mind whether or not I add a trailing space at the end, but the second two don't work even when they're identical (no trailing whitespace).

int main(){ string s; cin >> s; // Remove spaces from string for (auto it = s.begin(); it != s.end();){ if (*it == ' ') s.erase(it); else ++it; } // Caculate grid sizes int floor = sqrt(s.size()); int ceiling = sqrt(s.size()) + 1; if (floor * ceiling < s.size()) (floor < ceiling)? floor += 1 : ceiling += 1; // Create grid vector<string> encrypted(ceiling); for (int i = 0; i < floor; ++i) { for (int j = 0; j < ceiling; ++j) { encrypted[j] += s[j + i * ceiling]; } } // Ugly output method to remove trailing spaces for (int i = 0; i < encrypted.size(); ++i) { std::cout << encrypted[i]; if (i < encrypted.size()-1) std::cout << " "; } std::cout << std::endl; return 0; }

vinesh9876 + 1 comment yeah its not working

lianyuu + 0 comments string encryption(string s) { int count = 0; for(int i = 0; i<s.length(); i++) if(s[i]!=' '){ s[count++] = s[i]; } s[count] = '\0'; int row = floor(sqrt(count)); int col = ceil(sqrt(count)); if(row*col< count){ row++; } int k[row][col]; int t = 0; for(int i = 0; i<row; i++){ for(int j = 0; j<col; j++){ if(t<count){ k[i][j] = s[t]; cout << s[t]; t++; } } } string out = ""; t = 0; for(int i = 0; i<col; i++){ for(int j = 0; j<row; j++){ if(t<count &&(k[j][i]!= '\0'&&k[j][i]!=NULL)){ out += k[j][i]; t++; } } out = out + " "; } return out; }

amrata_kasture + 0 comments I am facing same issue for test cases 1,3,6. I downloaded cases and output is correct but still test cases are failing. Anyone figured out cause?

sudhar287 + 0 comments After proceesing the input, my 2D matrix looked like this. When printing it column wise, ensure that

*cout*is not executed when a emply space is encountered i.e*'\0*'mails4ipiyush + 0 comments I am also facing the same issue. I even trimmed the trailing spaces. Still its showing wrong answer.

khadar111 + 0 comments for(int i=0;i

svfarande + 0 comments Same problem :(

a65b4139 + 1 comment I am having the exact same problem.

This is my code:

import java.io.*; import java.util.*; public class Solution { public static void main(String[] args) { Scanner in = new Scanner(System.in); String message = in.nextLine(); String ciphertext = encrypt(message); System.out.println(ciphertext); } private static char[][] buildGrid(String message, int rows, int columns) { char[][] grid = new char[rows][columns]; char[] chars = message.toCharArray(); int row; int column; for (int i = 0; i < chars.length; i++) { row = i / columns; column = i % columns; grid[row][column] = chars[i]; } return grid; } private static String encrypt(String message) { int length = message.length(); double lengthSqrt = Math.sqrt(length); int rows = (int) Math.floor(lengthSqrt); int columns = (int) Math.ceil(lengthSqrt); rows = (rows * columns < length) ? columns : rows; char[][] grid = buildGrid(message, rows, columns); StringJoiner sj = new StringJoiner(" "); StringBuilder sb = new StringBuilder(); int charsTotal = 0; for (int column = 0; column < columns; column++) { sb.setLength(0); for (int row = 0; row < rows; row++) { if (charsTotal <= length) { sb.append(grid[row][column]); charsTotal++; } } sj.add(sb.toString()); } return sj.toString(); } }

Anutrix + 0 comments /** * * @author Anutrix */ import java.io.*; import java.util.*; public class Encrytion { public static void main(String[] args) { Scanner in = new Scanner(System.in); String msg = in.nextLine(); int n = msg.length(); int y = (int) Math.ceil(Math.sqrt(n)); for(int i=0; i<y; i++){ int pos = i; while(pos<n){ System.out.print(msg.charAt(pos)); pos +=y; } System.out.print(" "); } } }

Hows this?

blazefrostrider + 0 comments I had the same mistake and i solved it by checking whether it is a letter before printing it . You can identify your extra spaces by printing '#' or anything else instead of a space . Also , the row calculation is wrong when applied to second test case . I calculated row by Ceil(len of input / col)

kemalsreenivas38 + 0 comments Check if the character is null before printing.

samar5yadav + 5 comments `import math s=input() sm=s.replace(" ","") r=math.floor(math.sqrt(len(sm))) c=math.ceil(math.sqrt(len(sm))) for i in range(c): print(sm[i::c],end=" ")`

short and sweet. that's why you gotta love python

hamza_emra + 1 comment could you please explain the for loop part? specialy sm[i::c] part

samar5yadav + 2 comments okay. lets take example that is given in question.

input: if man was meant to stay on the ground god would have given us roots

sm=ifmanwasmeanttostayonthegroundgodwouldhavegivenusroots

now we know the number of rows(r=7) and columns(c=8)

what sm[i::c] means is start from sm[i] to end of sm print every character with indices i,i+c,i+2c,i+3c... till the end. After that add " ". so let's take i=0 for example that means print characters with indices 0,8,16,24,32,40,48 (till you reach the end of sm). so here it is "imtgdvs" then add " ". Same goes on on till you are done with all the columns.

i hope this helps!

hamza_emra + 0 comments It helped alot thank you so much

ashutoshm1771 + 0 comments brilliant

Being_human + 0 comments NICE AND SORT

array_yar + 0 comments [deleted]pdog1111 + 0 comments Same idea but a little simpler:

import math s = input() w = int(math.ceil(len(s.strip())**.5)) print(" ".join([s[i::w] for i in range(w)]))

ajsmith22 + 0 comments No need to calculate

`r`

here.

sujithvm + 12 comments This is the solution i submitted. Can anyone please tell me why ideone is giving correct answer for TestCase 1 and Hackerrank is giving a different answer. No difference in code

`TestCase : feedthedog Ideone output : fto ehg ee dd Hackerrank editor output : fto ehg ee`

visrahane + 1 comment take care of the space(blank) and it works.

manavkothari + 2 comments how to solve space and null problem in c?

sachin_dandavati + 0 comments First initialise it with null or ' '. Then do function, it will work

srikanthk555 + 0 comments use isprint function before printing characters to stdin that would be useful in checking non printable characters like space etc,,

karantirthani + 1 comment i am facing the same problem

etayluz + 5 comments Here's one way:

`int main(){ char* s = (char *)malloc(10240 * sizeof(char)); scanf("%s",s); int len = strlen(s); int rows = floor(sqrt(len)); int cols = ceil(sqrt(len)); if (rows * cols < len) { rows = cols; } for (int c = 0; c < cols; c++) { for (int r = 0; r < rows; r++) { int idx = c + r * cols; if (idx < len) { printf("%c", s[idx]); } } printf(" "); } return 0; }`

GowthamSiddarth + 0 comments why did you allocate 10240 specifically?

highly_rated + 0 comments [deleted]vidushig2 + 1 comment int main(){ char s[10000]; cin >> s; int l = strlen(s); int rows = floor(sqrt(l)); int columns = ceil(sqrt(l)); if((rows*columns)

`return 0;`

}

test case 1 and 2 are failing.Please tell why

shahpujan1992 + 0 comments Input for 1st test case is- feedthedog Output - fto ehg ee dd

pp43076 + 2 comments But the question says that if two or more grids satisfy the condition for number of rows and columns, then choose the one with min rows(n) x columns(m).

The above code does not take minimum n x m.

Example : chillout It gives different answers for 2 x 4 and 3 x 3. And 2 x 4 has min n x m.

Testcase giving wroung output

ankit_mahajan_19 + 2 comments i agree with this statement. it should be 2*4 = 8 instead of 3*3 = 9.

lausanne_man + 1 comment Yes. For some L the constraint can't be met. 8 is one example: sqrt(8) ~= 2.8, so a 3x3 grid violates the constraint, and 2x3 which meets it is too small for 8 elements.

Another test where L = 3 has the same problem.

bearhack + 0 comments The whole point to constraining the grid parameters is to make sure that they are within 1 unit of each other. Thus, 2x4 is outside of the constraints of floor(sqrt(8)) = 2 and ceil(sqrt(8)) = 3 because 4 is greater than 3. However, because 2x3 is too small to use 8 units, you

*can*use 3x3 and still fit within the constraints. It's a really roundabout way of just saying keep your grid parameters within 1 unit of each other.

Aashish_J + 0 comments Column cannot be 4 (should be <= 3)

adi341875 + 0 comments According to constraint n,m should lie between the floor and ceil. In this case: floor = 2; ceil =3; For minimum area, 2*4 should be choosen but it violates the constraints. i.e. column >ceil; So we choose 3*3 to satisfy the condition.

Happy Coding :)

pankaj_mittal372 + 0 comments this code executed all the test cases but i think this code has some fault.....let say len=7 so we will get rows=2 and cols=3 rows*cols

ScottDuane + 4 comments Same problem here. My compiler outputs "fto ehg ee dd" for Sample #2 but Hackerrank outputs "fto ehg ee". Same thing with Test case #6, which is one of the test cases that Hackerrank graded "wrong". Here's my code:

https://www.hackerrank.com/challenges/encryption/submissions/code/11082541

areyoukiddingme + 0 comments similar issue here. http://ideone.com/PZaK34

StevoTVR + 0 comments I think your problem is on line 40. Everything needs to be flipped.

MetonymyQT + 0 comments Because you are printing unpritable characters. Check if the character is printable, if it is a letter.

lausanne_man + 0 comments It appears Sample #2 has been fixed.

thugwaffle + 0 comments I have the same problem. Spent a decent amount of time trying to find the bug, but I put it in Ideone and got the right answer.

Tatparya + 0 comments I had the same problem. You are basically going out of bounds when reading the string ( which is a memory error ) The HackerRank compiler just stops executing the code when you go out of bounds. Suggestion : Check for boundary conditions

alexgbelov + 0 comments I'm guessing because you never initialized the default value in arr, so you don't know if its going to be a space character. So, if (arr[r][c] != ' ') is useless.

shubham_sharma14 + 0 comments if (arr=='\0'); break

shubhinder + 0 comments use this :----->

if(grid[j][i]==(char) 0){ break; }

TheRevenant + 0 comments Ignore the '\0' characters when displaying the output.

rajendra + 0 comments just add the condition if you are working in java char[i][j]!=0 since a emty cell in char array is 0 in java, here is my solution for that https://www.hackerrank.com/challenges/encryption/submissions/code/16072054

shahpujan1992 + 0 comments In this scenario if u used floor and ceil method then it gives row=2,col=3.. Actually to store that much data we need row=2,col=4.. So I done it and directly prints the characters without storing in the 2D array..

mserranom + 0 comments Same issue here, correct results are marked as failures:

import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; public class Solution { public static void main(String[] args) { Scanner in = new Scanner(System.in); String s = in.next(); int[] gridSize = findMinimumArea(s.length()); char[][] grid = new char[gridSize[0]][gridSize[1]]; int cursor = 0; for(int row = 0; row < gridSize[0]; row++) { for(int col = 0; col < gridSize[1]; col++) { if(cursor >= s.length()) { break; } else { grid[row][col] = s.charAt(cursor); cursor++; } } } String ans = ""; for(int col = 0; col < gridSize[1]; col++) { for(int row = 0; row < gridSize[0]; row++) { ans += grid[row][col]; } ans += " "; } System.out.println(ans.trim()); } // [rows, cols] private static int[] findMinimumArea(int n) { int min = (int)Math.round(Math.floor(Math.sqrt(n))); int max = (int)Math.ceil(Math.sqrt(n)); for(int row = min; row <= max; row++) { for(int col = row; col <= max; col++) { if(row * col >= n) { return new int[]{row,col}; } } } throw new Error("shouldn't get here : " + n); } }

StopAsh12 + 1 comment hey what does poosible square with the minimum have to do with this,as i think there are going to be only two square.ceiling and floor of an integer are going to be two consecutive number,following the constraints one can be increased and the other can only be decreased.so there are going to be only 2 square.The language of the question could have been easy to understand.

shashank21jHackerRank Admin + 1 comment Actually square is unique, there is no question of max/min.

Will change the statementshubham_sharma14 + 3 comments /*If multiple grids satisfy the above conditions, choose the one with the minimum area, i.e. rowsÃ—columns. */

in test case "chillout" they have taken 3*3 but I want to take 2*4 and when i take 2*4 they show wrong answer!!!!!!

shubham_sharma14 + 2 comments leave it.

i got it

briandignan + 1 comment So what is the correct output here? In the case of "chillout", shouldn't it be 2*4 (area 8) and not 3*3 (area 9)? 2*4 meets the constraints. It's got more columns than rows, and the number of rows is greater/equalto floor(sqrt(L))

alkis + 1 comment You are right about the lower limit. What about the upper limit?

briandignan + 0 comments Ahh right. I forgot about that part. Thanks!

manthan19 + 0 comments coz 4 is greater than ceil of sqrt(8)

mish_16 + 1 comment in test case "chillout" my output and expected output are same. still they are showing wrong answer..help me out shubham_sir.. and same is the case with feedthedog test case.

shubham_sharma14 + 0 comments /*If multiple grids satisfy the above conditions, choose the one with the minimum area, i.e. rowsÃ—columns. */

also take care of ceil and floor function

Sort 942 Discussions, By:

Please Login in order to post a comment