Instance of a number in an array [closed] - ruby

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I know "instance_of?" searches for an instance of a class. I am looking for an object that can find an instance of the user input inside the array. Code for clarity:
user_input = nil
array = [[1, 2, 3][4, 5, 6][7, 8, 9]]
until user_input.instance_of?(array) do
print "Choose a number in our array"
begin
user_input = gets.chomp
rescue ArgumentError
user_input = nil
puts "Not in our array. Try again!"
end
end

You can use Array#include?
Here's a simple implementation. I simplified the array for example purposes.
array = [1, 2, 3, 4, 5, 6]
puts "Enter a number"
while user_input = gets.chomp
if array.include?(user_input.to_i)
puts "You got it."
break
else
puts "Not in our array. Try again!"
end
end

Related

Checking if a letter is used more than it appears in a range? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
I have a randomly generated grid (representing an array of letters) containing 9 letters. With this letter a user have to form an english valid word using each letter only once.
How can I check this condition?
Example:
["A", "P", "L" "E", "C", "N", "T", "L", "W"]
apple
So "apple" is not valid because it use two "P"'s when in the array there is only one.
Thanks
This can be done in multiple ways, here is one way to do it. This is under the assumption that the letters array has all elements in the upper case.
Also, using just delete() would remove all of those values in the array causing an issue if the letters array had multiples of a letter so I used delete_at() in order to delete the first instance of the particular element.
letters = ["A", "P", "L", "E", "C", "N", "T", "L", "W"]
word = 'apple'
def valid_word?(letters, word)
word.upcase.scan(/\w/).map do |letter|
return false unless letters.include?(letter)
letters.delete_at(letters.index(letter))
end
true
end
print valid_word?(letters, word)
First you would need to list all valid English words, e.g. from https://www.worddb.com/9-letter/words. Assuming you created en_9c_words.dict and it contains all valid English 9-character words, each lowercase and in one line, here is what you could do:
en_dict = File.read('en_9c_words.dict').split("\n")
valid_answers = []
valid_answer = en_dict.sample
grid = en_dict.sample.upcase.chars.shuffle
puts "Letters: " + grid * ', '
until user_input == ''
user_input = gets.chomp
if valid_answer == user_input
puts "YAY! You found a valid word."
else
puts "Sorry, try again."
end
end
In case you actually want to generate grid independently from en_dict, you will have to deal with performance issues caused by permutations and checking for valid answers, e.g.
until valid_answers.length > 0
grid = Array.new(9) { [*?A..?Z].sample }
permutations = grid.permutation.map(&:join).map(&:downcase)
valid_answers = en_dict & permutations
end
I certainly don't recommend that.
In any case, I hope you find this helpful.

Find the specific number from Array.collect [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I want to find out what's the first, the second, and the third result, so that I can do if firstnumber==secondnumber && secondnumber==thirdnumber. How could I find those numbers on the results?
numbers = 3.times.map { Random.new.rand(0..10000) }
prizes = numbers.map do |x|
case x
when 1..3000
[ '7', 10000 ]
when 3001..6000
[ "Cherries", 500 ]
when 6001..10000
[ "Diamond", 400 ]
end
end
puts "Your results are: #{prizes.collect { |p| p[0] }.join(", ")}!
I tried to use p[0][0], but it gives the first letter instead.
Say if:
results = prizes.collect { |p| p[0] } #=> ["Diamond", "Cherries", "7"]
Then do the following to get at each result:
results[0] #=> "Diamond"
results[1] #=> "Cherries"
results[2] #=> "7"
You could also use results.first to get the first element. If you happen to be working in Rails you can even do the following:
results.second #=> "Cherries"
results.third #=> "7"
Here's a fine way to do this:
numbers = 3.times.map { Random.new.rand(0..10000) }
prizes = numbers.map do |x|
case x
when 1..3000
{ name: '7', val: 10000 }
when 3001..6000
{name: "Cherries", val: 10000 }
when 6001..10000
{name: "Diamond", val: 400 }
end
end
# You could replace 'map' with 'collect' here and have the same results
prizes_string = prizes.map { |p| "#{p[:name]}: #{p[:val]}" }.join(" and ")
puts "Your results are: #{prizes_string}!"

How can I filter an array of objects based on a hash of conditions in Ruby? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I want to pass hash:
filter_search = {age: 20, weight: 30, height: 30, salary: (100000..200000)}
to method
def search(array, filter)
array.select do |elem|
???????
end
end
filtered_array = search(some_array, filter_search)
How can I do this? Maybe I'm thinking in wrong way and there is another pattern to solve this?
Assuming the array parameter an array of objects that have the appropriate methods (age, weight, height, salary) and you want to return a filtered array of the ones that perfectly match your hash filter, something like this might work.
def search(array, filter)
array.select do |elem|
filter.all? do |key, value|
elem.send(key) == value
end
end
end
If you have hashes in your array instead of objects, you would use:
def search(array, filter)
array.select do |elem|
filter.all? do |key, value|
elem[key] == value
end
end
end

Hash delete_if in Ruby [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm trying to remove key-value pairs from a hash whose value is less than the highest key-value pair's value in the hash. Example: If my hash is {:Jan => 3, :Feb =>4, :Mar =>4}, I'd want to remove the :Jan => 3 entry. I am attempting delete_if with a comparison to no avail.
def highestvalue(myhash)
myhash.delete_if { |k,v| v < v}
print myhash
end
months = {:Jan => 3, :Feb =>4, :Mar =>4}
highestvalue(months)
def highestvalue(myhash)
max = myhash.values.max
myhash.delete_if { |k, v| v < max }
end

Can't get if statement to evaluate properly -- .include? always evaluates to false [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I'm having trouble getting my if statement for def is_valid_card_query(card_queried) to evaluate properly. I think it has something to do with my array and how I'm passing the variable in, perhaps?
I'm trying to evaluate first if the card is valid, meaning it's rank is (2 - A), second if the player has the card, and if so then I just return the card. But no matter what I do, it always defaults to the if.
cards_available.include? "card_queried" keeps evaluating to false *when I pass card_queried in through the method call*.
How can I fix this?
Here's the code. I have the portion I'm trying to run at the bottom:
require 'socket'
require 'rspec'
require 'json'
require_relative 'FishDeck.rb'
require_relative 'FishHand.rb'
require_relative 'FishGame.rb'
require_relative 'FishServer.rb'
require_relative 'FishPlayers.rb'
require_relative 'ServerTests.rb'
class ClientClass
attr_accessor :players_available, :card_choices_available
def initialize(host, port)
#socket = TCPSocket.new(host, port)
players_available = nil
card_choices_available = nil
end
def get_input
incoming = #socket.gets.chomp
#puts "Here is the output for incoming: #{incoming}"
end
def send_input(message)
outgoing = #socket.puts(message)
end
def close
#socket.close
end
def is_valid_player_query(player_queried)
if (player_queried > players_available) || (player_queried < 1)
puts "I'm sorry, that's not a player."
puts "Please enter a player number ranging from 1 through #{players_available}"
user_input = gets.chomp
is_valid_player_query(user_input) #Recursion until proper response
else
return player_queried
end
end
def is_valid_card_query(card_queried)
puts "CARD QUERIED: #{card_queried}"
cards_available = %w(2 3 4 5 6 7 8 9 10 J Q K A)
puts "CARDS AVAILABLE: #{cards_available}"
if (cards_available.include? "card_queried") == false
puts "CARD NOT AVAILABLE EVER"
puts "True if statement? #{cards_available.include? "card_queried"}"
puts "I'm sorry, that's not a valid card choice."
puts "Please enter a card number ranging from 2 through A. You're using a traditional deck"
user_input = gets.chomp
user_input = is_valid_card_query(user_input) #Recursion until proper response
elsif (((cards_available.include? "card_queried") == true) && ((card_choices_available.include? "card_queried") == false))
puts "CARD IN DECK BUT NOT HAND"
puts "True if statement? #{cards_available.include? "card_queried"}"
puts "I'm sorry, you don't have that card, so you can't ask for it."
puts "Here are the cards for which you may ask: #{card_choices_available}"
user_input = gets.chomp
user_input = is_valid_card_query(user_input)
else
puts "True if statement? #{cards_available.include? "card_queried"}"
puts "PASS!"
return card_queried
end
end
def input_decision(input)
if input == "PLAYERS"
input = #socket.gets.chomp #gets the actual array
input = input.to_i
players_available = input
elsif input == "CARDS"
input = #socket.gets.chomp
input = JSON.parse(input)
card_choices_available = input
elsif input == "EXIT"
puts "The server has closed. Goodbye!"
#I need some way to break the loop or close the client if the server has closed
elsif input == "ANNOUNCEMENT" #just reads it
input = #socket.gets.chomp
puts input
else #get input from user case
user_choice = []
puts "It is your turn. Please choose a player to ask for a card"
user_input = gets.chomp
user_input = is_valid_player_query(user_input)
user_choice << user_input
puts "Great! You're asking Player #{user_input} for a card. What card would you like?"
user_input = gets.chomp
user_input = is_valid_card_query(user_input)
user_choice << user_input
user_choice = user_choice.to_json
#socket.send_input(user_choice)
end
end
end
#server = SocketServerClass.new(2012, 3)
#client1 = ClientClass.new('localhost', 2012)
#client2 = ClientClass.new('localhost', 2012)
#client3 = ClientClass.new('localhost', 2012)
#server.accept_client(#server.fish_game)
#server.accept_client(#server.fish_game)
#server.accept_client(#server.fish_game)
#client1.card_choices_available = %w(3, 6, 9 K, 10)
#client1.is_valid_card_query("3") #Doesn't work just 3 , either.
Your code states that cards_available consists of the following array:
["2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K" ,"A"]
However, you are evaluating whether or not cards_available includes the string "card_queried" – this will never evaluate to true. What should be evaluating whether it includes the variable card_queried, which, according to your instructions, should be a string "ranging from 2 through A":
cards_available.include? card_queried

Resources