We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Loading...
  • Practice
  • Compete
  • Jobs
  • Leaderboard
  • Hiring developers?
  1. Practice
  2. Algorithms
  3. Implementation
  4. Encryption
  5. Discussions

Encryption

  • Problem
  • Submissions
  • Leaderboard
  • Discussions
  • Editorial

Sort 757 Discussions, By:

votes
  • recency
  • votes

Please Login in order to post a comment

  • Schuetzl 4 years ago+ 39 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?

    42|
    Permalink
    • dan_mar_042 4 years ago+ 0 comments

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

      -5|
      ParentPermalink
    • xXGoziXx 4 years ago+ 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

      -7|
      ParentPermalink
      • REX_37 11 months ago+ 1 comment

        where to se the timing?

        0|
        ParentPermalink
        • lwchkg 9 months ago+ 0 comments

          I guess the function to see the times are removed.

          0|
          ParentPermalink
    • cangktvn 4 years ago+ 4 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;
      }
      
      10|
      ParentPermalink
      • vidushig2 4 years ago+ 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;
        

        }

        please tell why test case 1 and 2 are failing.

        -3|
        ParentPermalink
        • slash331erock 1 year ago+ 3 comments

          same problem my output and expected output is exactly the same still it is showing wrong answer

          2|
          ParentPermalink
          • Vardhan 6 months ago+ 2 comments

            Yes same problem with me. Any idea how to rectify that?

            0|
            ParentPermalink
            • B1ack 6 months ago+ 0 comments

              maybe problem with an extra space in your result

              -1|
              ParentPermalink
            • scan2 5 months ago+ 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)

              2|
              ParentPermalink
          • lkrajcsovicz 5 months ago+ 0 comments

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

            0|
            ParentPermalink
          • 2019201057_anur 4 months ago+ 0 comments

            because u need to append '\0' extra and while looping ...just break when \0 occurs

            0|
            ParentPermalink
      • ganeshmukesh111 3 years ago+ 8 comments

        how you manage to skip spaces from orignal string (s)?

        -2|
        ParentPermalink
        • beshm 3 years ago+ 1 comment

          if you are using java, you could use trim method.

          -3|
          ParentPermalink
          • vyavaharkardeve1 2 years ago+ 0 comments

            trim() removes only the spaces before and after the string.

            0|
            ParentPermalink
        • beastieric 3 years ago+ 0 comments

          There are no spaces in the original string.

          2|
          ParentPermalink
        • knivendha 2 years ago+ 0 comments

          usre replace()

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

          1|
          ParentPermalink
        • naeemalicious 2 years ago+ 0 comments

          s.replaceAll(" ", "");

          2|
          ParentPermalink
        • tthrash 1 year ago+ 0 comments
          [deleted]
          0|
          ParentPermalink
        • tthrash 1 year ago+ 0 comments

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

          0|
          ParentPermalink
        • vishal_nimavat 1 year ago+ 0 comments

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

          0|
          ParentPermalink
        • B1ack 6 months ago+ 1 comment

          you can use replace method - > str.replace(" ","")

          0|
          ParentPermalink
          • Vardhan 6 months ago+ 1 comment

            The answers are matching, still the TestCases are not passing. I used the replace Method.

            0|
            ParentPermalink
            • B1ack 6 months ago+ 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.

              0|
              ParentPermalink
      • tarabahadur_tha1 2 years ago+ 1 comment

        Could you please explain the logic behind determining the noOfRows and noOfCols

        0|
        ParentPermalink
        • vishal_nimavat 1 year ago+ 0 comments

          in java

              final double length = string.length();
                      int row = (int) Math.floor(Math.sqrt(length));
                      final int column = (int) Math.ceil(Math.sqrt(length));
          
          0|
          ParentPermalink
      • abkumar192000 6 months ago+ 0 comments

        clap;

        0|
        ParentPermalink
    • Kthompso 4 years ago+ 3 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?

      15|
      ParentPermalink
      • qu4ku 4 years ago+ 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)))))
        
        4|
        ParentPermalink
        • FilipF 3 years ago+ 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.

          11|
          ParentPermalink
          • dangerDon 3 years ago+ 1 comment

            This is what i am searching for, One liner

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

            0|
            ParentPermalink
            • aymansubbagh 3 weeks ago+ 0 comments

              seriously yeah, my code is horrific

              0|
              ParentPermalink
          • Dragg 3 years ago+ 1 comment

            this is awesome! :D

            0|
            ParentPermalink
            • ganeshmukesh111 3 years ago+ 0 comments

              thanks

              0|
              ParentPermalink
          • amoghmulge 9 months ago+ 0 comments

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

            0|
            ParentPermalink
        • mridula_bvs 2 years ago+ 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)))))
          
          1|
          ParentPermalink
          • shawnkmeier 9 months ago+ 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.

            0|
            ParentPermalink
        • ashutoshdikshit1 2 months ago+ 1 comment
          [deleted]
          0|
          ParentPermalink
          • ashutoshdikshit1 2 months ago+ 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 .

            0|
            ParentPermalink
            • bala12901 1 month ago+ 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)
              
              0|
              ParentPermalink
              • bala12901 1 month ago+ 0 comments
                        **   if x<len(arr[y]):**
                

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

                0|
                ParentPermalink
      • adityasrb 10 months ago+ 0 comments
        [deleted]
        0|
        ParentPermalink
      • manishmeshram51 3 months ago+ 0 comments

        can you please explain how you used lambda in your code?

        0|
        ParentPermalink
    • qu4ku 4 years ago+ 3 comments

      once you said it it actually seems to be stupid to solve it with arrays :D

      1|
      ParentPermalink
      • MichaelDsa 1 year ago+ 0 comments

        Yeah, the hint was great! :D

        1|
        ParentPermalink
      • viigihabe 1 year ago+ 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.

        0|
        ParentPermalink
      • CristianNaziru 9 months ago+ 1 comment

        ... I solved it with a matrix, feelsbad...

        0|
        ParentPermalink
        • smitparekh1995 9 months ago+ 0 comments
          [deleted]
          0|
          ParentPermalink
    • Epshita 3 years ago+ 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.

      -3|
      ParentPermalink
    • shouki 3 years ago+ 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.

      1|
      ParentPermalink
      • AndreaR 3 years ago+ 1 comment

        yes, C# .02s, no array, using StringBuilder

        0|
        ParentPermalink
        • KUTlime 2 years ago+ 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(" ");
                  }
              }
          }
          
          3|
          ParentPermalink
    • mk9440 3 years ago+ 1 comment
      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);}}
      
      0|
      ParentPermalink
      • naeemalicious 2 years ago+ 0 comments

        You forgot to remove the spaces between the words.

        1|
        ParentPermalink
    • lifekills 3 years ago+ 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.

      0|
      ParentPermalink
    • ashsingh1 3 years ago+ 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(" ");
              }
          }
      
      6|
      ParentPermalink
      • james_kurakula 3 years ago+ 2 comments

        what is the use of this line in your code.....

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

        1|
        ParentPermalink
        • zmingxie 3 years ago+ 0 comments

          I don't see why this line is needed either...

          0|
          ParentPermalink
        • _Nitin_Verma_ 3 years ago+ 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)

          1|
          ParentPermalink
      • chabrecek 9 months ago+ 0 comments

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

        1|
        ParentPermalink
      • Vishesh_Sanghani 8 months ago+ 0 comments

        Lastly the string must be trimmed to aviod Blank spaces.

        0|
        ParentPermalink
    • meyer_greg_pro 3 years ago+ 1 comment

      How can you the computation time?

      0|
      ParentPermalink
      • lifekills 3 years ago+ 0 comments

        The submissions tab then View Results

        1|
        ParentPermalink
    • avasilev 3 years ago+ 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 << ' ';
      }
      
      4|
      ParentPermalink
    • nagavenkatara 3 years ago+ 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+ " ");
      }
      
      0|
      ParentPermalink
    • ryanfehr18 3 years ago+ 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.

      -6|
      ParentPermalink
    • AGRN96 3 years ago+ 1 comment

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

      1|
      ParentPermalink
      • dangerDon 3 years ago+ 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

        1|
        ParentPermalink
    • Coder_AMiT 3 years ago+ 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='')
      
      5|
      ParentPermalink
    • Rys23 3 years ago+ 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

      0|
      ParentPermalink
      • yarpit90 2 years ago+ 4 comments

        I did it this way, simlar to what you have done

        image

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

        image

        2|
        ParentPermalink
        • vkumarjjp123 2 years ago+ 1 comment

          that exactly what is happening with me too...

          1|
          ParentPermalink
          • CometLi 2 years ago+ 0 comments

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

            0|
            ParentPermalink
        • mrunalidhenge99 2 years ago+ 3 comments

          same issue. hv u solve it?

          1|
          ParentPermalink
          • CometLi 2 years ago+ 0 comments
            [deleted]
            0|
            ParentPermalink
          • CometLi 2 years ago+ 0 comments

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

            0|
            ParentPermalink
          • pranshusingh421p 5 months ago+ 0 comments

            same issue with me also

            0|
            ParentPermalink
        • CometLi 2 years ago+ 0 comments
          [deleted]
          0|
          ParentPermalink
        • snoisingla 2 years ago+ 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.

          1|
          ParentPermalink
          • harshilajadiya 11 months ago+ 0 comments

            a great help thank you.

            0|
            ParentPermalink
    • sandyboy 2 years ago+ 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;
      }
      
      0|
      ParentPermalink
    • [deleted] 2 years ago+ 1 comment

      How are checking the running time of your solution?

      0|
      ParentPermalink
      • vishu006 2 years ago+ 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

        0|
        ParentPermalink
        • [deleted] 2 years ago+ 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.

          0|
          ParentPermalink
    • vishu006 2 years ago+ 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

      0|
      ParentPermalink
    • ahmad_abu_sheikh 2 years ago+ 0 comments

      yep, 2D array is very unnecessary.

      0|
      ParentPermalink
    • ravikumar_2402_1 2 years ago+ 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;
      

      }

      -1|
      ParentPermalink
    • y_aitloutou 2 years ago+ 1 comment

      how do you check the time per subimssion ?

      0|
      ParentPermalink
      • CometLi 2 years ago+ 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.

        0|
        ParentPermalink
    • smitparekh1995 2 years ago+ 0 comments
      [deleted]
      0|
      ParentPermalink
    • smitparekh1995 2 years ago+ 0 comments
      [deleted]
      0|
      ParentPermalink
    • will_whyang 2 years ago+ 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(" ")
          }
      }
      
      0|
      ParentPermalink
    • danglingP0inter 2 years ago+ 0 comments
      [deleted]
      0|
      ParentPermalink
    • _dec0der_ 2 years ago+ 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<<" ";
        }
      
      0|
      ParentPermalink
    • sahulrajhansa 2 years ago+ 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(); } }

      -1|
      ParentPermalink
    • JJJason 2 years ago+ 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 = ' ')
      
      -2|
      ParentPermalink
    • rahulkalita8 1 year ago+ 0 comments
      [deleted]
      0|
      ParentPermalink
    • rahulkalita8 1 year ago+ 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<<" ";
          }
      
      }
      
      1|
      ParentPermalink
    • d_kunal96 1 year ago+ 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();
      
      -1|
      ParentPermalink
    • aniketnath283 1 year ago+ 0 comments

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

      0|
      ParentPermalink
    • alimobasshir21 1 year ago+ 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;
      

      }

      0|
      ParentPermalink
      • aniketnath283 1 year ago+ 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

        0|
        ParentPermalink
    • Thinkster 1 year ago+ 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
      
      0|
      ParentPermalink
    • hellomici 11 months ago+ 0 comments

      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
      
      2|
      ParentPermalink
    • noeleom 10 months ago+ 0 comments

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

      1|
      ParentPermalink
    • fran_rabljenovi1 5 months ago+ 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.

      0|
      ParentPermalink
  • saurabh_jasper 3 years ago+ 16 comments

    image

    image

    why is this happening?

    18|
    Permalink
    • aditya_avs 3 years ago+ 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.

      0|
      ParentPermalink
      • magician03 3 years ago+ 0 comments
        [deleted]
        0|
        ParentPermalink
    • saurabh_jasper 3 years ago+ 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.

      0|
      ParentPermalink
    • akankshakunwar81 3 years ago+ 0 comments

      have you solved this ??? Iam getting the same problem

      1|
      ParentPermalink
    • s_w_zzang 3 years ago+ 0 comments

      Have you resolved? Same problem for me. I also checked trailing space

      0|
      ParentPermalink
    • magician03 3 years ago+ 1 comment

      same issue for me, did u solve it ?

      0|
      ParentPermalink
      • avkumar_19 3 years ago+ 0 comments

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

        2|
        ParentPermalink
    • vinesh9876 3 years ago+ 0 comments

      same issue here

      0|
      ParentPermalink
    • abhinavdayal 3 years ago+ 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.

      0|
      ParentPermalink
      • vinesh9876 3 years ago+ 0 comments

        why dose it matter if I'm getting the same output

        0|
        ParentPermalink
    • louisehmbc 3 years ago+ 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;
      }
      
      0|
      ParentPermalink
      • vinesh9876 3 years ago+ 0 comments

        yeah its not working

        0|
        ParentPermalink
    • amrata_kasture 3 years ago+ 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?

      0|
      ParentPermalink
    • sudhar287 3 years ago+ 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'

      image

      13|
      ParentPermalink
    • mails4ipiyush 3 years ago+ 0 comments

      I am also facing the same issue. I even trimmed the trailing spaces. Still its showing wrong answer.

      0|
      ParentPermalink
    • khadar111 2 years ago+ 0 comments

      for(int i=0;i

      0|
      ParentPermalink
    • svfarande 2 years ago+ 0 comments

      Same problem :(

      0|
      ParentPermalink
    • a65b4139 2 years ago+ 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();
          }
      }
      
      0|
      ParentPermalink
      • Anutrix 2 years ago+ 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?

        0|
        ParentPermalink
    • blazefrostrider 2 years ago+ 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)

      0|
      ParentPermalink
    • kemalsreenivas38 2 years ago+ 0 comments

      Check if the character is null before printing.

      2|
      ParentPermalink
  • samar5yadav 3 years ago+ 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

    12|
    Permalink
    • hamza_emra 3 years ago+ 1 comment

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

      0|
      ParentPermalink
      • samar5yadav 3 years ago+ 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!

        2|
        ParentPermalink
        • hamza_emra 3 years ago+ 0 comments

          It helped alot thank you so much

          0|
          ParentPermalink
        • ashutoshm1771 3 days ago+ 0 comments

          brilliant

          0|
          ParentPermalink
    • Being_human 2 years ago+ 0 comments

      NICE AND SORT

      0|
      ParentPermalink
    • array_yar 12 months ago+ 0 comments
      [deleted]
      0|
      ParentPermalink
    • pdog1111 7 months ago+ 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)]))
      
      1|
      ParentPermalink
    • ajsmith22 4 weeks ago+ 0 comments

      No need to calculate r here.

      0|
      ParentPermalink
  • sujithvm 5 years ago+ 12 comments

    http://ideone.com/1zvv4T

    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
    
    11|
    Permalink
    • visrahane 5 years ago+ 1 comment

      take care of the space(blank) and it works.

      -20|
      ParentPermalink
      • manavkothari 4 years ago+ 2 comments

        how to solve space and null problem in c?

        0|
        ParentPermalink
        • sachin_dandavati 4 years ago+ 0 comments

          First initialise it with null or ' '. Then do function, it will work

          0|
          ParentPermalink
        • srikanthk555 4 years ago+ 0 comments

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

          1|
          ParentPermalink
    • karantirthani 5 years ago+ 1 comment

      i am facing the same problem

      0|
      ParentPermalink
      • etayluz 4 years ago+ 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;
        }
        
        3|
        ParentPermalink
        • GowthamSiddarth 4 years ago+ 0 comments

          why did you allocate 10240 specifically?

          0|
          ParentPermalink
        • highly_rated 4 years ago+ 0 comments
          [deleted]
          0|
          ParentPermalink
        • vidushig2 4 years ago+ 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

          0|
          ParentPermalink
          • shahpujan1992 4 years ago+ 0 comments

            Input for 1st test case is- feedthedog Output - fto ehg ee dd

            0|
            ParentPermalink
        • pp43076 3 years ago+ 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

          3|
          ParentPermalink
          • ankit_mahajan_19 3 years ago+ 2 comments

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

            -1|
            ParentPermalink
            • lausanne_man 3 years ago+ 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.

              0|
              ParentPermalink
              • bearhack 3 years ago+ 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.

                4|
                ParentPermalink
            • Aashish_J 3 years ago+ 0 comments

              Column cannot be 4 (should be <= 3)

              2|
              ParentPermalink
          • adi341875 3 years ago+ 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 :)

            1|
            ParentPermalink
        • pankaj_mittal372 3 years ago+ 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

          0|
          ParentPermalink
    • ScottDuane 5 years ago+ 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

      0|
      ParentPermalink
      • areyoukiddingme 5 years ago+ 0 comments

        similar issue here. http://ideone.com/PZaK34

        1|
        ParentPermalink
      • StevoTVR 4 years ago+ 0 comments

        I think your problem is on line 40. Everything needs to be flipped.

        0|
        ParentPermalink
      • MetonymyQT 4 years ago+ 0 comments

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

        1|
        ParentPermalink
      • lausanne_man 3 years ago+ 0 comments

        It appears Sample #2 has been fixed.

        0|
        ParentPermalink
    • thugwaffle 5 years ago+ 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.

      http://ideone.com/dttF2J

      0|
      ParentPermalink
    • Tatparya 4 years ago+ 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

      4|
      ParentPermalink
    • alexgbelov 4 years ago+ 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.

      0|
      ParentPermalink
    • shubham_sharma14 4 years ago+ 0 comments

      if (arr=='\0'); break

      1|
      ParentPermalink
    • st4rk03 4 years ago+ 0 comments

      use this :----->

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

      4|
      ParentPermalink
    • TheRevenant 4 years ago+ 0 comments

      Ignore the '\0' characters when displaying the output.

      0|
      ParentPermalink
    • rajendra 4 years ago+ 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

      0|
      ParentPermalink
    • shahpujan1992 4 years ago+ 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..

      0|
      ParentPermalink
    • mserranom 3 years ago+ 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);
          }
      }
      
      0|
      ParentPermalink
  • StopAsh12 5 years ago+ 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.

    7|
    Permalink
    • shashank21jHackerRank Admin 5 years ago+ 1 comment

      Actually square is unique, there is no question of max/min.
      Will change the statement

      0|
      ParentPermalink
      • shubham_sharma14 4 years ago+ 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!!!!!!

        1|
        ParentPermalink
        • shubham_sharma14 4 years ago+ 2 comments

          leave it.

          i got it

          -2|
          ParentPermalink
          • alkis 4 years ago+ 1 comment

            I face the same problem. Could you give some more info on this?

            0|
            ParentPermalink
            • alkis 4 years ago+ 0 comments

              Leave it. I got it too!

              -1|
              ParentPermalink
          • briandignan 4 years ago+ 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))

            0|
            ParentPermalink
            • alkis 4 years ago+ 1 comment

              You are right about the lower limit. What about the upper limit?

              3|
              ParentPermalink
              • briandignan 4 years ago+ 0 comments

                Ahh right. I forgot about that part. Thanks!

                0|
                ParentPermalink
        • manthan19 4 years ago+ 0 comments

          coz 4 is greater than ceil of sqrt(8)

          1|
          ParentPermalink
        • mish_16 4 years ago+ 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.

          2|
          ParentPermalink
          • shubham_sharma14 4 years ago+ 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

            0|
            ParentPermalink
  • Tom_kn 8 months ago+ 0 comments

    Simple and redable. Passed all test cases.

    def encryption(s):
        n = 0
        st = math.ceil(math.sqrt(len(s)))
        res = ""
    
        for i in range(n, st, 1):
            res += s[n::st]+" "
            n += 1
    
        return res
    
    4|
    Permalink
  • Rajatsha90271 4 years ago+ 2 comments

    My first test case is getting passed but the other two are not ,while my output and "expected output " are same. Help

    3|
    Permalink
    • mendelAsked to answer 4 years ago+ 1 comment

      I would like to help you, but I can't because I don't know what you are doing.

      I just resubmitted my solution and it is still accepted, so the system seems to be working correctly.

      0|
      ParentPermalink
      • Rajatsha90271 4 years ago+ 1 comment

        /Following is my code ,,,, Please go though it,,,/

        include

        include

        include

        include

        int main() {

        int i = 0 , k = 0 ,  j , l , r , n = 0;
        char ch;
        char temp[101];
        char str[101];
        char res[101][101];
        while(ch != EOF)
        {
            ch = getchar();
            temp[i++] = ch;
        }
        temp[i] = '\0';
        for(i = 0 ; temp[i] != '\0' ; i++)
        {
        
                if(temp[i] == ' ')
                    continue;
                str[k++]= temp[i];
        
        
        }
        str[k] = '\0';
        l = ceil(sqrt(k));
        r = floor(sqrt(k));
        //if(l * r == k - 1)
        //{
            for(i = 0 ; i < r ; i++)
            {
                for(j = 0 ; j < l ; j++)
                {
                    res[i][j] = str[n++];
                }
        
            }
            for(i = 0 ; i < l; i++)
            {
                for(j = 0 ; j < r ; j++)
                {
                    printf("%c" , res[j][i]);
                }
                printf(" ");
            }
            return 0;
        //}
        /*else
        {
        
        }*/
        

        }

        -3|
        ParentPermalink
        • mendel 4 years ago+ 1 comment

          l = ceil(sqrt(k)); r = floor(sqrt(k));

          This code is too simple and does not reflect the problem statement properly.

          It is possible (but not necessary) to create a solution that does not compute r at all.

          0|
          ParentPermalink
          • roryneil 4 years ago+ 0 comments

            I didn't use floor at all. x,y = 0,ceil, then take chunks of s[x:y], adding ceil to x and y each time. But as someone mentioned above, you don't have to create this matrix, since the string would be s[0] + s[ceil] + s[2*ceil] etc., add a space, then do it again starting at s[1]+s[1+ceil], etc.

            0|
            ParentPermalink
    • saibhaskar1 4 years ago+ 1 comment

      i too have the same problem ... please let me know if you find some mistake

      0|
      ParentPermalink
      • mendel 4 years ago+ 1 comment

        Please check the last letters on the expected output - are they really the same?

        0|
        ParentPermalink
        • saibhaskar1 4 years ago+ 1 comment

          thanks ..there was a difference in spaces

          0|
          ParentPermalink
          • vinesh9876 3 years ago+ 0 comments

            trailing space?

            0|
            ParentPermalink
  • anshul_4ggarwal 2 years ago+ 0 comments

    My C++ Solution:

    int main() 
        {
            string str;
            cin>>str;
            int row=floor( sqrt( str.length() ) ); 
            int col= ceil( sqrt( str.length() ) );
           
            for(int i=0; i<col; i++)
            {  int j=i;
                while(j<str.length())
                {cout<<str[j]; j+=col;}
                cout<<" ";
            }
            return 0;
        }
    
    2|
    Permalink
  • neeraj_deshpand1 2 years ago+ 3 comments

    I am getting exact same answer still it is saying Wrong answer in compiler message. I double checked for spaces before and after the answer but there is no difference. For first testcase it is accepting the answer but for 2nd and 3rd testcase it is saying Wrong answer. What can be the probable reason?

    2|
    Permalink
    • ysrisumanth 2 years ago+ 0 comments

      same problem here

      0|
      ParentPermalink
    • cesarla 2 years ago+ 1 comment

      I am facing the same problem.

      0|
      ParentPermalink
      • cesarla 2 years ago+ 0 comments
        [deleted]
        0|
        ParentPermalink
    • cesarla 2 years ago+ 0 comments

      Actually the problem in my case is that the string serialization was ok but it was producing the wrong equals since I was adding the null character '\u0000' to the result.

      0|
      ParentPermalink
  • brandacher_simon 3 years ago+ 0 comments

    Java Solution: Passes all Testcases.

    public static void main(String[] args) {
            Scanner in = new Scanner(System.in);
            String line = in.nextLine().replace(" ","");
            int cols=(int)Math.ceil(Math.sqrt(line.length()));
    
    
            for(int index = 0;index<cols;index++) {
                StringBuffer sB = new StringBuffer();
                for (int i=index; i < line.length() && i < (i + cols); i+=cols) {
                    sB.append(line.charAt(i));
                }
                System.out.print(sB.toString()+" ");
            }
        }
    
    2|
    Permalink
Load more conversations

Need Help?


View editorial
View top submissions
  • Contest Calendar
  • Blog
  • Scoring
  • Environment
  • FAQ
  • About Us
  • Support
  • Careers
  • Terms Of Service
  • Privacy Policy
  • Request a Feature