How to replace element in multidimensional array in ruby - ruby

I am having some difficulty with my code and I am hoping for some insight:
I have a 2d array for a board and I am attempting to replace a number with "X" when called, but am having struggles achieving this.
class BingoBoard
def initialize
#bingo_board = Array.new(5) {Array (5.times.map{rand(1..100)})}
#bingo_board[2][2] = 'X'
end
def new_board
#bingo_board.each{|row| p row}
end
def ball
#letter = ["B","I","N","G","O"].shuffle.first
#ball = rand(1..100)
puts "The ball is #{#letter}#{#ball}"
end
def verify
#ball
#bingo_board.each{|row| p row}
#bingo_board.collect! { |i| (i == #ball) ? "X" : i}
end
end
newgame = BingoBoard.new
puts newgame.ball
newgame.verify
I am aware that when verify is called it is iterating only through the array1, but I am unsure how to go about making the fix. Any help appreciated.

This is the root of the problem:
#bingo_board.collect! { |i| (i == #ball) ? "X" : i}
In this example, i is an array. So what you might want to do is to replace your code with something like:
#bingo_board.collect! do |i| # you're iterating over a double array here
if i.include?(#ball) # i is a single array, so we're checking if the ball number is included
i[i.index(#ball)] = 'X'; i # find the index of the included element, replace with X
else
i
end
end
Or if you prefer one-liner:
#bingo_board.collect! { |i| i.include?(#ball) ? (i[i.index(#ball)] = 'X'; i) : i }
Be aware that this is going to only replace the first occurrence of the element. So, say if your ball is 10, and you have:
[8, 9, 9, 10, 10]
you will get:
[8, 9, 9, "X", 10]
If you want ALL of the 10s to be replaced, then do something like:
#bingo_board.collect! do |i|
if i.include?(#ball)
i.collect! { |x| x == #ball ? 'X' : x }
else
i
end
end

Related

Need help to create a breadth-first search function

I’m currently doing Knight’s Travails project.
In this project you need to find the shortest way from A to B for the chess knight.
I don’t know why my program crashes when it comes to breadth-first search function. I cannot catch it with debugger because VScode freezes at reading variable “root” inside knight_moves.
Could you help me find the ussue?
I’ve created the board. It has links to every cell of the board according position of the cell.
I’ve created links between cells with add_edges function. Links are possible ways to move.
So far I’ve got the code below
class Node
attr_reader :pos
attr_accessor :children, :search_info
def initialize (row, column)
#pos = [row, column]
#children = nil
#search_info = Hash.new
end
end
class Board
attr_reader :show
def initialize
create_board
end
def create_board
board = []
8.times do |x|
board<<[x]
end
board.each_with_index do |item, index|
8.times do |x|
board[index] << x unless x == index
end
end
board.each do |x|
x.sort!
end
#board = board
end
def show
#board
end
def fill_with_nodes
#board.each_with_index do |item, index|
item.map! {|column| Node.new(index,column)}
end
end
def add_edges
#board.each_with_index do |row, index|
row.each do |node|
node.children = []
node.children = node.children << #board[node.pos[0]-2][node.pos[1]-1] if (0..7).include?(node.pos[0]-2) && (0..7).include?(node.pos[1]-1)
node.children = node.children << #board[node.pos[0]-2][node.pos[1]+1] if (0..7).include?(node.pos[0]-2) && (0..7).include?(node.pos[1]+1)
node.children = node.children << #board[node.pos[0]+2][node.pos[1]-1] if (0..7).include?(node.pos[0]+2) && (0..7).include?(node.pos[1]-1)
node.children = node.children << #board[node.pos[0]+2][node.pos[1]+1] if (0..7).include?(node.pos[0]+2) && (0..7).include?(node.pos[1]+1)
node.children = node.children << #board[node.pos[0]-1][node.pos[1]-2] if (0..7).include?(node.pos[0]-1) && (0..7).include?(node.pos[1]-2)
node.children = node.children << #board[node.pos[0]+1][node.pos[1]-2] if (0..7).include?(node.pos[0]+1) && (0..7).include?(node.pos[1]-2)
node.children = node.children << #board[node.pos[0]-1][node.pos[1]+2] if (0..7).include?(node.pos[0]-1) && (0..7).include?(node.pos[1]+2)
node.children = node.children << #board[node.pos[0]+1][node.pos[1]+2] if (0..7).include?(node.pos[0]+1) && (0..7).include?(node.pos[1]+2)
end
end
end
def cell (row, column)
#board[row][column]
end
def knight_moves (start, finish)
raise StandardError.new("Invalid start") unless (0..7).include?(start[0]) || (0..7).include?(start[1])
raise StandardError.new("Invalid finish") unless (0..7).include?(finish[0]) || (0..7).include?(finish[1])
queue = []
root = #board[finish[0]][finish[1]]
root.search_info[:distanse] = 0
queue << root
until queue.empty?
node = queue.shift
break if node.pos == [start[0],start[1]]
node.children.each do |child|
unless child.search_info[:distanse]
child.search_info[:distanse] = node.search_info[:distanse] + 1
child.search_info[:predecessor] = node
queue << child
end
end
end
end
end
#This part is for testing
puts a = Board.new
puts a.show.to_s
a.fill_with_nodes
puts a.show.to_s
a.add_edges
a.knight_moves([0,0], [0,1])
def show_cell(board,row, column)
puts ""
puts board.cell(row,column).pos.to_s, board.cell(row,column).children.map {|child| child.pos}.to_s ,board.cell(row,column).search_info.to_s
end
show_cell(a,2,2)
Edit: I've found that line "child.search_info[:predecessor] = node" crashes the programm. And if I use #variable to store "predecessor" instead of hash the programm runs. I don't know why though. What's the reason?
As for me, the main issue with the code is its unnecessary ("incidental") complexity.
Yes, the task you're solving can be reduced to a graph traversal problem, but it doesn't mean you must represent the graph explicitly. For this particular task - where all the possible moves from the arbitrary cell are well-defined and the board itself is limited - you can easily calculate the graph edges on the fly (and without all this additional machinery that makes your code so hard to reason about - even for you). Explicit representation of the board looks redundant too (again, for this particular task).
Taking all this into account, the solution might be as simple as:
class Knight
def initialize
#knight_moves = [[-2, -1], [-2, 1], [-1, -2], [-1, 2], [1, -2], [1, 2], [2, -1], [2, 1]]
end
def move(start, stop)
visited = {}
queue = [[stop, nil]]
while queue.any?
current_cell, next_cell = queue.shift
next if visited.has_key?(current_cell)
visited[current_cell] = next_cell
return build_path(start, stop, visited) if current_cell == start
possible_moves(current_cell).each do |next_move|
queue << [next_move, current_cell] unless visited.has_key?(next_move)
end
end
end
private
def possible_moves(cell)
#knight_moves.
map { |x, y| [cell.first + x, cell.last + y] }.
select(&method(:valid_move?))
end
def build_path(start, stop, visited)
path = [start]
while next_cell = visited[path.last]
path << next_cell
end
path.last == stop ? path : nil
end
def valid_move?(cell)
cell.all? { |n| n >= 0 && n <= 7 }
end
end
knight = Knight.new
knight.move [0,0], [0,1] #=> [[0, 0], [2, 1], [1, 3], [0, 1]]

Turning several Enumerables into one

Is there a way to get several Enumerable objects to appear as a single Enumerable without flattening it into an Array? Currently I've written a class like so, but I feel there must be a built-in solution.
class Enumerables
include Enumerable
def initialize
#enums = []
end
def <<(enum)
#enums << enum
end
def each(&block)
if block_given?
#enums.each { |enum|
puts "Enumerating #{enum}"
enum.each(&block)
}
else
to_enum(:each)
end
end
end
enums = Enumerables.new
enums << 1.upto(3)
enums << 5.upto(8)
enums.each { |s| puts s }
As a simple example, it needs to be able to accept an infinite enumerator like so.
inf = Enumerator.new { |y| a = 1; loop { y << a; a +=1 } };
Well, it might be done with standard library using Enumerator. The advantage of this approach would be it returns the real enumerator, that might be mapped, reduced etc.
MULTI_ENUM = lambda do |*input|
# dup is needed here to prevent
# a mutation of inputs when given
# as a splatted param
# (due to `input.shift` below)
input = input.dup.map(&:to_enum)
Enumerator.new do |yielder|
loop do
# check if the `next` is presented
# and mutate the input swiping out
# the first (already iterated) elem
input.first.peek rescue input.shift
# stop iteration if there is no input left
raise StopIteration if input.empty?
# extract the next element from
# the currently iterated enum and
# append it to our new Enumerator
yielder << input.first.next
end
end
end
MULTI_ENUM.(1..3, 4.upto(5), [6, 7]).
map { |e| e ** 2 }
#⇒ [1, 4, 9, 16, 25, 36, 49]
After all. Use Enumerable::Lazy#flat_map with .each.lazy on elements:
inf = Enumerator.new { |y| a = 1; loop { y << a; a += 1 } }
[(1..3).to_a, inf].lazy.flat_map { |e| e.each.lazy }.take(10).force
#⇒ [1, 2, 3, 1, 2, 3, 4, 5, 6, 7]
I ended up with this solution, maybe is close to what you already tried:
def enumerate(*enum)
enum.each_with_object([]) { |e, arr| arr << e.to_a }.flatten
end
enumerate( 1..3, 5.upto(8), 3.times, 'a'..'c' ).each { |e| p e }
# => 1, 2, 3, 5, 6, 7, 8, 0, 1, 2, "a", "b", "c"
Or (same mechanics):
def enumerate(*enum)
enum.flat_map { |e| e.to_a }
end

How can I pass in a block to my "bubble sort" method?

The below code is my newbie take on a bubble sort method.
#For each element in the list, look at that element and the element
#directly to it's right. Swap these two elements so they are in
#ascending order.
def bubble_sort (array)
a = 0
b = 1
until (array.each_cons(2).all? { |a, b| (a <=> b) <= 0}) == true do
sort = lambda {array[a] <=> array[b]}
sort_call = sort.call
loop do
case sort_call
when -1 #don't swap
a += 1
b += 1
break
when 0 #don't swap
a += 1
b += 1
break
when 1 #swap
array.insert(a,array.delete_at(b))
a += 1
b += 1
break
else #end of array, return to start
a = 0
b = 1
break
end
end
end
puts array.inspect
end
array = [4, 2, 5, 6, 3, 23, 5546, 234, 234, 6]
bubble_sort(array)
I want to be able to alter this method so that it takes a block of code as an argument and uses this to determine how it sorts.
For example:
array = ["hello", "my", "name", "is", "daniel"]
bubble_sort(array) {array[#a].length <=> array[#b].length}
(When I've tried this I've turned a and b into instance variables throughout the code.)
I have tried using yield but I get undefined method 'length' for nil:NilClass once the end of the array is reached. I've tried adding in things such as
if array[#b+1] == nil
#a = 0
#b = 1
end
This helps but I still end up with weird problems like infinite loops or not being able to sort more than certain amount of elements.
Long story short, I have been at this for hours. Is there a simple way to do what I want to do? Thanks.
The way you're calling your lambda is a bit odd. It's actually completely unnecessary. I refactored your code and cleaned up a bit of the redundancy. The following works for me:
def sorted?(arr)
arr.each_cons(2).all? { |a, b| (a <=> b) <= 0 }
end
def bubble_sort (arr)
a = 0
b = 1
until sorted?(arr) do
# The yield call here passes `arr[a]` and `arr[b]` to the block.
comparison = if block_given?
yield(arr[a], arr[b])
else
arr[a] <=> arr[b]
end
if [-1, 0, 1].include? comparison
arr.insert(a, arr.delete_at(b)) if comparison == 1
a += 1
b += 1
else
a = 0
b = 1
end
end
arr
end
sample_array = [4, 2, 5, 6, 3, 23, 5546, 234, 234, 6]
# Sanity check:
100.times do
# `a` is the value of `arr[a]` in our function above. Likewise for `b` and `arr[b]`.
print bubble_sort(sample_array.shuffle) { |a, b| a <=> b }, "\n"
end
EDIT
A cleaner version:
# In place swap will be more efficient as it doesn't need to modify the size of the arra
def swap(arr, idx)
raise IndexError.new("Index #{idx} is out of bounds") if idx >= arr.length || idx < 0
temp = arr[idx]
arr[idx] = arr[idx + 1]
arr[idx + 1] = temp
end
def bubble_sort(arr)
loop do
sorted_elements = 0
arr.each_cons(2).each_with_index do |pair, idx|
comparison = if block_given?
yield pair.first, pair.last
else
pair.first <=> pair.last
end
if comparison > 0
swap(arr, idx)
else
sorted_elements += 1
end
end
return arr if sorted_elements >= arr.length - 1
end
end
# A simple test
sample_array = [4, 2, 2, 2, 2, 2, 5, 5, 6, 3, 23, 5546, 234, 234, 6]
sample_str_array = ["a", "ccc", "ccccc"]
100.times do
print bubble_sort(sample_array.shuffle) { |a, b| a <=> b }, "\n"
print bubble_sort(sample_str_array.shuffle) { |a, b| a.length <=> b.length }, "\n"
end
You're not too far off. Just a few things:
Make your function take a block argument
def bubble_sort (array, &block)
Check to see if the user has provided a block
if block_given?
# Call user's comparator block
else
# Use the default behavior
end
Call the user's comparator block
block.call(a, b)
In the user-provided block, accept block params for the elements to compare
bubble_sort(array) {|a,b| a.length <=> b.length}
That should put you in the right ballpark.

Subset Sum: Ruby with ".combination"

Details of the problem: To find if any combination of the array adds to the largest number found in the array.
Here are the steps I am trying to implement:
Extract the largest number from the array
Create a new array of
all the potential combinations that could be added by using
.combination
Test to see if any of these combinations equals the largest number in the original array.
Status: So far, I am just receiving an unexpected end error for the last end in the code. (I have found different answers online on how to solve the subset sums problem in Ruby, but would like to figure out how to solve it using the logic I have used so far.)
Any help would be great!
def subset_sum(sums)
largest_number = subset_sum.sort.reverse[0]
array_without_largest = subset_sum.sort.reverse[1..-1]
full_combination = []
i = 0
while i <= array_without_largest.length
full_combination = full_combination + array_without_largest.combination(i).to_a.to_s
i += 1
end
j = 0
while j <= full_combination.length
return true if full_combination[j].inject { |sum, x| sum + x} == largest_number
j += 1
end
end
return false
end
puts subset_sum(1,2,3,4,10)
puts subset_sum(-1,-3,3,9,8)
Consider this:
def any_subset_adds_to_max?(array)
sub_array = array - [array.max]
every_combination = (1..sub_array.length).flat_map { |n| sub_array.combination(n).to_a }
every_combination.any? { |combination| combination.reduce(:+) == array.max }
end
[
[1, 2, 3, 4, 10],
[-1, -3, 3, 9, 8]
].map { |test_array| any_subset_adds_to_max? test_array } # => [true, false]
Here is the closest example of the code that I could do while maintaining the originality. It works and I appreciate the help!
def subset_sum(sums)
largest_number = sums.max
array_without_largest = sums - [largest_number]
full_combination = []
array_without_largest.size.times do |i|
full_combination << array_without_largest.combination(i+1).to_a
end
full_combination.flatten!(1)
full_combination.size.times do |i|
return true if full_combination[i].inject(:+) == largest_number
end
false
end

Deleting While Iterating in Ruby?

I'm iterating over a very large set of strings, which iterates over a smaller set of strings. Due to the size, this method takes a while to do, so to speed it up, I'm trying to delete the strings from the smaller set that no longer needs to be used as it goes along. Below is my current code:
Ms::Fasta.foreach(#database) do |entry|
all.each do |set|
if entry.header[1..40].include? set[1] + "|"
startVal = entry.sequence.scan_i(set[0])[0]
if startVal != nil
#locations << [set[0], set[1], startVal, startVal + set[1].length]
all.delete(set)
end
end
end
end
The problem I face is that the easy way, array.delete(string), effectively adds a break statement to the inner loop, which messes up the results. The only way I know how to fix this is to do this:
Ms::Fasta.foreach(#database) do |entry|
i = 0
while i < all.length
set = all[i]
if entry.header[1..40].include? set[1] + "|"
startVal = entry.sequence.scan_i(set[0])[0]
if startVal != nil
#locations << [set[0], set[1], startVal, startVal + set[1].length]
all.delete_at(i)
i -= 1
end
end
i += 1
end
end
This feels kind of sloppy to me. Is there a better way to do this?
use delete_if
array.delete_if do |v|
if v.should_be_deleted?
true
else
v.update
false
end
end
use 'arr.shift'
a=[1,2,3,4]
while(a.length!=0)
print a
a.shift
print "\n"
end
Output:
[1, 2, 3, 4]
[2, 3, 4]
[3, 4]
[4]

Resources