ruby/rails array all elements between two indices - ruby-on-rails

I have an array like this: [7, 8, 9, 10, 11, 12, 1, 2, 3, 4, 5, 6]
What's the simplest way to return each item in the array from position 6 until 0 where the resulting array looks like: [1,2,3,4,5,6,7]
This positions in the array can be dynamic, for example passing in 4 and 9 should return [11,12,1,2,3,4]
I'm wondering if there's a method that accomplishes this in Rails api.
Thanks in advance
EDIT
Let's assume that no negative numbers, so doing array[2..-2] wont work.
Array#splice almost works for this, but if the second position is less than the first, it returns nil.

def foo a, min, max
a.rotate(min).first((max - min) % a.length + 1)
end
a = [7, 8, 9, 10, 11, 12, 1, 2, 3, 4, 5, 6]
foo(a, 6, 0) # => [1, 2, 3, 4, 5, 6, 7]
foo(a, 4, 9) # => [11, 12, 1, 2, 3, 4]

class Array
def get_sub_array(start,last)
(start > last) ? (self[start..-1] + self[0..last]) : self[start..last]
end
end
Then
a = [7, 8, 9, 10, 11, 12, 1, 2, 3, 4, 5, 6]
a.get_sub_array(6,0)
#[1, 2, 3, 4, 5, 6, 7]
Or if you don't want to monkey patch
You could have a method like
def get_sub_array(array, start,last)
(start > last) ? (array[start..-1] + array[0..last]) : array[start..last]
end
a = [7, 8, 9, 10, 11, 12, 1, 2, 3, 4, 5, 6]
get_sub_array(a,6,0)
#[1, 2, 3, 4, 5, 6, 7]

def some_function(some_array,start_val=6, end_val=0)
if end_val > start_val
some_array[start_val,(end_val - start_val)]
else
(some_array[start_val, some_array.size] << some_array[0, (end_val)]).flatten
end
end
You can use ternary operator to make it one liner too:
def some_function(some_array,start_val=6, end_val=0)
end_val > start_val ? some_array[start_val,(end_val - start_val)] : (some_array[start_val, some_array.size] << some_array[0, (end_val)]).flatten
end
a = [7, 8, 9, 10, 11, 12, 1, 2, 3, 4, 5, 6]
some_function(a) # => [1, 2, 3, 4, 5, 6, 7]
some_function(a, 4, 9) # => [11, 12, 1, 2, 3, 4]

min=6
max=0
arr = [7, 8, 9, 10, 11, 12, 1, 2, 3, 4, 5, 6]
result = []
if max<min
result << arr[min..arr.length]
result << arr[0..max]
else
result << arr[min..max]
end

A couple more ways (my preference being for #1).
a = [7, 8, 9, 10, 11, 12, 1, 2, 3, 4, 5, 6]
#1
def foo a, min, max
as = a.size
max += as if max < min
(min..max).map { |i| a[i%as] }
end
foo(a, 6, 0) # => [ 1, 2, 3, 4, 5, 6, 7]
foo(a, 4, 9) # => [11, 12, 1, 2, 3, 4]
#2
def foo a, min, max
max += a.size if max < min
e = a.cycle
min.times { e.next }
(max-min+1).times.map { e.next }
end
foo(a, 6, 0) # => [ 1, 2, 3, 4, 5, 6, 7]
foo(a, 4, 9) # => [11, 12, 1, 2, 3, 4]

def foo a, s, e
a = e < s ? (a[s,a.size] << a[0..e]).flatten : a[s..e]
end
a = [7, 8, 9, 10, 11, 12, 1, 2, 3, 4, 5, 6]
a = foo(a, 6, 0) # => [1, 2, 3, 4, 5, 6, 7]
a = foo(a, 4, 9) # => [11, 12, 1, 2, 3, 4]

myArray = [7, 8, 9, 10, 11, 12, 1, 2, 3, 4, 5, 6]
myArray[6..-1] returns [1, 2, 3, 4, 5, 6]
myArray[4..9] returns [11,12,1,2,3,4]

Related

dart generating all possible combinations list of lists

I have a list of lists, similar to this:
a = [ [1,2,3], [4,5,6], [7,8,9,10]]
I'd like to create all possible combinations, like this:
[(1, 4, 7), (1, 4, 8), (1, 4, 9), (1, 4, 10), (1, 5, 7), (1, 5, 8), (1, 5, 9), (1, 5, 10), (1, 6, 7), (1, 6, 8), (1, 6, 9), (1, 6, 10), (2, 4, 7), (2, 4, 8), (2, 4, 9), (2, 4, 10), (2, 5, 7), (2, 5, 8), (2, 5, 9), (2, 5, 10), (2, 6, 7), (2, 6, 8), (2, 6, 9), (2, 6, 10), (3, 4, 7), (3, 4, 8), (3, 4, 9), (3, 4, 10), (3, 5, 7), (3, 5, 8), (3, 5, 9), (3, 5, 10), (3, 6, 7), (3, 6, 8), (3, 6, 9), (3, 6, 10)]
For python, there's a library that does exactly this.
Is there a similar solution for Dart?
If not, I'd appreciate a simple code that accomplish that
One approach could be:
Iterable<List<T>> allCombinations<T>(List<List<T>> sources) sync* {
if (sources.isEmpty || sources.any((l) => l.isEmpty)) {
yield [];
return;
}
var indices = List<int>.filled(sources.length, 0);
var next = 0;
while (true) {
yield [for (var i = 0; i < indices.length; i++) sources[i][indices[i]]];
while (true) {
var nextIndex = indices[next] + 1;
if (nextIndex < sources[next].length) {
indices[next] = nextIndex;
break;
}
next += 1;
if (next == sources.length) return;
}
indices.fillRange(0, next, 0);
next = 0;
}
}
This works by effectively treating the indices as a number in variable base based on the source list lengths, then incrementing it and creating the corresponding list.
Time complexity is still 𝒪(Πi(source[i].length) * source.length).
Could not find a package which does exactly what you want, but I guess your can do something like this if you want to introduce your own method:
void main() {
print(combinations([
[1, 2, 3],
[4, 5, 6],
[7, 8, 9, 10]
]));
// ([1, 4, 7], [1, 4, 8], [1, 4, 9], [1, 4, 10], ..., [3, 6, 9], [3, 6, 10])
}
Iterable<List<T>> combinations<T>(
List<List<T>> lists, [
int index = 0,
List<T>? prefix,
]) sync* {
prefix ??= <T>[];
if (lists.length == index) {
yield prefix.toList();
} else {
for (final value in lists[index]) {
yield* combinations(lists, index + 1, prefix..add(value));
prefix.removeLast();
}
}
}
More efficient solution but also more risky to use since it does require the user of combinations to take care when consuming the output and make sure not to keep any instances of the inner Iterable:
void main() {
print(combinations([
[1, 2, 3],
[4, 5, 6],
[7, 8, 9, 10]
]).map((e) => e.toList()));
// ([1, 4, 7], [1, 4, 8], [1, 4, 9], [1, 4, 10], ..., [3, 6, 9], [3, 6, 10])
}
Iterable<Iterable<T>> combinations<T>(
List<List<T>> lists, [
int index = 0,
List<T>? prefix,
]) sync* {
prefix ??= <T>[];
if (lists.length == index) {
yield prefix;
} else {
for (final value in lists[index]) {
yield* combinations(lists, index + 1, prefix..add(value));
prefix.removeLast();
}
}
}
The problem with this solution is the risk of misuse as the following example:
final listOfCombinations = combinations([
[1, 2, 3],
[4, 5, 6],
[7, 8, 9, 10]
]).toList();
print(listOfCombinations);
// [[], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], []]
Which should instead be:
final listOfCombinations = combinations([
[1, 2, 3],
[4, 5, 6],
[7, 8, 9, 10]
]).map((e) => e.toList()).toList();
print(listOfCombinations);
// [[1, 4, 7], [1, 4, 8], [1, 4, 9], [1, 4, 10], [1, 5, 7], [1, 5, 8], [1, 5, 9], [1, 5, 10], [1, 6, 7], [1, 6, 8], [1, 6, 9], [1, 6, 10], [2, 4, 7], [2, 4, 8], [2, 4, 9], [2, 4, 10], [2, 5, 7], [2, 5, 8], [2, 5, 9], [2, 5, 10], [2, 6, 7], [2, 6, 8], [2, 6, 9], [2, 6, 10], [3, 4, 7], [3, 4, 8], [3, 4, 9], [3, 4, 10], [3, 5, 7], [3, 5, 8], [3, 5, 9], [3, 5, 10], [3, 6, 7], [3, 6, 8], [3, 6, 9], [3, 6, 10]]
So, use the first suggested solution if you don't want the risk of this kind of issues. :)
check out this answer. working for the problem you are searching for:
https://stackoverflow.com/a/57883482/11789758

Rails: random unique array of fixed length

How can I ensure uniqueness in this array while maintaining its length at 5?
def fixed
5.times.collect { SecureRandom.random_number(10) }
end
This behaviour seems odd:
5.times.collect.uniq { SecureRandom.random_number(10) }
# => [0, 2, 3, 4]
5.times.collect.uniq { SecureRandom.random_number(10) }
# => [0, 1, 3]
5.times.collect.uniq { SecureRandom.random_number(10) }
# => [0, 1, 2, 3, 4]
5.times.collect.uniq { SecureRandom.random_number(10) }
# => [0, 1, 2, 4]
5.times.collect.uniq { SecureRandom.random_number(10) }
# => [0, 1, 2, 3]
When the number of possible values is small – like 10 in your example – then I would generate an array with all options and just pick a random sample of entries:
(0..9).to_a.sample(5)
If the number of possible values is huge then generation all values first is certainly not an option. Then I would generate a random value as long as the array doesn't contain enough entries:
require 'set'
values = Set.new
until values.length == 5 do
values.add(SecureRandom.random_number(1_000_000))
end
values.to_a
Note the I am using a Set to ensure the uniqueness of the values in the second version.
Using SecureRandom
def fixed
unique_numbers = []
5.times.collect do
loop do
number = SecureRandom.random_number(10)
break number unless unique_numbers.include?(number)
end
end
end
And if you want to generate unique numbers between 1 to 10, then you can create array of 1 to 10 and use shuffle or sample to get random numbers.
Using shuffle
> (0...10).to_a.shuffle.take(5)
=> [4, 0, 1, 3, 7]
> (0...10).to_a.shuffle.take(5)
=> [6, 2, 3, 9, 1]
> (0...10).to_a.shuffle.take(5)
=> [9, 2, 5, 8, 4]
> (0...10).to_a.shuffle.take(5)
=> [5, 0, 6, 8, 7]
> (0...10).to_a.shuffle.take(5)
=> [2, 7, 1, 5, 0]
Using sample
> (1..10).to_a.sample(5)
=> [4, 6, 3, 2, 7]
> (1..10).to_a.sample(5)
=> [5, 8, 2, 3, 7]
> (1..10).to_a.sample(5)
=> [2, 5, 6, 1, 3]
> (1..10).to_a.sample(5)
=> [8, 5, 10, 9, 3]
> (1..10).to_a.sample(5)
=> [8, 1, 5, 3, 4]
You can also pass SecureRandom custom random generator as an argument with sample
> (1..10).to_a.sample(5, random: SecureRandom)
=> [6, 3, 4, 7, 10]
> (1..10).to_a.sample(5, random: SecureRandom)
=> [7, 4, 8, 1, 5]
> (1..10).to_a.sample(5, random: SecureRandom)
=> [8, 3, 9, 5, 10]
> (1..10).to_a.sample(5, random: SecureRandom)
=> [6, 8, 9, 2, 1]
> (1..10).to_a.sample(5, random: SecureRandom)
=> [9, 10, 1, 8, 2]
Just out of curiosity, using Enumerable#cycle infinite generator.
MAX = 10
SIZE = 5
[MAX].cycle.inject(Set.new) do |acc, max|
break acc if acc.size >= SIZE
acc << SecureRandom.random_number(max)
end
#⇒ #<Set: {2, 1, 7, 0, 9}>
or even with generic loop:
loop.each_with_object(Set.new) do |_, acc|
break acc if acc.size >= SIZE
acc << SecureRandom.random_number(10)
end
#⇒ #<Set: {2, 6, 7, 1, 3}>
One way would be to generate a range of numbers from 0 to 10 and
then shuffle them to get the unique random numbers.
You can convert that range to Array using to_a and shuffle them using shuffle
You can do something like this:
(0..10).to_a.shuffle[0..4] # => [8, 6, 1, 9, 10]
[0..4] will give you the first 5 shuffled elements.

Kaminari not respecting .per() setting

#items = #cats + #dogs + #birds
#pag_items = Kaminari.paginate_array(#items).page(params[:page]).per(9)
puts #pag_items.count
6
The #items array has 23 items.
Why is the #pag_items array only holding 6 items?
If i set it to 5, or 4 it will hold that many. But more than 6 it won't.
Thanks!
You probably has max_per_page setting enabled:
Kaminari.configure { |s| s.max_per_page = 6 }
#items = (1..23).to_a
# => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]
#pag_items = Kaminari.paginate_array(#items).page(1).per(9)
# => [1, 2, 3, 4, 5, 6]

Ruby array to subarray with fall factor

Is there any inbuilt method available to split large array into smaller chunks with dynamic fall factor?
Eg: i=0
src_arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
if batch_size = 5 and fall_factor = 1, first chunk should be [1, 2, 3, 4, 5] and subsequent array chunks should start from start_index = i * (batch_size - fall_factor). ie, start_index will be 0, 4, 8, 12, and
result: [1, 2, 3, 4, 5]
[5, 6, 7, 8, 9]
[9, 10, 11, 12, 13]
[13, 14]
if fall_factor = 2 result should be as below
[1, 2, 3, 4, 5]
[4, 5, 6, 7, 8]
[7, 8, 9, 10, 11]
[10, 11, 12, 13, 14]
I know how to SOLVE this. My question is if any inbuilt method available like each_slice to get this done instead of reinventing.
For example you can use just #step method of Numeric
0.step(src_arr.size - fall_factor - 1, batch_size - fall_factor).map do |ind|
src_arr[ind, batch_size]
end
# fall_factor = 1
# => [[1, 2, 3, 4, 5], [5, 6, 7, 8, 9], [9, 10, 11, 12, 13], [13, 14]]
# fall_factor = 2
# => [[1, 2, 3, 4, 5], [4, 5, 6, 7, 8], [7, 8, 9, 10, 11], [10, 11, 12, 13, 14]]
Code
def doit(arr, batch_size, fall_factor)
arr[batch_size..-1].
each_slice(batch_size-fall_factor).
each_with_object([arr[0,batch_size]]) { |b,c| c << [*c.last[-fall_factor..-1], *b] }
end
Examples
arr = (1..14).to_a
#=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
doit(arr, 5, 1)
#=> [[1, 2, 3, 4, 5], [5, 6, 7, 8, 9], [9, 10, 11, 12, 13], [13, 14]]
doit(arr, 5, 2)
#=> [[1, 2, 3, 4, 5], [4, 5, 6, 7, 8], [7, 8, 9, 10, 11], [10, 11, 12, 13, 14]]
doit(arr, 5, 3)
#=> [[1, 2, 3, 4, 5], [3, 4, 5, 6, 7], [5, 6, 7, 8, 9], [7, 8, 9, 10, 11],
# [9, 10, 11, 12, 13], [11, 12, 13, 14]]
doit(arr, 5, 4)
#=> [[1, 2, 3, 4, 5], [2, 3, 4, 5, 6], [3, 4, 5, 6, 7], [4, 5, 6, 7, 8],
# [5, 6, 7, 8, 9], [6, 7, 8, 9, 10], [7, 8, 9, 10, 11], [8, 9, 10, 11, 12],
# [9, 10, 11, 12, 13], [10, 11, 12, 13, 14]]
Explanation
For arr above and:
batch_size = 5
fall_factor = 2
we have:
a = arr[batch_size..-1]
#=> arr[5..-1]
#=> [6, 7, 8, 9, 10, 11, 12, 13, 14]
b = a.each_slice(batch_size-fall_factor)
#=> a.each_slice(3)
#=> #<Enumerator: [6, 7, 8, 9, 10, 11, 12, 13, 14]:each_slice(3)>
We can see the elements of the enumerator b by converting it to an array:
b.to_a
#=> [[6, 7, 8], [9, 10, 11], [12, 13, 14]]
Continuing:
d = [arr[0,batch_size]]
#=> [[1, 2, 3, 4, 5]]
b.each_with_object(d) { |b,c| c << [*c.last[-fall_factor..-1], *b] }
#=> [[1, 2, 3, 4, 5], [4, 5, 6, 7, 8], [7, 8, 9, 10, 11], [10, 11, 12, 13, 14]]
To see how the last calculation is performed, let:
e = b.each_with_object(d)
#=> #<Enumerator: #<Enumerator: [6, 7, 8, 9, 10, 11, 12, 13, 14]:
# each_slice(3)>:each_with_object([[1, 2, 3, 4, 5]])>
e.to_a
#=> [[[6, 7, 8], [[1, 2, 3, 4, 5]]],
# [[9, 10, 11], [[1, 2, 3, 4, 5]]],
# [[12, 13, 14], [[1, 2, 3, 4, 5]]]]
We can use Enumerator#next to obtain each element of e that is passed to the block, set the block variables to each of those values and perform the block calculation. The first element is passed to the block:
b, c = e.next
#=> [[6, 7, 8], [[1, 2, 3, 4, 5]]]
b #=> [6, 7, 8]
c #=> [[1, 2, 3, 4, 5]]
The block calculation is therefore:
c << [*c.last[-fall_factor..-1], *b]
#=> c << [*[[1, 2, 3, 4, 5]].last[-2..-1], *[6, 7, 8]]
# c << [*[1, 2, 3, 4, 5][-2..-1], *[6, 7, 8]]
# c << [*[4, 5], *[6, 7, 8]]
# c << [4, 5, 6, 7, 8]
c #=> [[1, 2, 3, 4, 5], [4, 5, 6, 7, 8]]
The next element of e is now passed to the block:
b, c = e.next
#=> [[9, 10, 11], [[1, 2, 3, 4, 5], [4, 5, 6, 7, 8]]]
b #=> [9, 10, 11]
c #=> [[1, 2, 3, 4, 5], [4, 5, 6, 7, 8]]
The remaining calculations are performed similarly.
Based on logic shared by you, below is one possible implementation:
b = 5 # batch size
f = 2 # fall factor
indices = (0...src_arr.size).collect {|i| i * (b-f)}.reject {|i| i + f >= src_arr.size}
result = indices.each_with_object([]) do |i, obj|
obj << src_arr[i, b]
end
p result
#=> [[1, 2, 3, 4, 5], [4, 5, 6, 7, 8], [7, 8, 9, 10, 11], [10, 11, 12, 13, 14]]

ruby array (enumerable) method to select and reject into 2 arrays in 1 operation

# this code works
list = (0..20).to_a
# => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
odd = list.select { |x| x.odd? }
# => [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
list.reject! { |x| x.odd? }
# => [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
# but can i emulate this type of functionality with an enumerable method?
set = [1,5,10]
# => [1, 5, 10]
one, five, ten = set
# => [1, 5, 10]
one
# => 1
five
# => 5
ten
# => 10
# ------------------------------------------------
# method I am looking for ?
list = (0..20).to_a
odd, even = list.select_with_reject { |x| x.odd? }
# put the matching items into the first variable
# and the non-matching into the second
Sure, you can do:
odd, even = list.partition &:odd?
odd = []
even = []
list = [1..20]
list.each {|x| x.odd? ? odd << x : even << x }
As pguardiario said, the partition method is the most direct way. You could also use Set#divide:
require 'set'
list = (1..10).to_a
odd, even = Set.new(list).divide(&:odd?).to_a.map{|x| x.to_a}
You could try below:
odd,even = (0..20).group_by(&:odd?).values
p odd,even
Output:
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]

Resources