So I figured out that I can count through the hash, the problem is that for 7 and 9 I have four values. I have tried several other things with no luck. Can someone help understand what else I could do to get the values I want out of the hash. I realize that I can match the numbers with the key, but I am confused how to get the values to permute.
letters = {"1" => ["1", "1", "1"],
"2" => ["a", "b", "c"],
"3" => ["d", "e", "f"],
"4" => ["g", "h", "i"],
"5" => ["j", "k", "l"],
"6" => ["m", "n", "o"],
"7" => ["p", "q", "r", "s"],
"8" => ["t", "u", "v"],
"9" => ["w", "x", "y", "z"]}
phone_number = gets.chomp.to_s
words = []
word = []
numbers = phone_number.chomp.chars
count0 = 0
while count0 < 3
count1 = 0
while count1 < 3
count2 = 0
while count2 < 3
count3 = 0
while count3 < 3
count4 = 0
while count4 < 3
count5 = 0
while count5 < 3
count6 = 0
while count6 < 3
word[0] = letters[numbers[0]][count0]
word[1] = letters[numbers[1]][count1]
word[2] = letters[numbers[2]][count2]
word[3] = letters[numbers[3]][count3]
word[4] = letters[numbers[4]][count4]
word[5] = letters[numbers[5]][count5]
word[6] = letters[numbers[6]][count6]
words << word.join
count6 += 1
end
count5 += 1
end
count4 += 1
end
count3 += 1
end
count2 += 1
end
count1 += 1
end
count0 += 1
end
puts words
Edit:
I want to a seven digit number and print out all possible letter combinations. I am a beginner so I want to understand with the things I know now. I want to try and do this with if statements please.
numbers = phone_number.chomp.chars
if letters.key?(numbers[0])
if letters.key?(numbers[1])
if letters.key?(numbers[2])
if letters.key?(numbers[3])
if letters.key?(numbers[4])
if letters.key?(numbers[5])
if letters.key?(numbers[6])
end
end
end
end
end
end
end
I understand how to grab a value from a matching key, but don't get how I can hold the first value while going through the rest, if that makes any sense.
product is the function you are looking for, the following works with any number of digits:
digits = '27'
keys = digits.chars.map{|digit|letters[digit]}
p keys.shift.product(*keys).map(&:join) #=> ["ap", "aq", "ar", "as", "bp", "bq", "br", "bs", "cp", "cq", "cr", "cs"]
This prints all possible words for a variable-sized phone number:
letters = {"1" => ["1"],
"2" => ["a", "b", "c"],
"3" => ["d", "e", "f"],
"4" => ["g", "h", "i"],
"5" => ["j", "k", "l"],
"6" => ["m", "n", "o"],
"7" => ["p", "q", "r", "s"],
"8" => ["t", "u", "v"],
"9" => ["w", "x", "y", "z"]}
digits = gets.chomp.split ''
# Total number of combinations
n = digits.inject(1) { |a,b| a * letters[b].size }
words = []
0.upto n-1 do |q|
word = []
digits.reverse.each do |digit|
q, r = q.divmod letters[digit].size
word.unshift letters[digit][r]
end
words << word.join
end
puts words
For example, if the input is 67, then there are 12 combinations:
mp mq mr ms np nq nr ns op oq or os
Edit: I don't see a way to make use of the 7 if statements as you have written, but perhaps this is closer to the kind of answer you are looking for:
words = []
letters[digits[0]].each do |c0|
letters[digits[1]].each do |c1|
letters[digits[2]].each do |c2|
letters[digits[3]].each do |c3|
letters[digits[4]].each do |c4|
letters[digits[5]].each do |c5|
letters[digits[6]].each do |c6|
words << [c0,c1,c2,c3,c4,c5,c6].join
end
end
end
end
end
end
end
puts words
A good exercise would be to re-write this in a way that can work for phone numbers of any length, not just 7. Again, this is only for instructional purposes. In practice, one would use Array's product method as in hirolau's answer.
LETTERS = {"1" => ["1", "1", "1"],
"2" => ["a", "b", "c"],
"3" => ["d", "e", "f"],
"4" => ["g", "h", "i"],
"5" => ["j", "k", "l"],
"6" => ["m", "n", "o"],
"7" => ["p", "q", "r", "s"],
"8" => ["t", "u", "v"],
"9" => ["w", "x", "y", "z"]}
def convert_to_phone_number(string)
string.each_char.with_object([]) { |x, arr| LETTERS.each { |k,v| (arr.push k; break) if v.include?(x) }}.join
end
convert_to_phone_number "foobar"
#=> "366227"
i think so it is issue of cache memory
u need to change like below
LETTERS = {"1" => ["1", "1", "1"],
"2" => ["a", "b", "c"],
"3" => ["d", "e", "f"],
"4" => ["g", "h", "i"],
"5" => ["j", "k", "l"],
"6" => ["m", "n", "o"],
"7" => ["p", "q", "r", "s"],
"8" => ["t", "u", "v"],
"9" => ["w", "x", "y", "z"]}
def convert_to_phone_number(string)
string.each_char.with_object([]) { |x, arr| LETTERS.each { |k,v| (arr.push k; break) if v.include?(x) }}.join
end
convert_to_phone_number "foobar"
Related
We are trying to implement the verification of the new EU corona virus test/vaccination certificates, but can't get the base45 decoding working.
Specification is here: https://datatracker.ietf.org/doc/draft-faltstrom-base45/
We nearly finished our class, but we sometimes get wrong values back..
Target is this:
Encoding example 1: The string "AB" is the byte sequence [65 66].
The 16 bit value is 65 * 256 + 66 = 16706. 16706 equals 11 + 45 * 11
+ 45 * 45 * 8 so the sequence in base 45 is [11 11 8]. By looking up
these values in the Table 1 we get the encoded string "BB8".
Encoding example 2: The string "Hello!!" as ASCII is the byte
sequence [72 101 108 108 111 33 33]. If we look at each 16 bit
value, it is [18533 27756 28449 33]. Note the 33 for the last byte.
When looking at the values modulo 45, we get [[38 6 9] [36 31 13] [9
2 14] [33 0]] where the last byte is represented by two. By looking
up these values in the Table 1 we get the encoded string "%69
VD92EX0".
Encoding example 3: The string "base-45" as ASCII is the byte
sequence [98 97 115 101 45 52 53]. If we look at each 16 bit value,
it is [25185 29541 11572 53]. Note the 53 for the last byte. When
looking at the values modulo 45, we get [[30 19 12] [21 26 14] [7 32
5] [8 1]] where the last byte is represented by two. By looking up
these values in the Table 1 we get the encoded string "UJCLQE7W581".
Here is my current code, which produces wrong values:
class Base45
ALPHABET = {
"00" => "0",
"01" => "1",
"02" => "2",
"03" => "3",
"04" => "4",
"05" => "5",
"06" => "6",
"07" => "7",
"08" => "8",
"09" => "9",
"10" => "A",
"11" => "B",
"12" => "C",
"13" => "D",
"14" => "E",
"15" => "F",
"16" => "G",
"17" => "H",
"18" => "I",
"19" => "J",
"20" => "K",
"21" => "L",
"22" => "M",
"23" => "N",
"24" => "O",
"25" => "P",
"26" => "Q",
"27" => "R",
"28" => "S",
"29" => "T",
"30" => "U",
"31" => "V",
"32" => "W",
"33" => "X",
"34" => "Y",
"35" => "Z",
"36" => " ",
"37" => "$",
"38" => "%",
"39" => "*",
"40" => "+",
"41" => "-",
"42" => ".",
"43" => "/",
"44" => ":"
}.freeze
def self.encode_base45(text)
restsumme = text.unpack('S>*')
# not sure what this is doing, but without it, it works worse :D
restsumme << text.bytes[-1] if text.bytes.size > 2 && text.bytes[-1] < 256
bytearr = restsumme.map do |bytes|
arr = []
multiplier, rest = bytes.divmod(45**2)
arr << multiplier if multiplier > 0
multiplier, rest = rest.divmod(45)
arr << multiplier if multiplier > 0
arr << rest if rest > 0
arr.reverse
end
return bytearr.flatten.map{|a| ALPHABET[a.to_s.rjust(2, "0")]}.join
end
def self.decode_base45(text)
arr = text.split("").map do |char|
ALPHABET.invert[char]
end
textarr = arr.each_slice(3).to_a.map do |group|
subarr = group.map.with_index do |val, index|
val.to_i * (45**index)
end
ap subarr
subarr.sum
end
return textarr.pack("S>*") # returns wrong values
end
end
Results:
Base45.encode_base45("AB")
=> "BB8" # works
Base45.decode_base45("BB8")
=> "AB" # works
Base45.encode_base45("Hello!!")
=> "%69 VD92EX" # works
Base45.decode_base45("BB8")
=> "Hello!\x00!" # wrong \x00
Base45.encode_base45("base-45")
=> "UJCLQE7W581" # works
Base45.decode_base45("UJCLQE7W581")
=> "base-4\x005" # wrong \x00
Any hints appreciated :(
After struggling to get the other answers to work, I made my own method based on your question and this snippet. Abovementioned answers worked in most cases but not in all of them, especially when the string length mod 3 = 2.
class Base45
ALPHABET = {
0 => "0",
1 => "1",
2 => "2",
3 => "3",
4 => "4",
5 => "5",
6 => "6",
7 => "7",
8 => "8",
9 => "9",
10 => "A",
11 => "B",
12 => "C",
13 => "D",
14 => "E",
15 => "F",
16 => "G",
17 => "H",
18 => "I",
19 => "J",
20 => "K",
21 => "L",
22 => "M",
23 => "N",
24 => "O",
25 => "P",
26 => "Q",
27 => "R",
28 => "S",
29 => "T",
30 => "U",
31 => "V",
32 => "W",
33 => "X",
34 => "Y",
35 => "Z",
36 => " ",
37 => "$",
38 => "%",
39 => "*",
40 => "+",
41 => "-",
42 => ".",
43 => "/",
44 => ":"
}.freeze
def self.decode_base45(text)
raise ArgumentError, "invalid base45 string" if text.size % 3 == 1
arr = text.split("").map do |char|
ALPHABET.invert[char]
end
arr.each_slice(3).to_a.map do |group|
if group.size == 3
x = group[0] + group[1] * 45 + group[2] * 45 * 45
raise ArgumentError, "invalid base45 string" if x > 0xFFFF
x.divmod(256)
else
x = group[0] + group[1] * 45
raise ArgumentError, "invalid base45 string" if x > 0xFF
x
end
end.flatten.pack("C*")
end
end
if you'd like a bodgy way of doing this:
return textarr.map{|x| x<256 ? [x].pack("C*") : [x].pack("n*") }.join
looking at this scheme, it feels like a weird way to encode, as we're working with numbers ... if it were me, I'd have started at the tail of the string and worked towards the head, but that's because we're using numbers.
anyway, the reason that my bodge works is that it treats small elements/numbers as 8-bit unsigned instead of 16-bit unsigned.
...
slightly more pleasing to the eye, but probably no better:
def self.decode_base45(text)
arr = text.split("").map do |char|
ALPHABET.invert[char]
end
textarr = arr.each_slice(3).to_a.map do |group|
subarr = group.map.with_index do |val, index|
val.to_i * (45**index)
end
ap subarr
subarr.sum.divmod(256)
end.flatten.reject(&:zero?)
return textarr.pack("C*") # returns wrong values
end
It might not be a proper solution to the problem here.
But adding textarr.pack("S>*").gsub(/\x00/, "") solved the problem for the given decoding examples.
Also it's really weird that your encode version didn't work well for me (had wrong results in two first examples).
Anyway, this thread led me to contribute a bit by making this as a gem.
Let's take QED8WEX0 and QED8WEX00 for example, you got [[26, 14, 13], [8, 32, 14], [33, 0]] and [[26, 14, 13], [8, 32, 14], [33, 0, 0]] respectively.
The problem here is their final form are the same: [26981, 29798, 33] and you can't determine whether 33 represents for 1 bytes or 2 bytes.
We can solve it by passing dynamic argument based on input length to Array#pack, for example:
[26981, 29798, 33].pack((input.length % 3).zero? ? 'n*' : "n#{input.length / 3}C")
Here is my implementation:
# frozen_string_literal: true
class Base45Lite
MAX_UINT18 = 2**16 - 1
SQUARED_45 = 45**2
MAPPING = [
*'0'..'9',
*'A'..'Z',
' ', '$', '%', '*', '+', '-', '.', '/', ':'
].map!.with_index { |x, i| [i, x] }.to_h.freeze
REVERSE_MAPPING = MAPPING.invert.freeze
def self.encode(input)
sequence = []
input.unpack('n*').map! do |uint16|
i, c = uint16.divmod(45)
i, d = i.divmod(45)
_, e = i.divmod(45)
sequence.push(c, d, e)
end
if input.bytesize.odd?
i, c = input.getbyte(-1).divmod(45)
_, d = i.divmod(45)
sequence.push(c, d)
end
sequence.map!{ MAPPING[_1] }.join
end
def self.decode(input)
input
.chars.map! { REVERSE_MAPPING[_1] }
.each_slice(3).map do |slice|
c, d, e = slice
sum = c + d * 45
sum += e * SQUARED_45 if e
sum
end
.pack((input.length % 3).zero? ? 'n*' : "n#{input.length / 3}C")
end
end
if __FILE__ == $PROGRAM_NAME
require 'minitest/autorun'
class Base45Test < Minitest::Test
parallelize_me!
def test_encode
assert_equal 'BB8', Base45Lite.encode('AB')
assert_equal '%69 VD92EX0', Base45Lite.encode('Hello!!')
assert_equal 'UJCLQE7W581', Base45Lite.encode('base-45')
end
def test_decode
assert_equal 'ietf!', Base45Lite.decode('QED8WEX0')
assert_equal 'AB', Base45Lite.decode('BB8')
assert_equal 'Hello!!', Base45Lite.decode('%69 VD92EX0')
assert_equal 'base-45', Base45Lite.decode('UJCLQE7W581')
end
end
end
You can find a more comprehensive implementation here https://gist.github.com/tonytonyjan/5eefdfbe7a79cd676e75c138466e921d
You can also install the Ruby gem https://rubygems.org/gems/base45_lite
Benchmark
Compare with https://github.com/wattswing/base45
require 'benchmark/ips'
require 'base45'
require_relative 'base45_lite'
message = 'base-45'
encoded = 'UJCLQE7W581'
Benchmark.ips do |x|
x.report('Base45Lite.encode'){ |n| n.times { Base45Lite.encode(message) } }
x.report('Base45.encode'){ |n| n.times { Base45.encode(message) } }
x.compare!
end
Benchmark.ips do |x|
x.report('Base45Lite.decode'){ |n| n.times { Base45Lite.decode(encoded) } }
x.report('Base45.decode'){ |n| n.times { Base45.decode(encoded) } }
x.compare!
end
Warming up --------------------------------------
Base45Lite.encode 37.721k i/100ms
Base45.encode 16.121k i/100ms
Calculating -------------------------------------
Base45Lite.encode 348.105k (± 6.7%) i/s - 1.735M in 5.008303s
Base45.encode 148.871k (± 7.1%) i/s - 741.566k in 5.008783s
Comparison:
Base45Lite.encode: 348105.0 i/s
Base45.encode: 148870.7 i/s - 2.34x (± 0.00) slower
Warming up --------------------------------------
Base45Lite.decode 25.909k i/100ms
Base45.decode 16.972k i/100ms
Calculating -------------------------------------
Base45Lite.decode 231.134k (± 6.9%) i/s - 1.166M in 5.068220s
Base45.decode 148.288k (± 6.5%) i/s - 746.768k in 5.057694s
Comparison:
Base45Lite.decode: 231134.5 i/s
Base45.decode: 148287.8 i/s - 1.56x (± 0.00) slower
I have the following code:
def caesar_cipher(text, move_by)
move_by %= 26
chars = Hash[('a'..'z').map.with_index.to_a]
converted = text.split.map do |word|
word.chars.map do |char|
if (chars[char.downcase] + move_by) <= 26
chars.key(chars[char.downcase] + move_by)
else
chars.key(chars[char.downcase] + move_by - 26)
end
end
end
end
print caesar_cipher("What a string", 5)
It converts string from variable text to integer. Here is the output I get when I run it: [["b", "m", "f", "y"], ["f"], ["x", "y", "w", "n", "s", "l"]], and I'd like it to be joined like this"bmft f xywnsl". I've tried .join method, but it gives me "bmftfxywnsl"
If:
arr = [["b", "m", "f", "y"], ["f"], ["x", "y", "w", "n", "s", "l"]]
then
arr.map(&:join).join(' ')
#=> "bmfy f xywnsl"
You can think of map(&:join) as:
arr.map { |a| a.join }.join(' ')
Isn't Ruby great?
Not sure if that's the term I should use for it but what I'm trying to do is add len amount of characters to an array, then output that to a .txt. I have the generation done to my satisfaction but I'm not sure how to pack the strings into an array. Right now it just spits out all the strings into the console because of the puts statement, just to make sure it works.
#Password list generator by Nightc||ed, ©2015
norm = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]
caps = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]
nums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
puts "How many passwords would you like to generate?"
num = gets.to_i
system "cls"
puts "Password length (1-x):"
len = gets.to_i
system "cls"
puts """
Which characters would you like to use?
[1] a-z, 0-9
[2] A-Z, 0-9
[3] a-z, A-Z, 0-9
"""
arr = []
type = gets.chomp
if type == "1"
arr = [norm,nums]
elsif type == "2"
arr = [caps,nums]
elsif type == "3"
arr = [norm,caps,nums]
else
exit
end
num.times do |pass|
len.times do |char|
arr2 = arr.to_a.sample
char = arr2.to_a.sample
puts char
end
end
sleep
here your code simplified
#Password list generator by Nightc||ed, ©2015
norm = [*"a".."z"]
caps = [*"A".."Z"]
nums = [*0..9]
num, len, type = [
"How many passwords would you like to generate?",
"Password length (1-x):",
"Which characters would you like to use?
[1] a-z, 0-9
[2] A-Z, 0-9
[3] a-z, A-Z, 0-9"].map do |msg|
puts msg
gets.to_i
end
arr = case type
when 1 then
norm + nums
when 2 then
caps + nums
when 3 then
norm + caps + nums
else
exit
end
passwords = num.times.map { arr.sample(len).join }
puts passwords.inspect
sleep
I think you can simplify your life by replacing the if... and below with the following:
case type
when "1"
arr = [norm,nums].flatten
when "2"
arr = [caps,nums].flatten
when "3"
arr = [norm,caps,nums].flatten
else
exit
end
passwd_set = []
num.times { passwd_set << arr.sample(len).join }
p passwd_set
I find case statements easier to read, and more easily extended. Flattening the arrays makes it so sample can directly produce the desired number of characters/symbols, and those can be joined to produce a string which can be appended to your passwd_set array.
You can add to an array using the << method. For example:
arr = []
3.times do |el|
arr << el
end
arr.inspect #=> [0, 1, 2]
Another option would be the push method:
arr = []
(0..2).each { |el| arr.push(el)}
I have this question.
Using the Ruby language, have the function CaesarCipher(str,num) take the str parameter and perform a Caesar Cipher shift on it using the num parameter as the shifting number. A Caesar Cipher works by shifting each letter in the string N places down in the alphabet (in this case N will be num). Punctuation, spaces, and capitalization should remain intact. For example if the string is "Caesar Cipher" and num is 2 the output should be "Ecguct Ekrjgt".
Any my code looks like this. I think the onlt problem i have is to update each letter and then each word within the loops. please help. thank you
def Caesar_cipher(str, num)
if num > 25
num -= 26
end
alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]
str = str.split(" ")
str.each do |word|
word.each_char do |c|
if alphabet.include?(c)
n = alphabet.index(c) + num
if n > 25
n -= 26
end
c = alphabet[n]
end
end
end
return str
end
puts Caesar_cipher("zabcd", 1) // "zabcd"
str = str.split("")
alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]
alphabet2 = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]
while num > 25
num -= 26
end
str = str.map do |char|
if alphabet.include?(char)
n = alphabet.index(char) + num
while n > 25
n -= 26
end
char = alphabet[n]
elsif alphabet2.include?(char)
m = alphabet2.index(char) + num
while m > 25
m -= 26
end
char = alphabet2[m]
else
char
end
char
end
return str.join
end
def cipher_shift(s, n)
letters = [*'a'..'z']
s.chars.map {|x| letters.include?(x.downcase) ? (x.ord + n).chr : x}.join
end
I have some array
>> a = ["a..c", "0..2"]
=> ["a..c", "0..2"]
I need convert this array to another array
>> b = ("a".."c").to_a + (0..2).to_a
=> ["a", "b", "c", 0, 1, 2]
How I can do it?
a.flat_map do |string_range|
from, to = string_range.split("..", 2)
(from =~ /^\d+$/ ? (from.to_i..to.to_i) : (from..to)).to_a
end
#=> => ["a", "b", "c", 0, 1, 2]
what about this?
a = ["a..c", "0..2"]
b = a.map { |e| Range.new( *(e).split('..') ).to_a }.flatten
no flat_map used so it works the same on all versions
as #steenslag correctly mentioned, this version does not convert to integers.
here is a version that does:
b = a.map do |e|
Range.new( *(e).split('..').map{ |c| c =~ /\A\d+\Z/ ? c.to_i : c } ).to_a
end.flatten
see it in action here
a = ["a..c", "0..2"]
b = a.flat_map{|str| Range.new(*str.split('..')).to_a} # => ["a", "b", "c", "0", "1", "2"]
p b.map!{|v| Integer(v) rescue v} # => ["a", "b", "c", 0, 1, 2]