multiply array using each on ruby - arrays

I've been stuck on this problem. I'd appreciate any help.
The instructions
"Use the .each method on the odds array to print out double the value of each item of the array. In other words, multiply each item by 2.
Make sure to use print rather than puts, so your output appears on one line."
My code
odds = [1,3,5,7,9]
odds.each do |placeholder|
odds *= 2
print odds
end

odds = [1,3,5,7,9]
odds.each do |placeholder|
odds *= 2
print odds
end
Your usage of #each is correct here, but remember that #each receives an ::Enumerable object, the block passed in uses the variable placeholder to encapsulate the value in the ::Array at the current point of the iteration. Therefore you would need to use placeholder to retrieve the value you want to double, and not odds because odds would still be an ::Array within the ::Enumerable function #each.
This code can be written in two lines as follows:
odds = [1,3,5,7,9]
odds.each {|placeholder| print placeholder * 2 }
Strictly speaking, #map would be the preferred method for doing this.

odds.each { |x| print "#{x*2}" }
ruby-ish way:
print odds.map {|x| x*2}.join(' ')

You are trying to multiply the Array odds by two in each iteration in your code. The do |placeholder| means 'for each item in the array, give me the single element and call it placeholder'.
So you would need to use placeholder *= 2.
However, since you aren't mutating the original value in odds, you can shorten your inner block by just print placeholder * 2.
Additionally, while the question might be saying to use :each, :map is much more canonical to what you are doing. Using map would allow you to double each element like so:
odds.map{ |i| i*2 }

odds is your array. placeholder represents a value from the array. Without explicitly providing you the answer, what you want to do is multiply the value by 2, not the array itself.

Here Iam done that on succesfully
odds = [1,3,5,7,9]
odds.each do |x|
x *= 2
print x
end

Related

Matlab array storing through loop

I have a for loop and each value a{i} b{i} c{i} is equal each time with a specific number. So I was wondering how can I put all those value in an array through loop. The way that I am using I mean this one [a{i};b{i};c{i}] it seems that it doesn't work! If I keep 2 out of three values is working but I want the data from all of the values (a b c)
You can see the (pseudo)code below:
for i=1:number of cells
Cell{i}.Tri=[a{i};b{i};c{i}]
end
cell2mat is what you need:
a = num2cell(rand(1,10));
b = num2cell(rand(1,10));
c = num2cell(rand(1,10));
abc = cell2mat([a;b;c]);
This can be done without a for loop by using cellfun combined with the cat function. EDIT: As noted in the comments, cellfun is itself a loop.
% Create all variables
a{1}=rand(10);
a=repmat(a,10,1);
b=a;
c=a;
% Add a cell array of equal size to a. The contents of each cell are the dimension along which to concatenate.
catarg=num2cell(ones(size(a)))
% Do the concatenation
d=cellfun(#cat,catarg,a,b,c,'UniformOutput',false);

Yielding a modified Ruby array to a block

I'm trying to turn 2 lines of ruby code into 1. For example:
def average(numbers)
result = numbers.compact
numbers.reduce(+) / numbers.length
end
I've been looking through array methods and can't find an appropriate one to turn this function into a one-liner. I had hoped something like this would work:
def average(numbers)
numbers.compact.<tap or another method> { |arr| arr.reduce(+) / arr.length }
end
Basically, I'm modifying the array (in the example I have to call compact to rid nil values), so I don't have access to the array variable, and I don't want an iterator, because I don't want to call reduce(+) and length on individual elements of the array.
Does anyone have an idea of methods I could look into?
I believe you mean for your method to be the following (reduce(:+), not reduce(+) and use result rather than numbers in the second line).
def average(numbers)
result = numbers.compact
result.reduce(:+) / result.length
end
average [1,2,3]
#=> 2
If you wish the average to be a float, change the second line to
result.reduce(0.0, :+) / result.length
There are various ways to combine the two lines of the method, but I don't prefer any of them to the above. Here are a few. (I don't see how Object#tap could be used here.)
numbers.compact.reduce(:+) / numbers.compact.length
(result = numbers.compact).reduce(:+) / result.compact.length
numbers.map(&:to_i).reduce(:+) / numbers.compact.length
Note that, even if numbers can be mutated, one cannot write
numbers.compact!.reduce(:+) / numbers.length
because numbers.compact! returns nil if numbers contains no nil elements.
In Ruby v2.4+ you can use Array#sum:
result.sum / result.length
You could change the way you call average
def average(numbers)
numbers.reduce(:+) / numbers.length
end
average(num_array.compact)

Loop through an array while summing the output

I am trying to use a for loop and then sum all of the outputs. I know this is a basic question, but I am not sure if I should be trying to solve this within the loop or using another array.
For example:
for i in 1..100
if foo / 2 == 0
#find the sum of all outputs
end
end
Try this:
(2..100).step(2).inject(:+) #=> 2550
Or:
2.step(100,2).inject(:+) #=> 2550
You can use sum instead of inject(:+) from Ruby 2.4+
I'm not entirely sure what you're asking, but my initial understanding is that you want to sum all of the numbers in a range (1..100) that meet a specific condition. In this case, something divided by 2 cannot equal zero aside from zero itself. I'm wondering if you meant %2, in which case, you're asking to sum all the even numbers in the range 1..100. This can be accomplished by doing the following.
(1..100).select {|x| x if x.even?}.reduce(:+)
Effectively, you want to enumerate over a range and select only the numbers that meet your condition, as specified in the block. Calling reduce and passing it an accumulator.

How do I subtract a value from each element of an array in Lua?

I am trying to write a function to find the variance of a data set.
I am stuck on a small problem. I have an array, and I want to find how far each element in the array is from the average. Here is a simplified version of what I wrote:
>y={1,2,3}
>y_average=2
>y_diff={}
>for key, value in pairs(y) do y_diff[key]=(y[key]-y_average)
>>return unpack(y_diff)
>>end
-1
what I want to get: -1, 0, 1
Why does it only give me the first value and not all three?
Your return is breaking the loop in the first iteration as mentioned in a comment. Try this:
for i in ipairs(y) do
y_diff[i] = y[i] - y_average
end
print( table.concat(y_diff, '\t') )
table.concat doesn't have a limit on the amount of elements it can handle and it would be what you would use if you wanted to put these elements in a file faster than writing them one by one.

Finding whether a value is equal to the value of any array element in MATLAB

Can anyone tell me if there is a way (in MATLAB) to check whether a certain value is equal to any of the values stored within another array?
The way I intend to use it is to check whether an element index in one matrix is equal to the values stored in another array (where the stored values are the indices of the elements which meet a certain criteria).
So, if the indices of the elements which meet the criteria are stored in the matrix below:
criteriacheck = [3 5 6 8 20];
Going through the main array (called array) and checking if the index matches:
for i = 1:numel(array)
if i == 'Any value stored in criteriacheck'
%# "Do this"
end
end
Does anyone have an idea of how I might go about this?
The excellent answer previously given by #woodchips applies here as well:
Many ways to do this. ismember is the first that comes to mind, since it is a set membership action you wish to take. Thus
X = primes(20);
ismember([15 17],X)
ans =
0 1
Since 15 is not prime, but 17 is, ismember has done its job well here.
Of course, find (or any) will also work. But these are not vectorized in the sense that ismember was. We can test to see if 15 is in the set represented by X, but to test both of those numbers will take a loop, or successive tests.
~isempty(find(X == 15))
~isempty(find(X == 17))
or,
any(X == 15)
any(X == 17)
Finally, I would point out that tests for exact values are dangerous if the numbers may be true floats. Tests against integer values as I have shown are easy. But tests against floating point numbers should usually employ a tolerance.
tol = 10*eps;
any(abs(X - 3.1415926535897932384) <= tol)
you could use the find command
if (~isempty(find(criteriacheck == i)))
% do something
end
Note: Although this answer doesn't address the question in the title, it does address a more fundamental issue with how you are designing your for loop (the solution of which negates having to do what you are asking in the title). ;)
Based on the for loop you've written, your array criteriacheck appears to be a set of indices into array, and for each of these indexed elements you want to do some computation. If this is so, here's an alternative way for you to design your for loop:
for i = criteriacheck
%# Do something with array(i)
end
This will loop over all the values in criteriacheck, setting i to each subsequent value (i.e. 3, 5, 6, 8, and 20 in your example). This is more compact and efficient than looping over each element of array and checking if the index is in criteriacheck.
NOTE: As Jonas points out, you want to make sure criteriacheck is a row vector for the for loop to function properly. You can form any matrix into a row vector by following it with the (:)' syntax, which reshapes it into a column vector and then transposes it into a row vector:
for i = criteriacheck(:)'
...
The original question "Can anyone tell me if there is a way (in MATLAB) to check whether a certain value is equal to any of the values stored within another array?" can be solved without any loop.
Just use the setdiff function.
I think the INTERSECT function is what you are looking for.
C = intersect(A,B) returns the values common to both A and B. The
values of C are in sorted order.
http://www.mathworks.de/de/help/matlab/ref/intersect.html
The question if i == 'Any value stored in criteriacheck can also be answered this way if you consider i a trivial matrix. However, you are proably better off with any(i==criteriacheck)

Resources