Cipher Discussions | Algorithms | HackerRank

Sort by

recency

|

114 Discussions

|

  • + 0 comments

    Haskell

    Missed three -- not sure why, but not spending more time on it.

    module Main where
    
    import Data.Foldable (Foldable (toList))
    import Data.Sequence (Seq, fromList, index, splitAt, (<|), (|>))
    import qualified Data.Sequence  as Seq
    
    cxor :: Char -> Char -> Char
    cxor '0' '0' = '0'
    cxor '1' '1' = '0'
    cxor _ _ = '1'
    
    solve2 :: Int -> Int -> String -> String
    solve2 n k e = go e solseq bsum
      where
        k' = k - 1
        solseq = fromList $ replicate k' '0'
        bsum = '0'
        go :: String -> Seq Char -> Char -> String
        go "" acc _ = drop k' $ reverse $ drop k' $ toList acc
        go (x : xs) acc bsum =
            let newC = x `cxor` bsum
                acc' = (newC <| acc)
                bsum' = newC `cxor` bsum `cxor` index acc' k'
             in go xs acc' bsum'
    
    main :: IO ()
    main = do
        [n, k] <- map read . words <$> getLine
        e <- getLine
        putStrLn $ solve2 n k e
        putStrLn ""
    
  • + 0 comments
    string cipher(int k, string s) {
        int n = s.size();
        string res = "";
        res.push_back(s[0]);
        
        for(int i=1;i<n-k+1;i++){
            if(i < k){
                int x = (int)(s[i]-'0') ^ (int)(s[i-1]-'0');
                char ch = ('0'+x);
                res.push_back(ch);
            }
            else{
                int r = res.size();
                int x = 0;
                for(int j=r-1;j>=r-k+1;j--){
                    x ^= (int)(res[j]-'0');
                }
                x ^= (int)(s[i]-'0');
                char ch = (char)('0'+x);
                res.push_back(ch);
            }
        }
        return res;
    }
    
  • + 0 comments

    def cipher(k, s): # Write your code here n=len(s) s1=s[0:n-k+1] res,xr="","0" for i1 in s1: if len(xr)-1

  • + 0 comments
    def cipher(k, s):
        # Write your code here
        if(k==0):
            return s
        S=s[0]
        for i in range(1,len(s)-(k-1)):
            S+=str(int(s[i])^int(s[i-1])^(0 if i<k else int(S[i-k])))         
        return S
    
  • + 1 comment

    C++

    string cipher(int k, string s)
    {
      int n = (int)s.size(), m = n-k+1, t = k+1;
      string r(m, 0), x(t, 0);
      for (int i = 0; i < m; i++) {
        x[i%t] = x[(i+1)%t] ^ (s[n-1-i]-'0');
        r[m-1-i] = (x[i%t] ^ x[(i+k)%t]) + '0';
      }
      return r;
    }