Sort by

recency

|

1478 Discussions

|

  • + 0 comments

    Kotlin solution with O(n)

    	var editedText = ""
    
            val breakerPoint = sqrt(s.length.toDouble()).toInt()
            val map = mutableMapOf<Int,String>()
    
            s.forEachIndexed { index, c ->
                map[index % (breakerPoint)] = (map[index % (breakerPoint)]?: "") + c
            }
            map.values.forEachIndexed { index, s ->
                editedText += s
                if (index != map.size - 1) {
                    editedText += " "
                }
            }
    
  • + 0 comments

    PHP:

    function encryption($s) {
        $s = str_split(str_replace(' ', '', $s));
        $sizeOf = sizeOf($s);
        
        $rows = floor(sqrt($sizeOf));
        $columns = ceil(sqrt($sizeOf));
        
        if ($rows * $columns < $sizeOf) $rows = $columns;
        
        $grid = [];   
        for($i = 0; $i < $rows; $i++) {
            for ($j = 0; $j < $columns; $j++) {
                $grid[$j][$i] = $s[$i * $columns + $j];
            }   
        }
        
        $encrypted = '';
        for ($i = 0; $i < sizeOf($grid); $i++) {
            $encrypted .= implode('', $grid[$i]) . ' ';
        }
        return $encrypted;
    }
    
  • + 0 comments

    PHP

    function encryption($s) {
        $s = str_split(str_replace(' ', '', $s));
        $sizeOf = sizeOf($s);
        
        $rows = floor(sqrt($sizeOf));
        $columns = ceil(sqrt($sizeOf));
        
        if ($rows * $columns < $sizeOf) $rows = $columns;
        
        $grid = [];   
        for($i = 0; $i < $rows; $i++) {
            for ($j = 0; $j < $columns; $j++) {
                $grid[$j][$i] = $s[$i * $columns + $j];
            }   
        }
        
        $encrypted = '';
        for ($i = 0; $i < sizeOf($grid); $i++) {
            $encrypted .= implode('', $grid[$i]) . ' ';
        }
        return $encrypted;
    }
    
  • + 0 comments

    Haskell:

    module Main where
    
    import Data.List (transpose)
    
    solve :: String -> String
    solve plain = encrypted
      where
        plain' = filter (/= ' ') plain
        len = length plain'
        rows = floor . sqrt $ fromIntegral len
        cols = ceiling . sqrt $ fromIntegral len
        grid = [take cols $ drop (i * cols) plain' | i <- [0 .. rows]]
        grid' = filter (/= "") grid -- edge case, final is ""
        encrypted = unwords $ transpose grid
    
    main :: IO ()
    main = interact solve
    
  • + 0 comments

    public static String encryption(String s) { StringBuilder result = new StringBuilder(); s = s.replaceAll("\s", ""); int n = s.length(); int row = (int) Math.sqrt(n); int column = (row * row == n) ? row : row + 1; for (int i = 0; i < column; i++) { for (int j = i; j < n; j += column) { result.append(s.charAt(j)); } result.append(" ");

        }
    
        return result.toString();
    
    }