Skip to content

Commit 350bc5a

Browse files
committed
exercism 75- Crypto Square
1 parent 916f7e2 commit 350bc5a

File tree

2 files changed

+43
-1
lines changed

2 files changed

+43
-1
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -296,7 +296,7 @@ solution of many challenges of [Leetcode](https://leetcode.com/), [Exercism](htt
296296
72. [Wordy](https://github.com/kumar91gopi/Algorithms-and-Data-Structures-in-Ruby/blob/master/exercism/wordy.rb)
297297
73. [Secret Handshake](https://github.com/kumar91gopi/Algorithms-and-Data-Structures-in-Ruby/blob/master/exercism/secret_handshake.rb)
298298
74. [Atbash Cipher](https://github.com/kumar91gopi/Algorithms-and-Data-Structures-in-Ruby/blob/master/exercism/atbash_cipher.rb)
299-
299+
75. [Crypto Square](https://github.com/kumar91gopi/Algorithms-and-Data-Structures-in-Ruby/blob/master/exercism/crypto_square.rb)
300300

301301
<a name="leetcode"/>
302302

exercism/crypto_square.rb

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
# Problem: https://exercism.org/tracks/ruby/exercises/crypto-square
2+
3+
# Solution
4+
class Crypto
5+
def initialize(plaintext)
6+
@plaintext = plaintext
7+
end
8+
9+
def ciphertext
10+
normalized_text = @plaintext.downcase.gsub(/\W/,"")
11+
text_len = normalized_text.length
12+
return "" if text_len==0
13+
col_len = Math.sqrt(text_len).ceil
14+
row_len = col_len*(col_len-1) < text_len ? col_len : col_len-1
15+
char_deficit = (col_len*row_len)-text_len
16+
normalized_text+=(" "*char_deficit)
17+
normalized_text
18+
.chars
19+
.each_slice(col_len)
20+
.to_a
21+
.transpose
22+
.map{|col| col.join("")}
23+
.join(" ")
24+
end
25+
end
26+
27+
# Solution (idiomatic)
28+
class Crypto
29+
def initialize(plaintext)
30+
@plaintext = plaintext
31+
end
32+
33+
def ciphertext
34+
normalized_text = @plaintext.downcase.gsub(/[^\da-z]/, '')
35+
length = normalized_text.length
36+
return '' if length.zero?
37+
cols = Math.sqrt(length).ceil
38+
rows = length.quo(cols).ceil
39+
rectangle_base = normalized_text + ' ' * (cols * rows - length)
40+
rectangle_base.chars.each_slice(cols).to_a.transpose.map(&:join).join(' ')
41+
end
42+
end

0 commit comments

Comments
 (0)