Menu
  • HOME
  • TAGS

Split an array into slices, with groupings

Tag: arrays,ruby,enumerable

I've got some Ruby code here, that works, but I'm certain I'm not doing it as efficiently as I can.

I have an Array of Objects, along this line:

[
    { name: "foo1", location: "new york" },
    { name: "foo2", location: "new york" },
    { name: "foo3", location: "new york" },
    { name: "bar1", location: "new york" },
    { name: "bar2", location: "new york" },
    { name: "bar3", location: "new york" },
    { name: "baz1", location: "chicago" },
    { name: "baz2", location: "chicago" },
    { name: "baz3", location: "chicago" },
    { name: "quux1", location: "chicago" },
    { name: "quux2", location: "chicago" },
    { name: "quux3", location: "chicago" }
]

I want to create some number of groups - say 3 - where each group contains a semi-equal amount of items, but interspersed by location.

I tried something like this:

group_size = 3
groups = []

group_size.times do
    groups.push([])
end

i = 0
objects.each do |object|
    groups[i].push(object)
    if i < (group_size - 1)
        i += 1
    else
        i = 0
    end
end

This returns a groups object, that looks like:

[
    [{:name=>"foo1", :location=>"new york"},
     {:name=>"bar1", :location=>"new york"},
     {:name=>"baz1", :location=>"chicago"},
     {:name=>"quux1", :location=>"chicago"}],
    [{:name=>"foo2", :location=>"new york"},
     {:name=>"bar2", :location=>"new york"},
     {:name=>"baz2", :location=>"chicago"},
     {:name=>"quux2", :location=>"chicago"}],
    [{:name=>"foo3", :location=>"new york"},
     {:name=>"bar3", :location=>"new york"},
     {:name=>"baz3", :location=>"chicago"},
     {:name=>"quux3", :location=>"chicago"}]
]

So you can see there's a couple of objects from each location in each grouping.

I played around with each_slice() and group_by(), even tried to use inject([]) - but I couldn't figure out a more elegant method to do this.

I'm hoping it's something that I'm overlooking - and I need to account for more locations and a non-even number of Objects.

Best How To :

Yes, this bookkeeping with i is usually a sign there should be something better. I came up with:

ar =[
    { name: "foo1", location: "new york" },
    { name: "foo2", location: "new york" },
    { name: "foo3", location: "new york" },
    { name: "bar1", location: "new york" },
    { name: "bar2", location: "new york" },
    { name: "bar3", location: "new york" },
    { name: "baz1", location: "chicago" },
    { name: "baz2", location: "chicago" },
    { name: "baz3", location: "chicago" },
    { name: "quux1", location: "chicago" },
    { name: "quux2", location: "chicago" },
    { name: "quux3", location: "chicago" }
]

# next line handles unsorted arrays, irrelevant with this data 
ar = ar.sort_by{|h| h[:location]}

num_groups = 3
groups     = Array.new(num_groups){[]}
wheel      = groups.cycle
ar.each{|h| wheel.next << h}

# done.
p groups
# => [[{:name=>"baz1", :location=>"chicago"}, {:name=>"quux1", :location=>"chicago"}, {:name=>"foo1", :location=>"new york"}, ...]

because I like the cycle method.

Comparing arrays with numbers in vb.net

arrays,vb.net

There are a few basic ways of checking for a value in an integer array. The first is to manually search by looping through each value in the array, which may be what you want if you need to do complicated comparisons. Second is the .Contains() method. It is simpler...

Translating a character array into a integer string in C++

c++,arrays,string

If you want a sequence of int, then use a vector<int>. Using the key_char string, the values of the chars in it will serve as the initial value of the ints. std::vector<int> key_num(key_char.begin(), key_char.end()); Then, iterate over each character of key_num and convert it to the equivalent int value for...

How to pivot array into another array in Ruby

arrays,ruby,csv

Here is a way using an intermediate hash-of-hash The h ends up looking like this {"Alaska"=>{"Rain"=>"3", "Snow"=>"4"}, "Alabama"=>{"Snow"=>"2", "Hail"=>"1"}} myArray = [["Alaska","Rain","3"],["Alaska","Snow","4"],["Alabama","Snow","2"],["Alabama","Hail","1"]] myFields = ["Snow","Rain","Hail"] h = Hash.new{|h, k| h[k] = {}} myArray.each{|i, j, k| h[i][j] = k } p [["State"] + myFields] + h.map{|k, v| [k] + v.values_at(*myFields)} output...

Get the actual value of a boolean attribute

ruby,page-object-gem,rspec3,rspec-expectations

The Page-Object gem's attribute method does not do any formatting of the attribute value. It simply returns what is returned from Selenium-WebDriver (or Watir-Webdriver). In the case of boolean attributes, this means that true or false will be returned. From the Selenium-WebDriver#attribute documentation: The following are deemed to be “boolean”...

accessing range of values in arduino array

arrays,arduino

Arrays in C++ don't allow this syntax. What you should do is something like this: char[2] id; if( sx1272.packet_received.length > 5 ) { id[0] = sx1272.packet_received.data[4]; id[1] = sx1272.packet_received.data[5]; } ...

Zipping two arrays together with index in Scala?

arrays,scala,zip

Simply do: array1.zip(array2).zipWithIndex.map { case ((a, b), i) => (a, b, i) } ...

C++ & Qt: Random string from an array area

c++,arrays,string,qt,random

You should use the random header. #include <random> std::default_random_engine generator; std::uniform_int_distribution dist(0, 5); int StringIndex = dist(generator); std::string ChosenString = characters[StringIndex]; The above will generate a random index into your array. If you want to limit the range, change the constructor of dist, for example (dist(0,2) would only allow for...

Stack level too deep because recursion

ruby-on-rails,ruby,ruby-on-rails-4,twitter

If you express the relation properly, ActiveRecord will do it for you class Tweet belongs_to :original_tweet, class_name: Tweet has_many :retweets, class_name: Tweet, dependent: :destroy, inverse_of :original_tweet end Tweet.last.destroy # will now destroy dependents ...

On rendering from controller, current_page method does not seem to work

ruby-on-rails,ruby,ruby-on-rails-4,model-view-controller

You can use content_for and yields to create a default in your layout which views can override. # layouts/application.html.erb: <% if content_for?(:banner) %> <%= yield(:banner) %> <% else %> <div id="banner"> <h1>This is the default...</h1> </div> <% end %> /users/signup.html.erb: <%- content_for :banner, flush: true do -%> <!-- move along,...

For loop with flexible stop variable

ruby

Normally we'd use a loop do with a guard clause: x = 1 loop do break if x >= y x += 1 ... end Make sure y is larger than x or it'll never do anything. y can change if necessary and as long as it's greater than x...

Javascript function to validate contents of an array

javascript,arrays

You can use a simple array based test like var validCodes = ['IT00', 'O144', '6A1L', '4243', 'O3D5', '44SG', 'CE64', '54FS', '4422']; function validItems(items) { for (var i = 0; i < items.length; i++) { if (validCodes.indexOf(items[i]) == -1) { return items[i]; } } return ''; } var items = ["IT00",...

Keep leading zeroes when converting string to integer

ruby

Short answer: no, you cant. 2.1.5 :001 > 0001 => 1 0001 doesn't make sense at all as Integer. In the Integer world, 0001 is exactly as 1. Moreover, the number of leading integer is generally irrelevant, unless you need to pad some integer for displaying, but in this case...

most efficient way to create javascript array out of various php arrays

javascript,php,jquery,arrays

John, Try this: var dataSet = []; for (i = 0; i < mfrPartNumber.length; i++ ) { data = [dateReceived[i],name[i],color[i]]; dataSet.push(data); } This will build an array out of each instance of [i], and keep growing as your user keeps pushing the button....

Blank screen on GridView

android,arrays,gridview

I executed ur code. Just add numberView.setTextColor(Color.BLACK); and it will work! :)...

Get elements containing text from array

javascript,jquery,html,arrays,contains

You can use :contains selector. I think you meant either one of those values, in that case var arr = ['bat', 'ball']; var selectors = arr.map(function(val) { return ':contains(' + val + ')' }); var $lis = $('ul li').filter(selectors.join()); $lis.css('color', 'red') <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <ul> <li>cricket bat</li> <li>tennis ball</li> <li>golf ball</li>...

Make instance variable accessible through hash in Ruby

ruby-on-rails,ruby,ruby-on-rails-4,activerecord

It's not "through Hash", it's "array access" operator. To implement it, you need to define methods: def [](*keys) # Define here end def []=(*keys, value) # Define here end Of course, if you won't be using multiple keys to access an element, you're fine with using just key instead of...

Heroku rake db:migrate failing - uninitialized constant

ruby-on-rails,ruby,heroku

Your migration file named should correspond to AddWeightToExercises. It should be accordingly xxxxxxxx_add_weight_to_exercises, where xxxxxxx corresponds to a particular timestamp.

Create array from another with specific indices

javascript,arrays

You can use .map, like so var data = [ 'h', 'e', 'l', 'l', 'o', ' ' ]; var indices = [ 4, 0, 5, 0, 1, 2, 2 ]; var res = indices.map(function (el) { return data[el]; }); console.log(res); The map() method creates a new array with the results...

How do I print more than one value per key in Tcl?

arrays,tcl

You can't do it with arrays or dictionaries; both are mappings from keys to values. Instead, you need to use foreach with a key-value pair system directly: set pairs { set1 table set2 chair set1 chair } foreach {key value} $pairs { puts "$key is $value" } This does actually...

How to pass array in rails 4 strong parameters

ruby-on-rails,arrays

According to the docs https://github.com/rails/strong_parameters#permitted-scalar-values: The permitted scalar types are String, Symbol, NilClass, Numeric, TrueClass, FalseClass, Date, Time, DateTime, StringIO, IO, ActionDispatch::Http::UploadedFile and Rack::Test::UploadedFile. To declare that the value in params must be an array of permitted scalar values map the key to an empty array: params.permit(:id => []) If...

Ruby: How to copy the multidimensional array in new array?

ruby-on-rails,arrays,ruby,multidimensional-array

dup does not create a deep copy, it copies only the outermost object. From that docs: Produces a shallow copy of obj—the instance variables of obj are copied, but not the objects they reference. dup copies the tainted state of obj. If you are not sure how deep your object...

Rails basic auth not working properly

ruby-on-rails,ruby,authentication

@user.keys.each do |key| username == key.api_id && password == key.api_key end This piece of code returns a value of .each, which is the collection it's called on (@user.keys in this case). As it is a truthy value, the check will pass always, regardless of what are the results of evaluating...

pointer to pointer dynamic array in C++

c++,arrays,pointers

The valid range of indices of an array with N elements is [0, N-1]. Thus instead of for example this loop for (int i=1; i <= n; i++) ^^^^ ^^^^^^ you have to write for ( int i = 0; i < n; i++ ) As you used operator new...

Ruby on Rails - Help Adding Badges to Application

ruby-on-rails,ruby,rest,activerecord,one-to-many

Take a look at merit gem. Even if you want to develop your own badge system from scratch this gem contains plenty of nice solutions you can use. https://github.com/merit-gem/merit

Allowing some enabled and disabled option on collection_select

ruby-on-rails,ruby

collection_select internally relies on options_from_collection_for_select helper. Rather than using the collection_select directly, you can use select and pass the result of a options_from_collection_for_select call. The reason you may want to call options_from_collection_for_select directly, is because this method also accepts an optional selected parameter that could be used to pass a...

Segmentation Fault if I don't say int i=0

c,arrays,segmentation-fault,initialization,int

In your code, int i is an automatic local variable. If not initialized explicitly, the value held by that variable in indeterministic. So, without explicit initialization, using (reading the value of ) i in any form, like array[i] invokes undefined behaviour, the side-effect being a segmentation fault. Isn't it automatically...

Loop until i get correct user

ruby,redis

Change if to while: while ["user_4", "user_5"].include?(@randUser = @redis.spop("users")) do @redis.sadd("users", @randUser) end $user_username = @redis.hget(@randUser, "username") $user_password = @redis.hget(@randUser, "password") Please note, that you actually mixed up receiver and parameters on Array#include?...

Ruby- get a xml node value

ruby,xml

Try to use css instead of xpath, this will work for you, doc = Nokogiri::XML(response.body) values = doc.css('Name').select{|name| name.text}.join',' puts values => Ram,Sam ...

SCALA: change the separator in Array

arrays,string,scala,delimiter

Your question is unclear, but I'll take a shot. To go from: val x = Array("a","x,y","b") to "a:x,y:b" You can use mkString: x.mkString(":") ...

Notice: Array to string conversion in “path of php file” on line 64

php,mysql,arrays,oracle

Curly brackets are your friend when inserting variables into double quoted strings: $main_query=oci_parse($connection,"INSERT INTO ROTTAN(NAME,ROLLNO) VALUES('{$array[$rs][0]}','{$array[$rs][1]}')"); ...

Rails Association Guidance [on hold]

ruby-on-rails,ruby,ruby-on-rails-4,ruby-on-rails-3.2

So, the complex part of your situation is that you have one thing (Surgery) that can be of many different types, and the different types have different fields. There are a number of different approaches to this problem, and I don't believe there's wide consensus on the 'best way'. The...

Perl: Using Text::CSV to print AoH

arrays,perl,csv

Pretty fundamentally - CSV is an array based data structure - it's a vaguely enhanced version of join. But the thing you need for this job is print_hr from Text::CSV. First you need to set your header order: $csv->column_names (@names); # Set column names for getline_hr () Then you can...

Merge and sum values and put them in an array

javascript,arrays,angularjs,foreach

You cannot store key-value pair in array. Use object to store key-value pair. See comments inline in the code. var obj = {}; // Initialize the object angular.forEach(data, function(value, key) { if (value.start_date > firstdayOfWeek && value.start_date < lastdayOfWeek) { if (obj[value.firstname]) { // If already exists obj[value.firstname] += value.distance;...

Rails shared controller actions

ruby-on-rails,ruby,ruby-on-rails-4

You should pass actions to the included block and perform_search_on to the class_methods block. module Searchable extend ActiveSupport::Concern class_methods do def perform_search_on(klass, associations = {}) ............. end end included do def filter respond_to do |format| format.json { render 'api/search/filters.json' } end end end end When your Searchable module include a...

Infinite loop with fread

c,arrays,loops,malloc,fread

If you're "trying to allocate an array 64 bytes in size", you may consider uint8_t Buffer[64]; instead of uint8_t *Buffer[64]; (the latter is an array of 64 pointers to byte) After doing this, you will have no need in malloc as your structure with a 64 bytes array inside is...

do calculation inside JSONArray in Java

java,arrays,json

Here's what I would do. Replace <JSON STRING HERE> with the JSON String you were going to parse: ArrayList<ArrayList<Integer>> resultList = new ArrayList<ArrayList<Integer>>(); JSONArray arr = new JSONArray(<JSON STRING HERE>); for(int i = 0; i < arr.length(); i ++) { JSONObject obj = arr.getJSONObject(i); JSONArray valueArray = obj.getJSONArray("values"); ArrayList<Integer> dataList...

What is Rack::Utils.multipart_part_limit within Rails and what function does it perform?

ruby-on-rails,ruby,rack,multipart

Telling it short, this value limits the amount of simultaneously opened files for multipart requests. To understand better what is multipart, you can see this question. The reason for this limitation is an ability to better adjust your app for your server. If you have too many files opened at...

Substring of a file

javascript,arrays,substring

To get your desired output, this will do the trick: var file = "a|b|c|d, a|b|c|d, a|b|c|d, a|b|c|d, a|b|c|d"; var array = file.split(", ") // Break up the original string on `", "` .map(function(element, index){ var temp = element.split('|'); return [temp[0], temp[1], index + 1]; }); console.log(array); alert(JSON.stringify(array)); The split converts...

Same enum values for multiple columns

ruby-on-rails,ruby,enums

Maybe it makes extract the planet as another model? def Planet enum type: %w(earth mars jupiter) end class PlanetEdge < ActiveRecord::Base belongs_to :first_planet, class_name: 'Planet' belongs_to :second_planet, class_name: 'Planet' end You can create a PlanetEdge by using accepts_nested_attributes_for: class PlanetEdge < ActiveRecord::Base belongs_to :first_planet, class_name: 'Planet' belongs_to :second_planet, class_name: 'Planet'...

How to innerHTML a function with array as parameter?

javascript,arrays,loops,foreach,innerhtml

Just take a variable for the occurrence of even or odd numbers. var myArray = function (nums) { var average = 0; var totalSum = 0; var hasEven = false; // flag if at least one value is even => true, otherwise false nums.forEach(function (value) { totalSum = totalSum +...

Ruby boolean logic: some amount of variables are true

ruby

[a, b, c].count(true) < 2 ........................

Javascript sort array of objects in reverse chronological order

javascript,arrays,sorting

As PM 77-1 suggests, consider using the built–in Array.prototype.sort with Date objects. Presumably you want to sort them on one of start or end: jobs.sort(function(a, b) { return new Date(a.ys, a.ms-1) - new Date(b.ys, b.ms-1); }) ...

Array in Foreach (CodeIgniter)

php,arrays,codeigniter,foreach

You can use active record as below. $arrResult = $this->db ->where('id','foo') ->where_in('result',array(1,2)) // alternative to above condition //->where('(result = 1 OR result = 2)') ->get('mytable') ->result_array(); foreach($arrResult as $result){ // run code based on $result; } ...

array and function php

php,arrays

$x and $y are only defined within the scope of the function. The code outside of the function does not know what $x or $y are and therefore will not print them. Simply declare them outside of the function as well, like so: <?php function sum($x, $y) { $z =...

Having two arrays in variable php

php,mysql,arrays,variables,multidimensional-array

The explode function is being used correctly, so your problem is further up. Either $data[$i] = mysql_result($result,$i,"data"); isn't returning the expected string "2015-06-04" from the database OR your function $data[$i] = data_eng_to_it_($data[$i]); isn't returning the expected string "04 June 2015" So test further up by echo / var_dump after both...

Heroku RAM not increasing with upgraded dynos

ruby-on-rails,ruby,ruby-on-rails-3,memory,heroku

That log excert is from a one off dyno, a la heroku run console - this is entirely seperate to your web dynos which you may be runnning 2x dyno's for. You need to specifiy --size=2x in your heroku run command to have the one off process use 2x dynos.

jQuery - Value in Function

jquery,arrays,function

You need to use brackets notation to access property by variable: function myFunc( array, fieldToCompare, valueToCompare ) { if( array[fieldToCompare] == "Thiago" ) alert(true); } And wrap name in quotes: myFunc( myArray, 'name', "Thiago" ); ...

Ruby access words in string

ruby

What you are doing will access the fourth character of String s. Split the string to an array and then access the fourth element as follows. puts s.split[3] Note: Calling split without parameters separates the string by whitespace. Edit: Fixing indexes. The index starts from 0. That means s.split[3] will...