How to add values of arrays having different lengths [duplicate] - arrays

This question already has answers here:
Sum of arrays of different size [closed]
(4 answers)
Closed 6 years ago.
I want to add values of two different length array.
a =[1,2,3]
b= [1,2]
c = [1,2,3,4]
and so on..
I want result to be like [3,6,6,4]. How to do this in ruby on rails.

In order to make it dynamic, I would create arrays of array with your a, b, c =>
a = [1, 2, 3]
b = [1, 2]
c = [1, 2, 3, 4]
arrays = [a, b, c]
Then I would retrieve the max size :
max_size = arrays.map(&:size).max #=> 4
Then the following line would give you your answer :
max_size.times.map{ |i| arrays.reduce(0){|s, a| s + a.fetch(i, 0)}} #=> [3, 6, 6, 4]

You can build a new array that consists of all those array, and then can write the following code to get the array that has combined entries of each array:
a = [1,2,3]
b = [1,2,3]
c = [1,2,3,4]
Before you apply the rest of the code, you need to make sure that each array has the same length. For that, you can append 0 in all the arrays if need be, to ensure that each array has the same length as the rest of the arrays have.
a = [1,2,3,0]
b = [1,2,3,0]
c = [1,2,3,4]
combined_array = [a,b,c]
result = combined_array.transpose.map { |a| a.reduce :+ }

Extending the answer from #Arslan Ali
I added a way to make all the arrays the same size, so that his method of summing can be applied:
a = [1,2,3]
b = [1,2,3]
c = [1,2,3,4]
arrays = [a, b, c]
size = [a, b, c].map{|a| a.size}.max # Compute maximum size
combined_array = [a,b,c].map{|a| a.fill(a.size...size){0}} # Fill arrays to maximum size
result = combined_array.transpose.map { |a| a.reduce :+ } # Sum everything

Here's one way:
a = [1, 2, 3]
b = [1, 2, 3]
c = [1, 2, 3, 4]
[a,b,c].inject([]) do |totals, add|
add.each_with_index do |n, i|
totals[i] = (totals[i] || 0) + n
end
totals
end

Related

Merge multiple arrays into a multidimensional one in Swift?

Example
let a = [a, b, c]
let b = [x, y, z]
I need this response
let c = [[a, b, c],[x, y, z]]
There are two approaches as I see it, either I concatenate both arrays (don't know if it's possible), or to append it directly in a multidimensional array.
If you will try to concatenate it:
let a = [1, 2, 3]
let b = [4, 5]
let c = a + b // will receive [1, 2, 3, 4, 5]
let d = [a, b] // will receive multidimensional array [[1, 2, 3], [4, 5]]
var e: [[Int]] = []
e.append(a)
e.append(b)
print(e) // should be equal to d

Modifying a 3d array using a 2D index with Numpy

I have an array in three dimensions (a, b, c) and I need to modify the positions c indexed by an array in two dimensions (a, b).
I wrote a code that works as expected, but does anyone know if there is a way to solve this problem without the for loop?
import numpy as np
arr = np.random.randn(100, 5, 2)
mod = np.random.randn(100, 5)
ids = np.random.randint(0, 2, size=[100,5])
for i in range(100):
for j in range(5):
arr[i,j,ids[i,j]] = mod[i,j]
You can refer to and set each slice of the array directly. I think this code shows the behaviour you are asking about:
import numpy as np
arr = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])
print(arr[:,:,2])
# Output:
#[[ 3 6]
# [ 9 12]]
new2DSlice = np.array([[23, 26], [29, 32]])
arr[:,:,2] = new2DSlice
print(arr[:,:,2])
# Outupt:
#[[23 26]
# [29 32]]
arr[:,:,2] refers to the third slice of the array and, in this example, sets it directly.
You can read about NumPy's array indexing and array slicing on W3Schools.
I got with this:
import numpy as np
arr = np.random.randn(100, 5, 2)
mod = np.random.randn(100, 5)
ids = np.random.randint(0, 2, size=[100,5])
x = np.arange(100)
y = np.arange(5)
arr[x[:,None],y,ids] = mod

Subtract arrays with frequency [duplicate]

This question already has answers here:
Ruby array subtraction without removing items more than once
(4 answers)
Closed 6 years ago.
I'm trying to subtract an array from another array taking frequency into account, like this:
[1,2,2,2] some_code [1,2] # => [2,2]
What's the easiest way to accomplish this?
Using - removes all occurrences of the elements in the second array:
[1,2,2,2] - [1,2] # => []
a1 = [1,2,2,2]
a2 = [1,2]
a2.each { |e| (idx = a1.find_index e) && (a1.delete_at idx) }
#⇒ [2, 2]
Here we iterate the second array and delete elements from the first one, once per iteration, if those were found.
The first found element will be deleted.
a = [1, 2, 2, 2]
b = [1, 2]
ha = a.each_with_object(Hash.new(0)){|e, h| h[e] += 1}
# => {1=>1, 2=>3}
hb = b.each_with_object(Hash.new(0)){|e, h| h[e] += 1}
# => {1=>1, 2=>1}
(ha.keys | hb.keys).flat_map{|k| Array.new([ha[k] - hb[k], 0].max, k)}
# => [2, 2]
If I understood the problem correctly, that you wish to delete single occurrence of each element of array b from array a, here is one way to do this:
a.keep_if {|i| !b.delete(i)}
#=> [2,2]
PS: Both arrays a and b are mutated by above code, so you may want to use dup to create a copy if you want to retain original arrays.
def subtract arr_a, arr_b
arr_b.each do |b|
idx = arr_a.index(b)
arr_a.delete_at(idx) unless idx.nil?
end
end
Output:
a = [1,2,2,2]
b = [1,2]
subtract a, b
puts "a: #{a}"
# => a: [2, 2]

Define multiple variables at the same time in MATLAB

I want to define multiple variables at the same time.
For example, I want to define
a = 1
b = 2
c = 3
like this.
So I made a matrix with [a,b,c]:
x = [a, b, c];
y = [1, 2, 3];
x = y
So I want to get the following answer.
a = 1
b = 2
c = 3
If I use
[a, b, c] = deal(1, 2, 3)
then, I can get
a = 1
b = 2
c = 3
But I want to use matrix x instead of [a, b, c]
So if I use,
x = deal(1,2,3)
there is an error.
Is there any solution?
Maybe I don't understand the question but if you want to use the matrix x instead of [a, b, c] why don't you just define it as
x = [1, 2, 3];
From your question it sounds to me as if you are overcomplicating the problem. You begin by wanting to declare
a = 1;
b = 2;
c = 3;
but what you want instead according to the end of your question is
x = [1, 2, 3];
If you define x as above you can the refer to the individual elements of x like
>> x(1), x(2), x(3)
ans =
1
ans =
2
ans =
3
Now you have the best of both worlds with 1 definition. You can refer to a, b and c using x(1), x(2), x(3) instead and you've only had to define x once with x = [1, 2, 3];.
You cannot deal into a numeric array, but you can deal into a cell array and then concatenate all the elements in the cell array, like this:
[x{1:3}] = deal(1, 2, 3); % x is a cell array {1, 2, 3}
x = [x{:}]; % x is now a numeric array [1, 2, 3]

Slicing an Array

I am having trouble finding a matlab function to slice an element out of an array.
For example:
A = [1, 2, 3, 4]
I want to take out on element of this array, say the element 3:
B = [1, 2, 4]
Is there a matlab function for this or would I have to code the algorithm to construct a new array with all the elements of A except 3?
Do this:
index_of_element_to_remove = 3;
A(index_of_element_to_remove) = [];
now A will be [1 2 4]
If you want to remove more elements at the same time you can do:
index_of_element_to_remove = [1 3];
A(index_of_element_to_remove) = [];
now A will be [2 4]
By value, which will remove all elements equal to 3
A(find(A==3)) = []
Or by index
A(3) = []

Resources