Time complexity of creating a Hashie::Mash object - ruby

I want to understand how expensive is to create a new Hashie::Mash. Does calling Hashie::Mash.new(object_hash) creates a deep copy of the "object_hash"
Example: What is the time complexity of below given array size is M and emp object has N key value pair.
array.map { |emp| Hashie::Mash.new(emp)
Will it be O ( M x N ) ?
Note:
I am trying to understand this from the performance perspective and N can be large won't be constant because of the nested hash.
In case you want to look at the structure of emp ( employee which can have nested employees is)
{
"id"=> 1,
.
.
"nested_employee" => [
{
"id"=> 12,
.
.
},
{
"id"=> 13,
.
.
}]
.
.
}

Related

How to sort string with numbers in it numerically?

So I am getting some json data and putting it inside of a Mutable List. I have a class with id, listId, and name inside of it. Im trying to sort the output of the list by listId which are just integers and then also the name which has a format of "Item 123". Im doing the following
val sortedList = data.sortedWith(compareBy({ it.listId }, { it.name }))
This sorts the listId correctly but the names is sorted alphabetically so the numbers go 1, 13, 2, 3. How am I able to sort both the categories but make the "name" also be sorted numerically?
I think
val sortedList = data.sortedWith(compareBy(
{ it.listId },
{ it.name.substring(0, it.name.indexOf(' ')) },
{ it.name.substring(it.name.indexOf(' ') + 1).toInt() }
))
will work but it is not computationally efficient because it will call String.indexOf() many times.
If you have a very long list, you should consider making another list whose each item has String and Int names.

How to store a list or a number into empty array in jsl?

I face a problem on how to store a list or a number into an empty array, below is my code :
For( i = 1, i <= N Items( S ), i++,
dt:Family Device << set name( "family device" );
dt << Select Where(Starts With( dt:family device, S[i] ) ) ;
baseDT = dt << Subset( output table name( "Subset" ), selected rows( 1 ), selected columns( 0 ), "invisible");
I plan to store baseDT in the empty array, Anyone has an idea on the store function? I very new to JSL if in python we will use append function to store, then how about jsl?
Initialize an empty array as
emp_array = {};
Append to array as :
Insert Into(emp_array, baseDT)
Then you can access the elements using index eg:
emp_array[n]

Finding k nearest neighbors with SPARQL query

I would like to write a single SPARQL query to find the k nearest neighbors for a set of vectors. To find the average label for the 100 nearest neighbors for a single vector I can use the following query:
PREFIX : <ml://>
PREFIX vector: <ml://vector/>
PREFIX feature: <ml://feature/>
SELECT (AVG(?label) as ?prediction)
WHERE {
{
SELECT ?other_vector (COUNT(?common_feature) as ?similarity)
WHERE { vector:0 :has ?common_feature .
?other_vector :has ?common_feature .
} GROUP BY ?other_vector ORDER BY DESC(?similarity) LIMIT 100
}
?other_vector :hasLabel ?label .
}
Is there a way to do this for multiple vectors in a single query?
Unless I'm overlooking something, you can do this by replacing the URI vector:0 with a variable, like so:
SELECT ?vector (AVG(?label) as ?prediction)
WHERE {
{
SELECT ?vector ?other_vector (COUNT(?common_feature) as ?similarity)
WHERE { ?vector :has ?common_feature .
?other_vector :has ?common_feature .
FILTER(?vector != ?other_vector)
} GROUP BY ?other_vector ORDER BY DESC(?similarity) LIMIT 100
}
?other_vector :hasLabel ?label .
}
I added a filter condition to check that ?vector and ?other_vector are not equal, whether that is necessary is up to you of course :)
If you need to restrict the list of vectors for which you want to find a match, you can use a VALUES clause to restrict possible bindings for ?vector:
VALUES ?vector { vector:0 vector:1 ... }

How to sort a lookup?

Hi I have a lookup type that stores strings and ints.
static Lookup<string, int> lookup;
lookup = (Lookup<string, int>)list.ToLookup(i => i.IP, i => i.Number);
But now I need to sort this lookup by the values (number), and get the top 10 keys with their values.
How is this possible?
Unfortunately elements inside a Lookup cannot be reordered.
But the ToLookup() method has a nice property that elements in all the groupings have the same order as the elements in the original sequence.
This means that with some Linq gymnastics, you can achieve what you want by using GroupBy:
var l = (from l in list
// group elements by key
group l by l.IP into g
// for each group order the elements and take top 10
select new { g.Key, Items = g.OrderBy(g1 => g1.Number).Take(10)} into g2
// flaten group into an enumerable using select many
from g in g2.Items
select g)
// get the desired lookup containing the top 10 ordered elements for each key
.ToLookup(g => g.IP, g => g.Number);
I'm not sure why you are casting a Lookup<string, int> to a Lookup<string, string>, but the general answer you want is:
var list = new List<Test>
{
new Test { IP = "A", Number = 1 }, new Test { IP = "A", Number = 3 }, new Test { IP = "A", Number = 4 },
new Test { IP = "B", Number = 1 }, new Test { IP = "B", Number = 1 }, new Test { IP = "B", Number = 1 },
new Test { IP = "C", Number = 1 },
new Test { IP = "D", Number = 1 },
new Test { IP = "E", Number = 1 }, new Test { IP = "E", Number = 1 }, new Test { IP = "E", Number = 1 }
};
var values = list.ToLookup(s => s.IP, s => s.Number)
.OrderByDescending(s => s.Count())
.Take(10);
Go find a Priority Queue (you can find one at http://www.itu.dk/research/c5/). Iterate over your look up and insert an IComparable item created from each entry in the look up, into the priority queue. Select the top ten items from the priority queue. Or just sort them by the count as the key.
var lookup = list.ToLookup( l => l.IP, l => l.Number );
var topten = lookup.OrderByDescending( l => l.Count() )
.Take( 10 );
foreach (var item in topten)
{
Console.WriteLine( "{0}: {1}", item.Key, item.Count() );
}
Note that sorting will have at best O(nlogn) performance while a good, heap-based priority queue will have O(logn) performance. If the collection isn't large, sorting is simpler given the built in support for it and not needing an intermediate class to support the priority queue implementation.
Take a look at the Take() LINQ function you should be able to do something like Take(10) to just return 10 results. As for sorting, check out the OrderBy() function that accepts a lambda expression as a sorting mechanism. Combining them both should give you what you're after.

Lua - Sorting a table alphabetically

I have a table that is filled with random content that a user enters. I want my users to be able to rapidly search through this table, and one way of facilitating their search is by sorting the table alphabetically. Originally, the table looked something like this:
myTable = {
Zebra = "black and white",
Apple = "I love them!",
Coin = "25cents"
}
I was able to implement a pairsByKeys() function which allowed me to output the tables contents in alphabetical order, but not to store them that way. Because of the way the searching is setup, the table itself needs to be in alphabetical order.
function pairsByKeys (t, f)
local a = {}
for n in pairs(t) do
table.insert(a, n)
end
table.sort(a, f)
local i = 0 -- iterator variable
local iter = function () -- iterator function
i = i + 1
if a[i] == nil then
return nil
else
return a[i], t[a[i]]
end
end
return iter
end
After a time I came to understand (perhaps incorrectly - you tell me) that non-numerically indexed tables cannot be sorted alphabetically. So then I started thinking of ways around that - one way I thought of is sorting the table and then putting each value into a numerically indexed array, something like below:
myTable = {
[1] = { Apple = "I love them!" },
[2] = { Coin = "25cents" },
[3] = { Zebra = "black and white" },
}
In principle, I feel this should work, but for some reason I am having difficulty with it. My table does not appear to be sorting. Here is the function I use, with the above function, to sort the table:
SortFunc = function ()
local newtbl = {}
local t = {}
for title,value in pairsByKeys(myTable) do
newtbl[title] = value
tinsert(t,newtbl[title])
end
myTable = t
end
myTable still does not end up being sorted. Why?
Lua's table can be hybrid. For numerical keys, starting at 1, it uses a vector and for other keys it uses a hash.
For example, {1="foo", 2="bar", 4="hey", my="name"}
1 & 2, will be placed in a vector, 4 & my will be placed in a hashtable. 4 broke the sequence and that's the reason for including it into the hashtable.
For information on how to sort Lua's table take a look here: 19.3 - Sort
Your new table needs consecutive integer keys and needs values themselves to be tables. So you want something on this order:
SortFunc = function (myTable)
local t = {}
for title,value in pairsByKeys(myTable) do
table.insert(t, { title = title, value = value })
end
myTable = t
return myTable
end
This assumes that pairsByKeys does what I think it does...

Resources