How do I pick randomly from an array?

Just use Array#sample: [:foo, :bar].sample # => :foo, or :bar 🙂 It is available in Ruby 1.9.1+. To be also able to use it with an earlier version of Ruby, you could require “backports/1.9.1/array/sample”. Note that in Ruby 1.8.7 it exists under the unfortunate name choice; it was renamed in later version so you shouldn’t … Read more

Preferred method to store PHP arrays (json_encode vs serialize)

Depends on your priorities. If performance is your absolute driving characteristic, then by all means use the fastest one. Just make sure you have a full understanding of the differences before you make a choice Unlike serialize() you need to add extra parameter to keep UTF-8 characters untouched: json_encode($array, JSON_UNESCAPED_UNICODE) (otherwise it converts UTF-8 characters … Read more

Convert pandas dataframe to NumPy array

Use df.to_numpy() It’s better than df.values, here’s why.* It’s time to deprecate your usage of values and as_matrix(). pandas v0.24.0 introduced two new methods for obtaining NumPy arrays from pandas objects: to_numpy(), which is defined on Index, Series, and DataFrame objects, and array, which is defined on Index and Series objects only. If you visit … Read more

Adding values to a C# array

You can do this way – int[] terms = new int[400]; for (int runs = 0; runs < 400; runs++) { terms[runs] = value; } Alternatively, you can use Lists – the advantage with lists being, you don’t need to know the array size when instantiating the list. List<int> termsList = new List<int>(); for (int … Read more

Check if a Bash array contains a value

This approach has the advantage of not needing to loop over all the elements (at least not explicitly). But since array_to_string_internal() in array.c still loops over array elements and concatenates them into a string, it’s probably not more efficient than the looping solutions proposed, but it’s more readable. if [[ ” ${array[*]} ” =~ ” … Read more

How do I find the length of an array?

If you mean a C-style array, then you can do something like: int a[7]; std::cout << “Length of array = ” << (sizeof(a)/sizeof(*a)) << std::endl; This doesn’t work on pointers (i.e. it won’t work for either of the following): int *p = new int[7]; std::cout << “Length of array = ” << (sizeof(p)/sizeof(*p)) << std::endl; … Read more