Check if array of integers increments in Ruby
Try this:
def array_increments_by?(step, array)
sorted = array.sort
lastNum = sorted[0]
sorted[1, sorted.count].each do |n|
if lastNum + step != n
return false
end
lastNum = n
end
true
end
Usage:
array_increments?(1, [0,1,2,3]) #=> true
array_increments?(2, [0,2,4,6]) #=> true
array_increments?(2, [0,2,4,8]) #=> false
Rails, evaluate if numbers are in sequence
You can combine a couple methods in Ruby to do this pretty efficiently.
input.each_cons(2).reduce(true) { |result, (a, b)| result && (a <=> b) < 0 }
each_cons
will iterate through your array yielding, in this case, each 2 consecutive items. Because we don't pass it a block, it returns an enumerator that we can iterate through and get a single resulting value using reduce
(a.k.a. inject
).
Our block compares a
and b
using <=>
which will return -1, 0, or 1 depending on whether the first value is "less-than", equal, or "greater than". In this case, we want to make sure a
is -1
.
In case you're not familiar with it, the parenthesis in the block argument are Ruby 1.9+, and they allow the arguments to be splatted in (otherwise we would get a 2-item array in our block).
Counting integers in array from 1 to 100 in increments of 10
counts = 10.times.map { |i| (i + 1)...(i + 11) }.map { |range|
a.count { |x| range.include? x }
}
counts[0]
# => 17 (number of numbers in 1...11)
counts[1]
# => 20 (number of numbers in 11...21)
counts[2]
# => 22 (number of numbers in 21...31)
# ...
EDIT: Or even easier, by exploiting a simple mathematical property:
counts = a.group_by { |x| (x - 1) / 10 }.map { |k, v| v.count }
Hopefully each 10 (1-10, 11-20, etc) has a different variable that I can call later on.
Why would you want different variables when you can have an array?
EDIT2: Whole program, in 1-4 lines:
array = 200.times.map { rand(1..100) }.sort
array.group_by { |x| (x - 1) / 10 }.each do |k, v|
puts "%2d-%2d %s" % [k * 10 + 1, k * 10 + 10, "#" * v.count]
end
Translation: Do two hundred iterations, and construct an array, such that each element is a random number between 1 and 100. Then group the array by the result of division by 10 (adjusting by 1 so we don't get ranges of 0-9, 10-19...); iterating on the hash containing the division result and items, print the bounds (reconstructing the start and the end from the division result) and also a number of hashes corresponding to the number of items in each group.
EDIT3: As Stefan notes, we can use chunk
because the array is sorted, for a bit of a speedup. group_by
above doesn't care about the array being sorted. You can simply replace group_by
with chunk
even though they return different types, simply because iterating on hashes works the same way as iterating on array of two-element arrays.
array = 200.times.map { rand(1..100) }.sort
array.chunk { |x| (x - 1) / 10 }.each do |k, v|
puts "%2d-%2d %s" % [k * 10 + 1, k * 10 + 10, "#" * v.count]
end
incremental array in ruby, 0..40, [10, 20, 30, 40]
Use the step
method for this:
10.step(40,10)
The first argument is the number you want to count up to, with the second argument being the "steps" that you take to get there.
Ruby - Append increment number to duplicate filed in array of objects
the input data can be huge, is there any way to mutate the same object and find only duplicate to reduce the latency and memory
Something like this would work:
input
.group_by { |item| item[:name] }
.reject { |_name, entries| entries.count == 1 }
.each do |_name, entries|
entries.each.with_index(1) do |entry, index|
entry[:name] << "-#{index}"
end
end
It groups the items by their :name
key and rejects those with only 1 entry. It then traverses the remaining groups (i.e. with 2 or more entries) and appends the 1-bases index to each entry's name.
Afterwards, input
will be:
[{:id=>1, :name=>"john-1"},
{:id=>2, :name=>"Man-1"},
{:id=>3, :name=>"Man-2"},
{:id=>4, :name=>"john-2"},
{:id=>5, :name=>"kind-1"},
{:id=>6, :name=>"nova"},
{:id=>7, :name=>"kind-2"},
{:id=>8, :name=>"fred-1"},
{:id=>9, :name=>"fred-2"},
{:id=>10, :name=>"john-3"}]
Mapping array values to hash with incrementing key name
It's not too hard to do this using the each_with_index
method which is zero-indexed by default:
Hash[colors.each_with_index.map { |c, i| [ 'color%d' % i, c ] }]
You were close with map
, you just needed to expand it into value/index pairs.
How to populate an array with incrementally increasing values Ruby
(1..num).to_a
is all you need to do in Ruby.
1..num
will create a Range
object with start at 1
and end at whatever value num
is. Range
objects have to_a
method to blow them up into real Arrays
by enumerating each element within the range.
For most purposes, you won't actually need the Array
- Range
will work fine. That includes iteration (which is what I assume you want, given the problem you're working on).
That said, knowing how to create such an Array
"by hand" is valuable learning experience, so you might want to keep working on it a bit. Hint: you want to start with an empty array ([]
) instead with Array.new num
, then iterate something num.times
, and add numbers into the Array
. If you already start with an Array
of size num
, and then push num
elements into it, you'll end up with twice num
elements. If, as is your case, you're adding elements while you're iterating the array, the loop never exits, because for each element you process, you add another one. It's like chasing a metal ball with the repulsing side of a magnet.
Generated integer array based on number in rails
See Ruby: How to iterate over a range, but in set increments?
So in your case it would be:
(min..max).step(10) do |n|
n += 'buttoncode'
end
By the way, this is not really Rails specific, but Ruby specific. Rails is a web framework that handles the interaction between browser and the web server that is built on top of Ruby.
If you feel like you aren't that up to speed with Ruby, try https://learnrubythehardway.org/book/ and do some exercise on HackerRank or ProjectEuler in Ruby.
Related Topics
How to Programmatically Check If a Certificate Has Been Revoked
Ruby -V Dyld: Library Not Loaded: /Usr/Local/Lib/Libgmp.10.Dylib
How to Put a Delay on a Loop in Ruby
Ruby Refuses to Divide Correctly
Many: 'Require': Cannot Load Such File -- "Gem_Name" (Loaderror) After Upgrade of Ruby/Rails
Error Installing Ruby 2.6.7 on MAC Os - How to Resolve
Require': Cannot Load Such File -- Spec_Helper (Loaderror)
Open-Uri Returning Ascii-8Bit from Webpage Encoded in Iso-8859
Ruby Variable as Same Object (Pointers)
How to Convert Activerecord Table Name to Model Class Name
How to Make Xcode Use the Correct Version of Ruby When Running a Script
Telling Bundler to Exclude Certain Gems from a Particular Gem's Installation
Get, or Calculate the Entropy of an Image with Ruby and Imagemagick