Issue regarding variable alteration in Ruby [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 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. :-)

Related

Why am I getting all these nils - Euler 3

I came up with this solution for Project Euler 3 although I got the answer I also get so many nils before it I can't figure out why? is there any way I can only get the answer.
Anyway here is my code
def factor(number)
max = []
(2...number).each do |x|
if number % x == 0
number = number/x
max << number
s = max[-2]
elsif number == 1
return[]
end
puts s
end
end
puts factor(600851475143)
max is an empty array. s = max[-2] is s =[][-2] for a long time. [][-2] returns nil.

Maximum Calculation Possible

I have a method to calculate the factorial of an input number
def fact( n )
if (n == 0)
1
else
n * fact(n-1)
end
end
I want to create a loop that will test what the maximum possible calculable value is for this method. For my machine this number is 8734, but I found that through trial and error.
My idea is to create a for/ each loop and test whether the returned result is a real number or not. I only want to puts the last numerical value that actually produces a real numerical result.
Thanks!
I would do something like this:
i = 1
loop do
begin
fact(i)
rescue SystemStackError
puts "stack level too deep at: #{i}"
break
end
i += 1
end
Note that this is a very naive algorith that checks every number and might take some time. It would be must faster to Do some kind of binary search on a range of numbers.
You can do as #spickermann suggests, but there is no need to search for the argument for fact at which the exception is raised. Rather, just compute fact(n) for any suitably large value of n (e.g. n = 100_000), increment a stack depth counter each time fact is called, and report the value of that counter when the SystemStackError exception is raised. The following code performs that calculation for various values of n, showing that the value of n is not important, so long as it is suitably large. I would think n = 100_000 would be plenty large for any Ruby implementation, but make it a million if you like.
def fact( n )
#stack_size += 1
if (n == 0)
1
else
n * fact(n-1)
end
end
[10_000, 20_000, 50_000, 100_000, 8733, 8732].each do |n|
print "n=#{n.to_s.ljust(6)}: "
begin
#stack_size = 0
fact(n)
rescue SystemStackError
puts "stack level too deep at: #{#stack_size}"
end
end
# n=10000 : stack level too deep at: 8733
# n=20000 : stack level too deep at: 8733
# n=50000 : stack level too deep at: 8733
# n=100000: stack level too deep at: 8733
# n=8733 : stack level too deep at: 8733
# n=8732 :
Note that the exception was not raised when n => 8732.
Does the maximum stack depth depend on the method? Most certainly! If we replace fact with:
def fact(n)
#stack_size += 1
fact(n-1)
end
we get:
# stack level too deep at: 9356

Ruby diagonal matrix from random numbers [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 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

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.

Is it possible to check to the position of an iterator in Ruby? [duplicate]

This question already has answers here:
How to get the array index or iteration number with an each iterator?
(2 answers)
Closed 8 years ago.
Is there a way to get the position of an iterator (how many times it has iterated)?
values = (1..100)
values.each do |value|
if ... % 10 == 1 then puts iterator.count end
end
Or do you have to count explicitly:
values = (1..100)
counter = 0
values.each do |value|
if counter % 10 == 1 then puts counter end
counter += 1
end
Is there a cleaner approach?
Ruby 1.9.2
Use each_with_index
values.each_with_index do |value, idx|
puts idx if idx % 10 == 1
# do something else
end
Or you can use a cooler alternative
values.each.with_index do |value, idx|
# work
end
I called it cooler because #with_index is relatively less known and it can be combined with map (and other methods) to yield interesting results.

Resources