Ruby diagonal matrix from random numbers [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 8 years ago.
Improve this question
I need to create a diagonal matrix (8x8) and fill it with random numbers in [-30..45] range
After I need to transform array into vector and sort it
I tried different ways.
At first I create matrix (8x8)
matrix = Matrix.build(8) {0}
puts matrix.each_slice(matrix.column_size) {|r| p r }
Also I made an array with random numbers in range
array = (-30..45).to_a.shuffle
puts array [0..8]
And made a diagonal matrix
matrixd = Matrix.diagonal(1,2,3,4,5,6,7,8)
puts matrixd.each_slice(matrix.column_size) {|r| p r}
How can i fill diagonal matrix with my array and put it in vector?
I have 2 algorithms for sorting vector
class Array
def bubblesort!
length.times do |j|
for i in 1...(length - j)
if self[i] < self[i - 1]
self[i], self[i - 1] = self[i - 1], self[i]
end
end
end
self
end
end
class Array
def selectionsort!
0.upto(length - 2) do |i|
(min_idx = i + 1).upto(length - 1) do |j|
if self[j] < self[min_idx]
min_idx = j
end
end
if self[i] > self[min_idx]
self[i], self[min_idx] = self[min_idx], self[i]
end
end
self
end
end

For the diagonal matrix:
elems = [*-30..45].sample(8)
Matrix.diagonal(*elems)
For the rest, I'm not sure what you're trying to accomplish

Related

taking a random amount of hash pairs and putting it in another 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 5 years ago.
Improve this question
I'm trying to take several key value pairs at random from one hash to another. Taking n values from h and putting it into i
h = {"a"=>1,"b"=>2,"c"=>3}
n = 2
i = {}
If you are using Ruby 2.5+, take advantage of the sweet new Hash#slice method, which is designed to do exactly this:
>> h = {"a"=>1,"b"=>2,"c"=>3}
>> n = 2
>> h.slice(*h.keys.sample(n))
#> {"c"=>3, "a"=>1}
You can get an array of random keys with keys.sample then iterate over them to add keys and values from h into i.
h = {"a"=>1,"b"=>2,"c"=>3}
n = 2
i = {}
h.keys.sample(n).each { |k| i[k] = h[k] }
i #=> {"b"=>2, "c"=>3}
Or you can just map the sample keys with values from h then convert to a hash.
h.keys.sample(n).map { |k| [k, h[k]] }.to_h
#=> {"b"=>2, "a"=>1}
h = {"a"=>1,"b"=>2,"c"=>3}
n = 2
random_keys = h.keys.sample(n)
i = random_keys.each_with_object({}){|m,o| o[m] = h[m]}
p i
Results:
{"b"=>2, "c"=>3}
sample method will take n random keys as an array.
each_with_objece Iterates elements of random_keys with new hash o.
h = {"a"=>1,"b"=>2,"c"=>3}
n = 2
g = {pet: 'dog'}
rnd_keys = h.keys.sample(n)
#=> ["c", "a"|
g.merge(h.select { |k,_| rnd_keys.include?(k) })
#=> {:pet=>"dog", "a"=>1, "c"=>3}
If, as in the example, g is empty, simply:
h.select { |k,_| rnd_keys.include?(k) }
# => {"a"=>1, "c"=>3}

Finding from the list neg and pos numers in Ruby [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
Two lists of numbers, one with the input pos numbers, and one
with those that are neg numbers (ignore the zero-valued numbers)
Method: You must first build two arrays with the required output numbers, before you
display any of them
the below code is not ruby. how can i convert it to ruby?
# Loop to read input and build the two new arrays
while ($next = <>) {
if ($next > 0) {
push #pos_list, $next;
}
else {
if ($next < 0) {
push #neg_list, $next;
}
}
}
# Output the results
print "The array of positive numbers: \n #pos_list \n";
print "\nThe array of negative numbers: \n #neg_list \n";
numbers = [4,-2,7,3,0,-8]
pos_list = numbers.select {|x| x > 0}
neg_list = numbers.select {|x| x < 0}
p pos_list # => [4, 7, 3]
p neg_list # => [-2, -8]
numbers is your array of numbers, which you have built from user input. Array#select returns a new array containing all elements that cause the attached block to evaluate to true. See: http://www.ruby-doc.org/core-2.1.0/Array.html#method-i-select
Assuming numbers to be the array of numbers from the input:
pos = []
neg = []
numbers.each do |n|
pos += n if n > 0
neg += n if n < 0
end
After the above code executes you can retrieve positive numbers from pos and negative ones from neg.
How you populate numbers can vary. A possible solution is too loop and keep asking for a number:
numbers = []
begin
current = gets.chomp.to_i
numbers << current if current > 0
end until current == 0
assuming you don't want 0 to be part of number. Otherwise you'll have to check for a given input to stop the loop. Alternatively you can have a fixed size of numbers.

combine methods 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 9 years ago.
Improve this question
In an effort to speed up my program, I'm trying to combine these two methods, but am having the hardest time doing it. Here are the methods:
def prime?(number, array)
array.each do |x|
if number % x == 0
return false
end
end
true
end
def sum_prime_2(number)
i = 0
prime = 1
output = [2]
while prime < number
if prime?(prime, output)
i += 1
output << prime if prime != 1
end
prime += 2
end
output.inject(:+)
end
And here is what I've come up with, but it's not quite working. I'd love any help.
def sum_prime(number)
i = 0
prime = 1
output = [2]
while prime < number
if output.each { |x| prime % x == 0 } == true # prime? method
output << prime if prime != 1
i += 1
end
prime += 2
end
output.inject(:+)
end
Here's a simplification of your current approach:
def sum_primes(limit)
primes = [2]
n = 3
while n < limit
primes << n if primes.all? { |p| n % p != 0 }
n += 2
end
primes.inject(:+)
end
But you can do better. For example, there's no need to check for divisibility by all prior primes -- only up to the square of n. Even better would be a sieve approach, particularly an incremental one.
I would actually use this code, rather than combining the two functions:
def prime?(number, array)
array.each do |x|
if number % x == 0
return false
end
return true if x * x > number
end
true
end
Doing a quick benchmark for sum_prime_2(100000) versus FMc's answer versus mine, the original code takes about 5.0 seconds, FMc's takes 6.5 seconds, but my version just 0.1 seconds.

Ruby puts not putting [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 am answering the following question:
Q3: Write a method, is_prime?, that takes a number num and returns
true if it is prime and false otherwise.
You may wish to use the modulo operation: 5 % 2 returns the remainder
when dividing 5 by 2: 1. If num is divisible by i, then num % i == 0.
(You would not be expected to already know about modulo for the
challenge)
but I get no answer back. My final "puts" doesn't seem to be working. Here is my code:
# Q3 method is_prime?
def is_prime? (num)
i = 2
while i <= num
is_divisble = ((num%i) == 0)
if is_divisble
return false
end
i+=1
end
# is not divisible
return true
end
puts 'select a number greater than one and see if it\'s prime'
num = gets.chomp.to_i
puts is_prime?(num)
The code prints fine. However, it always prints true. Remedy: change while i <= num
to while i < num .
i <= num
It is your mistake :).
Your code will increment i until i == num so num%i will always be true at the end.
Just replace it with
i < num

Issue regarding variable alteration 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 have the following code...
#organisims.each do |organisim|
randomvalue = rand(10)
prediction = organisim.predict
if prediction == randomvalue
organisim.resources += 1
end
if prediction != randomvalue
organisim.resources -= 1
end
end
I am trying to alter the 'organisims' resources if the prediction it makes matches the randomly generated number. It seems to work fine, -1 if no match, +1 if there is a match.
The problem is that when I iterate this array (of organisims), processing their resources, I recieve duplicates in my output, such as
Cycle 100
Average resouces: 1500
Cycle 101
Average resouces: 1500
Then again,
Cycle 102
Average resouces: 1400
Cycle 103
Average resouces: 1400
Is this an issue with my code (I see no issues with it) or with the psudorandom number generator that Ruby uses?
Cheers as always
Martin
I think this may be an issue of the scope of your accumulator consider this example.
# example Organism class
class Organisim
attr_accessor :predict, :resources, :prediction
def initialize
#resources = 0
end
def predict
#prediction = rand(10)
#prediction
end
end
# initialize #organisims
#organisims = []
100.times do
#organisims << Organisim.new
end
puts "!!!! Starting Organisim Specific Run"
# iterate over array tracking organisim's resource
#organisims.each_with_index do |org, i|
# parrallel assignment
r, p = rand(10), org.predict
#ruby ternery operator
(p == r) ? org.resources += 1 : org.resources -= 1
puts "Run #{i} Prediction: #{org.prediction} Instance Resources: #{org.resources} Overall Resources: n/a"
end
puts "!!!! Cumulative Resource Run"
# resources scoped outside the iteration loop as accumulator
overall_resources = 0
# re-initialize #organisims
#organisims = []
100.times do
#organisims << Organisim.new
end
#organisims.each_with_index do |org, i|
# parrallel assignment
r, p = rand(10), org.predict
#ruby ternery operator
#track class level resource
(p == r) ? org.resources += 1 : org.resources -= 1
#iterate accumulator
(p == r) ? overall_resources += 1 : overall_resources -= 1
puts "Run #{i} Prediction: #{org.prediction} Instance Resources: #{org.resources} Overall Resources: #{overall_resources}"
end
The first iteration loop is like (I think) the one that you have in your question but you're changing the resource within the organisim object instance.
The second iteration your accumulator is outside the scope of your iteration so it grows and shrinks as the objects are acted upon. :-)

Resources