I have an ordered array which contain 1 to 1000000 elements.
I want to achieve an array such that the elements in the array are swapped with its next element.For instance if we assume the array elements are
[1,2,3,4,5,6]
I want to return an array with elements as
[2,1,4,3,6,5]
How do I achieve this in ruby for 100000 such elements? Can anyone guide me?
a = [1,2,3,4,5,6]
a.each_slice(2).map{|inner_a| inner_a.reverse}.flatten
# => [2, 1, 4, 3, 6, 5]
Description:
a.each_slice(2)returns an enumerator (#<Enumerator: [1, 2, 3, 4, 5, 6]:each_slice(2)>) with two element couples from your array. To see try a.each_slice(2).to_a. This returns [[1, 2], [3, 4], [5, 6]] with I only have to flatten for your expected result.
See also the first comment if you prefer a shorter notation of it.
Assuming you want to use a minimum amount of memory (since you chose a large array), and assuming the result is to be a mutated array (i.e. not a new array, but a change to the existing array) and finally assuming a is always an even number of elements...
a.each_index{|x| a[x], a[x+1] = a[x+1], a[x] if x.even?}
Possibly more performant...
(0...a.size).step(2) {|x| a[x], a[x+1] = a[x+1], a[x]}
You can try this.
arr = (1..100000).to_a
arr.each_with_index.each_slice(2){|(_,i), (_,j)| arr[i], arr[j] = arr[j], arr[i]}
Related
I am trying to print all the different sums of all combinations in this array [1,2,3]. I want to first push every sum result to a new array b, then print them using b.uniq so that non of the sum results are repeated.
However, with the code I have, the 3 repeats itself, and I think it is because of the way it is pushed into the array b.
Is there a better way of doing this?
a = [1,2,3]
b = []
b.push a
b.push a.combination(2).collect {|a,b| (a+b)}
b.push a.combination(3).collect {|a,b,c| (a+b+c)}
puts b.uniq
p b #[[1, 2, 3], [3, 4, 5], [6]]
Can someone please help me with this? I am still new in ruby.
Because an Array of arbitrary length can be summed using inject(:+), we can create a more general solution by iterating over the range 1..n, where n is the length of the Array.
(1..(a.size)).flat_map do |n|
a.combination(n).map { |c| c.inject(&:+) }
end.uniq
#=> [1, 2, 3, 4, 5, 6]
By using flat_map, we can avoid getting the nested Array result, and can call uniq directly on it. Another option to ensure uniqueness would be to pass the result to a Set, for which Ruby guarantees uniqueness internally.
require "set"
sums = (1..(a.size)).flat_map do |n|
a.combination(n).map { |c| c.inject(&:+) }
end
Set.new(sums)
#=> #<Set: {1, 2, 3, 4, 5, 6}>
This will work for an any Array, as long as all elements are Fixnum.
If all you want is an array of the possible sums, flatten the array before getting the unique values.
puts b.flatten.uniq
What is happening is uniq is running over a multi-dimensional array. This causes it to look for duplicate arrays in your array. You'll need the array to be flattened first.
Let's say that I have a multidimensional array with array's inside of it that each have two numbers. How do I iterate over the entire array and output the lowest number in each array? For example [[4, 6][8, 3]].My attempts at using .min, <=>, and if else statements have not worked.
Assuming you want to list 'all the mins from the arrays', there are lots of ways, here is a simple one:
array_of_arrays = [[4,6],[8,3]]
lowest_arrays = array_of_arrays.map {|a| a[0] < a[1] ? a[0] : a[1]}
or
lowest_arrays = array_of_arrays.map {|a| a.min}
This outputs [4, 3]
Should be as simple as:
[[4, 6],[8, 3]].each{|a| puts a.min}
or
[[4, 6],[8, 3]].map{|a| a.min}
... for an array output
Just use flatten followed by min like so:
[[4, 6], [8, 3]].flatten.min
=> 3
I have created several arrays, containing multiple integers. Now i want the integers to be sorted, lowest first. Say for instance, i have this in an array: 6,6,1,2,4,4, i want it to be sorted: 1,2,4,4,6,6. Also, is there anyway i can make ruby recognize the 4 lowest values, and display them somehow? I have tried to mess around with .show, but since im quite new to programming i'm rather confused by the results i receive.
did you try this?
a = [6,6,1,2,4,4]
p a.sort
#=> [1, 2, 4, 4, 6, 6]
sort will sort in ascending order.
if you need them sorted in descending order, use sort with a block:
p a.sort {|a,b| b <=> a}
#=> [6, 6, 4, 4, 2, 1]
UPDATE: not sure how i missed the part about lowest values ...
thank you #Mladen
a.sort.take(4)
#=> [1, 2, 4, 4]
This is the basic problem: I have an array of integers with possibly duplicate elements. I need to know the indices of each element, but when I sort the array, whenever I select an element from the new array, I want to be able to reference the same element from the original array.
I am looking for a solution to the problem, or maybe a solution to the approach I am taking.
Here is an array
a = [1, 2, 3, 4, 3, 5, 2]
There are two 2's and two 3's, but if I'm working with the first 2 (from the left), I want to work with index 1, and if I'm working with the second 2, I want to be working with index 6. So I use a helper array to allow me to do this:
helper = [0, 1, 2, 3, 4, 5, 6]
Which I will iterate over and use to access each element from a.
I could have accomplished this with each_with_index, but the problem begins when I sort the array.
Now I have a sort order
sort_order = [2, 4, 1, 5, 3]
I use sort_by to sort a according to sort_order, to produce
sorted_a = [2, 2, 4, 1, 5, 3, 3]
You may assume all elements in the input exist in sort_order to avoid sort_by exceptions.
Now the problem is that my helper array should be updated to match the new positions. Each element should be sorted the same way as a was sorted, because it is unclear whether the first 2 in the new array was at index 1 or at index 6 of the original array.
So my new helper array might look like
new_helper = [1, 6, 3, 0, 5, 2, 4]
So if I were to go with this approach, how would I produce the new_helper array, given the original array and the sort order?
Maybe there is a better way to do this?
I would suggest first zip the original array with the helper array, sort the zipped array according the component coming from the original array, then unzip them (this method does not exist unfortunately, but you can do transpose). Or you can implement your own sorting logic as pointed out by Hunter.
Make a list of pairs of the original data and that data's index. Like this:
a = [(1, 0), (2, 1), (3, 2), (4, 3), (3, 4), (5, 5), (2,6)]
Sort that list (lexicographically, or just ignore the second part of the pair except to carry it along). The second item in every pair tells you where the element was in the original array.
You need to swap the values in the helper array when you swap then in your main array.
loop do
swapped = false
0.upto(list.size-2) do |i|
if list[i] > list[i+1]
list[i], list[i+1] = list[i+1], list[i] # swap values
helper[i], helper[i+1] = helper[i+1], helper[i]; #swap helper values
swapped = true
end
end
break unless swapped
end
Example
irb(main):001:0> def parallel_sort(list, helper)
irb(main):002:1> loop do
irb(main):003:2* swapped = false
irb(main):004:2> 0.upto(list.size-2) do |i|
irb(main):005:3* if list[i] > list[i+1]
irb(main):006:4> list[i], list[i+1] = list[i+1], list[i] # swap values
irb(main):007:4> helper[i], helper[i+1] = helper[i+1], helper[i]; #swap helper values
irb(main):008:4* swapped = true
irb(main):009:4> end
irb(main):010:3> end
irb(main):011:2> break unless swapped
irb(main):012:2> end
irb(main):013:1> return [list, helper]
irb(main):014:1> end
=> nil
irb(main):015:0> a = [3,2,1]
=> [3, 2, 1]
irb(main):016:0> b = ["three","two","one"]
=> ["three", "two", "one"]
irb(main):017:0> parallel_sort(a,b)
=> [[1, 2, 3], ["one", "two", "three"]]
irb(main):018:0>
Sorting inside a loop is rarely a good idea.... If you are doing so, you might be better off with a treap (fast on average but infrequently an operation will take a while) or red-black tree (relatively slow, but gives pretty consistent operation times). These are rather like hash tables, except they're not as fast, and they keep elements stored in order using trees.
Either way, why not use a class that saves both the value to sort by, and the helper value? Then they're always together, and you don't need a custom sorting algorithm.
Since you have sort_order, your array is already kind of sorted, so we should use this fact as an advantage. I came up with this simple solution:
a = [1, 2, 3, 4, 3, 5, 2]
sort_order = [2, 4, 1, 5, 3]
# Save indices
indices = Hash.new { |hash, key| hash[key] = [] }
a.each_with_index { |elem, index| indices[elem] << index }
# Sort the array by placing elements into "right" positions
sorted = []
helper = []
sort_order.each do |elem|
indices[elem].each do |index|
sorted << elem
helper << index
end
end
p sorted
p helper
The algorithm is based on idea of Counting sort, I slightly modified it to save indices.
I've got a sorted array:
array = [[4, 13], [1, 12], [3, 8], [2, 8], [0, 3]]
Which shows me a position (array[n][0]) and the number of occurrences of that position (array[n][1]).
I need to test to see if more than one item in the array has the same number of occurrences as the last item.
I thought I might be able to do it with this:
array.detect {|i| i[1] == array.last[1] }.length
But it returns 2 for the above array, and seems to also return 2 for the following array:
array = [[4, 13], [1, 12], [3, 8], [2, 3], [0, 3]]
When I run it without length it always returns the first occurrence.
Is there a way to get this to count the occurrences?
EDIT:
Sorry, will ask my follow up question in a new question.
Try using find_all instead of detect. detect returns the first match. In your first example, that's array[3], which is another array of length 2. That's why it's returning 2 (it should always be returning 2 or nil for your arrays). find_all will return an array of the matches (instead of the first match itself), and its length will be the value you want.
Here's a clearer way of doing what you want, with none of the associated worries.
array.count{|i| i[1] == array.last[1]}