Sum every 3 elements of an array in ruby - arrays

Is there any efficient and short way to sum every 3 elements of an array?
ar = [1, 2, 3, 4, 5, 6, 7, 8, 1]
sum_ar = [6, 15, 16]
first 3 elements 1+2+3=6
next 3 elements 4+5+6=15
next 3 elements 7+8+1=15
...
if there are only two elements left, sum them
I could do something like this:
y=0
s=ar.size/3
((0..s).step(3).to_a).each do |i|
sum_ar[y]=ar[i..i+2].inject(:+)
y=y+1
end
but then I will miss the elements in case of such an array, where the size is not an exactly multiply of a 3:
ar=[1, 2, 3, 4, 5, 6, 7, 8]

A short way with Enumerable#each_slice:
[1, 2, 3, 4].each_slice(3).map { |e| e.inject(:+) } # => [6, 4]

Related

Sorting an array according to an element inside this array

I need to order my array according to an element of it, the reference element can vary.
For example, I would like the 3 to become the first element of the array and the 1, 2 to be put at the end.
array = [1, 2, 3, 4, 5, 6]
new_array = [3, 4, 5, 6, 1, 2]
The element may vary. If I start from 5, the behavior must be the same: the elements that precede are placed at the end, so I will have :
new_array = [5, 6, 1, 2, 3, 4]
If I understand correctly you want to rotate the array.
array
# [1, 2, 3, 4, 5, 6]
array.rotate(2) # or array.rotate(array.index(3))
# [3, 4, 5, 6, 1, 2]
https://apidock.com/ruby/v2_5_5/Array/rotate
Definitely use #rotate for this in actual use, but as an alternative, you could do something like #shift and #push until the desired element is at the beginning of the array.
def rotate(arr, elem)
arr2 = arr.clone
arr2.push(arr2.shift) until arr2.first == elem
arr2
end
irb(main):026:0> arr = [1, 2, 3, 4, 5, 6]
=> [1, 2, 3, 4, 5, 6]
irb(main):027:0> rotate(arr, 3)
=> [3, 4, 5, 6, 1, 2]
irb(main):028:0> arr
=> [1, 2, 3, 4, 5, 6]
Clearly, if elem is not in arr, this will run forever. You could implement some kind of check to ensure this doesn't happen, but that's just one reason you shouldn't actually do this as anything other than a learning exercise.
One approach would be to find the index of elem in arr and shift/push that many times. The &. operator may be useful in that situation to deal with the possibility of not finding elem in arr.

Combining 2-dimensional array (matrix) elements

I have a 2-dimensional array like [[1,2,3], [4,5,6], [7,8,9]].
So I need to combine every element with all the others form another sublists ang get an array like [[1,4,7], [1,4,8], [1,4,9], [2,4,7], [2,4,8], [2,4,9], [3,4,7], [3,4,8], [3,4,9], [1,5,7], [...], [...], ... etc] in Python3.
! The number of sublists may be different.
I have used different approaches with loops but nothing works correctly. How can I do that without using itertools? Thanks in advance!
I tried iterating arrays but I could not fully embody the idea.
arr = [[1,2,3], [4,5,6], [7,8,9]]
total = []
for i in arr[0]:
for index, j in enumerate(arr[1:]):
res = [i]
for indx, n in enumerate(j):
res.append(n)
for m in arr[index+1]:
res.append(m)
break
print(res)
And I got only this
[1, 4, 4, 5, 4, 6, 4]
[1, 7, 7, 8, 7, 9, 7]
[2, 4, 4, 5, 4, 6, 4]
[2, 7, 7, 8, 7, 9, 7]
[3, 4, 4, 5, 4, 6, 4]
[3, 7, 7, 8, 7, 9, 7] .. which is not correct.
Just use the cartesian product from itertools
from itertools import product
arr = [[1,2,3], [4,5,6], [7,8,9]]
prod = product(*arr)
print(list(prod))

Need help filtering an array?

I am trying to remove odd numbers from an array.
arr = [1, 2, 3, 4, 5, 6, 7, 8, 10]
def remove_odd_nums(arr)
for x in arr
if x % 2 == 0
arr.delete(x)
end
end
end
print remove_odd_nums(arr)
# [1, 3, 5, 7, 10]
I can't seem to make this program work. The method works on the numbers except for the last one. What am I doing wrong?
You want to delete odd numbers but your program is deleting even numbers (x % 2 == 0 checks if x is an even number)
METHOD 1:
arr = [1, 2, 3, 4, 5, 6, 7, 8, 10]
arr.delete_if &:odd?
print arr
delete_if iterates by incrementing the index for arr, and deletes an element immediately after evaluating the block &:odd? with respect to the element. In other words, it is going through each element in array, and deleting the element if &:odd? is true.
&:odd?: a lambda function passing in an object to the odd? method, which returns true if the object is an odd number. Further explanations can be found what is the functionality of "&: " operator in ruby?
Note that method 1 actually MODIFIES the original array. For a way to create a new array of non-odd numbers, there is...
METHOD 2:
non_odds = arr.select{|i| not i.odd?}
TL;DR: don't modify an array while iterating it.
Let's see what's happening by printing the current value of x and arr inside the loop:
def remove_odd_nums(arr)
for x in arr
p x: x, arr: arr # <- debug output
if x % 2 == 0
arr.delete(x)
end
end
end
remove_odd_nums([1, 2, 3, 4, 5, 6, 7, 8, 10])
Output:
{:x=>1, :arr=>[1, 2, 3, 4, 5, 6, 7, 8, 10]}
{:x=>2, :arr=>[1, 2, 3, 4, 5, 6, 7, 8, 10]}
{:x=>4, :arr=>[1, 3, 4, 5, 6, 7, 8, 10]}
{:x=>6, :arr=>[1, 3, 5, 6, 7, 8, 10]}
{:x=>8, :arr=>[1, 3, 5, 7, 8, 10]}
The first two x values are as expected: 1 and 2. But then it moves on to 4, skipping 3. It also skips 5, 7, and 10. But why?
It's because you are modifying the array while iterating it. Think of the for loop as someone pointing to an element at a specific position. Initially it looks like this:
1 2 3 4 5 6 7 8 10 <- array
^ <- element
for then moves on to the next element:
1 2 3 4 5 6 7 8 10
^
at this point x % 2 == 0 becomes true and 2 is deleted from the array:
1 3 4 5 6 7 8 10
^
for isn't aware of this change and simply moves on to the next element:
1 3 4 5 6 7 8 10
^
which is why we have unintentionally skipped 3. The same happens for 5 and 7.
When for finally reaches 8:
1 3 5 7 8 10
^
it is being deleted:
1 3 5 7 10
^
and for stops looping because it seems to have reached the array's end.
Hello Practical1 just to clarify why do you want to destroy objects and array?
In case you on want to filter array and only select even numbers , you can try a combination of Array#select and Integer#even? method helpers
arr = arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# select all even numbers in an array
arr.select(&:even?) # shorthand for arr.select {|number| number.even? }
will return even numbers
[0] 2,
[1] 4,
[2] 6,
[3] 8,
[4] 10
source:
Array#select https://apidock.com/ruby/Array/select
Integer#even? https://ruby-doc.org/core-1.8.7/Integer.html
Ruby has fabulous methods to modify arrays in place based on the logic in a block.
To arrive at an array with only odd numbers, you can either remove the elements that don't meet a test or keep the number that do meet a test. You can either return a new array or use one of the in place modification methods.
To remove undesired values, use either .reject for a new array or .reject! to modify an existing array in place.
Since we are removing, we would use {|e| e%2!=0} inside the block for odd numbers:
> [1,2,3,4,5,6,7,8,9,10].reject {|e| e%2!=0}
=> [2, 4, 6, 8, 10] # new array
> arr = [1, 2, 3, 4, 5, 6, 7, 8, 10]
> arr.reject! {|e| e%2!=0}
=> [2, 4, 6, 8, 10] # arr modified in place
Rather than a block, you can also use the odd? logical test for the same result:
> [1,2,3,4,5,6,7,8,9,10].reject &:odd?
=> [2, 4, 6, 8, 10]
Or, you can keep the values desired and other values will not be kept. You would use {|e| e%2==0} inside the block for even values. Or you can use &:even? instead of the block.
You can use .keep_if to return a new array:
> arr
=> [1, 2, 3, 4, 5, 6, 7, 8, 10]
> [1,2,3,4,5,6,7,8,9,10].keep_if {|e| e%2==0}
=> [2, 4, 6, 8, 10] # new array.
Or use .select! to modify in place:
> arr = [1, 2, 3, 4, 5, 6, 7, 8, 10]
=> [1, 2, 3, 4, 5, 6, 7, 8, 10]
> arr.select! {|e| e%2==0}
=> [2, 4, 6, 8, 10]
> arr
=> [2, 4, 6, 8, 10] # arr modified in place

How to select the first increasing values from Ruby array without enumerating every value?

Imagine one has an array such as:
a = [0, 1, 2, 3, 4, 2, 5, 1, 7, 6, 4, 5]
And one wishes to create an array consisting of the first n elements, starting with the first element in the array, that are a monotonic sequence increasing by one. Given a above, that array would be [0, 1, 2, 3, 4].
One could use slice_when, such as:
a.slice_when { |a, b| a != b - 1 }.first
The drawback of this approach is that slice_when continues to iterate over the array elements 2, 5, 1, and so on, until the end. In this case, iterating over the remaining values is useless, since one really just wants the first slice.
What is the elegant way to express this in Ruby, that ceases iterating once the first increasing sequence is selected?
How about lazy evaluation?
a = [0, 1, 2, 3, 4, 2, 5, 1, 7, 6, 4, 5]
a.lazy.slice_when { |a, b| a != b - 1 }.first
=> [0, 1, 2, 3, 4]
Enumerable#lazy
You could write the following.
def stairstep(arr)
return [] if arr.empty?
enum = arr.first.step
arr.take_while { |x| x == enum.next }
end
stairstep [1, 2, 3, 4, 6, 5, 1, 7, 6, 4, 5]
#=> [1, 2, 3, 4]
Perhaps something like this:
a = [0, 1, 2, 3, 4, 2, 5, 1, 7, 6, 4, 5]
(a.size - 1).times { |i| break a[0..i] if a[i] > a[i + 1] }
#=> [0,1,2,3,4]

How to select a portion of a NumPy array efficiently?

I'm switching from Matlab/octve to Numpy/Scipy.
To select a segment of a Matlab array, it was quite easy.
e.g.
>> x = [1, 2, 3, 4; 5, 6, 7, 8; 9, 10, 11, 12]
x =
1 2 3 4
5 6 7 8
9 10 11 12
>> y = x(2:3, 1:2)
y =
5 6
9 10
How can the same thing be done with NumPy when
x = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
As Indexing > Other indexing options in the NumPy documentation mentions,
The slicing and striding works exactly the same way it does for lists and tuples except that they can be applied to multiple dimensions as well.
For your example, this means
import numpy as np
x = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
# array([[ 1, 2, 3, 4],
# [ 5, 6, 7, 8],
# [ 9, 10, 11, 12]])
x[1:3, 0:2]
# => array([[ 5, 6],
# [ 9, 10]])
Most notable difference to Matlab is probably that indexing is zero-based (i.e., first element has index 0) and that index ranges (called 'slices' in Python) are expressed with an exclusive upper bound: l[4:7] gets l[4], l[5] and l[6] (the 3rd to the 7th element), but not l[7] (the 8th element).
The Python tutorial's section on lists will give you a feeling for how indexing and slicing works for normal (1-dimensional) collections.

Resources