How to know if no more values are present in the array as you iterate the array in a loop - arrays

So, I have a locations table in database which contains the seller_id. Many locations can have the same seller_id while locations are unique.
In the function, I get an input array which is the list of locations and each location has another array which is list of variants. Example
$data = [
23 => [40 => 1, 25 => 2],
6 => [22 => 3, 24 => 4],
28 => [22 => 3, 24 => 4],
18 => [22 => 3, 24 => 4],
]
So here, 23,6,28 and 18 are the locations and 40,25,22,24 are the variants.
The problem here is, I need an array of seller_id's and each seller_id will have the array of their respective variants. And I need to do it in an optimised way.
I figure it's something of this sort,
$locationIDs = collect($inventoryData)->keys();
$locationBySellers = Location::whereIn('id', $locationIDs)->pluck('seller_id','id');
foreach ($locationBySellers as $location => $seller) {
$variants = array_keys($data[$location]);
echo "Seller: ".$seller.", Variants: ".$variants."\n";
//How to know if no more sellers are present with value $seller
}
Can you help me with this. Any advice would be appreciated

Suppose $data is what you can pull from database. The following code will get the seller_id and their respective variants.
$data = [
23 => [40 => 1, 25 => 2],
6 => [22 => 3, 24 => 4],
28 => [22 => 3, 24 => 4],
18 => [22 => 3, 24 => 4],
];
foreach ($data as $location => $seller) {
$variants = array_keys($data[$location]);
foreach($seller as $variant=>$id) {
if(!isset($sellers[$id])) $sellers[$id]=[];
if(!in_array($variant,$sellers[$id])) array_push($sellers[$id],$variant);
}
// echo "Seller: ".$seller.", Variants: ".$variants."\n";
//How to know if no more sellers are present with value $seller
}
var_dump($sellers);
And it will output array(4) { [1]=> array(1) { [0]=> int(40) } [2]=> array(1) { [0]=> int(25) } [3]=> array(1) { [0]=> int(22) } [4]=> array(1) { [0]=> int(24) } }.

Related

How to convert a Hash with values as arrays to a Hash with keys from array and values as array of keys?

I have a hash of the following form:
{ 1 => [], 2 => ["A", "B"], 3 => ["C"], 4 => ["B", "C"], 5 => ["D"] }
what's the best way to transform this in Ruby to:
{ "A" => [2], "B" => [2, 4], "C" => [3, 4], "D" => [5], "default" => [1] }
The best way I know.
hash = { 1 => [], 2 => ['A','B'], 3 => ['C'], 4 => ['B','C'], 5 => ['D'] }
new_hash = hash.inject({}) do |result, (key, values)|
values.each do |value|
result[value] ||= []
result[value].push(key)
end
result[:default] = [key] if values.empty?
result
end
puts new_hash
A bit of more functional approach:
array
.flat_map {|k,v| v.product([k])}
.group_by(&:first)
.transform_values {|v| v.map(&:last) }
input = { 1 => [], 2 => ['A', 'B'], 3 => ['C'], 4 => ['B', 'C'], 5 => ['D'], 6 => [] }
output =
input.each_with_object(Hash.new([])) do |(key, values), hash|
values.each { |value| hash[value] += [key] }
hash['default'] += [key] if values.empty?
end
output
# => {"default"=>[1, 6], "A"=>[2], "B"=>[2, 4], "C"=>[3, 4], "D"=>[5]}

How to return all even numbers inside an array inside of a hash?

I've been given the following data structure:
users = {
"Jonathan" => {
:twitter => "tronathan",
:favorite_numbers => [12, 42, 75],
},
"Erik" => {
:twitter => "sferik",
:favorite_numbers => [8, 12, 24],
},
"Anil" => {
:twitter => "bridgpal",
:favorite_numbers => [12, 14, 85],
},
}
I need to return all of Anils favourite numbers that are even.
This is what I have so far:
users["Anil"][:favorite_numbers].each do |evennum|
if evennum.even?
puts evennum
end
end
You could do something like this
anil_favorite_even_numbers = users['Anil'][:favorite_numbers].select(&:even?)
This takes for granted that a user Anil exists and the favourite_numbers inside it too and that's an array. Otherwise we need a little bit of extra work.

Does Perl 6 have a built-in tool to make a deep copy of a nested data structure?

Does Perl 6 have a built-in tool to make a deep copy of a nested data structure?
Added example:
my %hash_A = (
a => {
aa => [ 1, 2, 3, 4, 5 ],
bb => { aaa => 1, bbb => 2 },
},
);
my %hash_B = %hash_A;
#my %hash_B = %hash_A.clone; # same result
%hash_B<a><aa>[2] = 735;
say %hash_A<a><aa>[2]; # says "735" but would like get "3"
my %A = (
a => {
aa => [ 1, 2, 3, 4, 5 ],
bb => { aaa => 1, bbb => 2 },
},
);
my %B = %A.deepmap(-> $c is copy {$c}); # make sure we get a new container instead of cloning the value
dd %A;
dd %B;
%B<a><aa>[2] = 735;
dd %A;
dd %B;
Use .clone and .deepmap to request a copy/deep-copy of a data-structure. But don't bet on it. Any object can define its own .clone method and do whatever it wants with it. If you must mutate and therefore must clone, make sure you test your program with large datasets. Bad algorithms can render a program virtually useless in production use.
The dirty way:
#!/usr/local/bin/perl6
use v6;
use MONKEY-SEE-NO-EVAL;
my %hash_A = (
a => {
aa => [ 1, 2, 3, 4, 5 ],
bb => { aaa => 1, bbb => 2 },
},
);
my %hash_B;
EVAL '%hash_B = (' ~ %hash_A.perl ~ ' )';
%hash_B<a><aa>[2] = 735;
say %hash_A;
say %hash_B;
which gives you:
$ perl6 test.p6
{a => {aa => [1 2 3 4 5], bb => {aaa => 1, bbb => 2}}}
{a => {aa => [1 2 735 4 5], bb => {aaa => 1, bbb => 2}}}
If you eval input from external source, always remember to check it first. Anyway, using EVAL is dangerous and should be avoided.

Hash with array of hashes inside hash

I have a hash like this:
document = {
"results" => {[
{"ip" => 10, "host" => 12},
{"ip" => 13, "host" => 17}
]}
}
It's a one item hash with an array of hashes inside the hash. I specified a value of ip = 10.
If the ip is more than 10, I want to print both keys with values. This hash is very complicated and I don't know how to access these values. Can you help me?
Edit:
What if I had hash like this
document = { "results" => [{"ip" => 10, "host" => 12, "temp" => yes},{"ip" => 13, "host" => 17, "temp" => yes}] } and wanted print only ip and host after matching ip with 10?
document["results"].each do |result|
if result["ip"] > 10
puts result # will print ip and host
end
end
I would use select:
document = { "results" => [{"ip" => 10, "host" => 12},{"ip" => 13, "host" => 17}] }
puts document['results'].select { |hash| hash['ip'] > 10 }
#=> {"ip"=>13, "host"=>17}
Explanation:
document['results']
returns the array of hashes:
[{"ip" => 10, "host" => 12},{"ip" => 13, "host" => 17}]
In the next step select is called on that returned array:
document['results'].select { |hash| hash['ip'] > 10 }
This returns all sub-hashes with an value > 10 assigned to the key 'ip'.
puts just prints the result to STDOUT
I have another problem today. Here is my code:
require 'rubygems'
require 'json'
document = JSON.load File.new("hosts.txt")
file = JSON.load File.new("admins.txt")
first_table = document["results"]
second_table = file["admins"]
new_one = first_table | second_table
First hash looks like this:
document = { "results" => [{"ip" => 10, "host" => 12},{"ip" => 13, "host" => 17}] }
The second hash is
file = { "admins" => [{"host" => 12, "name" => 12},{"host" => 17, "name" => 17}] }
I want merge these two hashes matching them by host by the same value to get
{ "new_one" => [{"ip" => 10, "host" => 12, "name" => 12}, {"ip" => 13, "host" => 17}, "name" => 17]
When I try new_one = first_table | second_tableit says test.rb:24:in <main>': undefined method|' for #Hash:0x00000002ca8be8 (NoMethodError) and when I try new_one = first_table.merge(second_table)its says test.rb:26:in <main>': undefined methodmerge' for #Array:0x00000002ce88b0(NoMethodError). So what is wrong with these hashes? One time they are hashes and the second time they are arrays? How to mach these hashes? The keys and values of host the same in both hashes.

Hash whose values are array size

I need a method that will take a hash and return a hash whose keys are from the old hash and values are the size of the arrays in the old hash. I.e.,
{ 1 => [1,1,1], 2 => [3,4,5], 7 => [9,12] }
# return
{ 1 => 3, 2 => 3, 7 => 2 }
Is there any way to implement this?
One way:
h = { 1 => [1,1,1], 2 => [3,4,5], 7 => [9,12] }
h.merge(h) { |*_,a| a.size }
#=> { 1 => 3, 2 => 3, 7 => 2 }
You can use map to build a new array of [key, value] pairs and then convert it back to a hash using to_h:
input = { 1 => [1,1,1], 2 => [3,4,5], 7 => [9,12] }
input.map { |key, value| [key, value.length] }.to_h
# => {1=>3, 2=>3, 7=>2}
This is quite straightforward: you can use inject to process all the items one by one and compose the result.
input = { 1 => [1,1,1], 2 => [3,4,5], 7 => [9,12] }
input.inject({}) do |result, (key, value)|
result.merge(key => value.size)
end
# => {1=>3, 2=>3, 7=>2}
Even without inject, just use .each to loop all the items and construct the result using a temporary support Hash.
Just for the sake of completeness, a solution using each_with_object:
input = { 1 => [1,1,1], 2 => [3,4,5], 7 => [9,12] }
input.each_with_object({}) { |(k, vs), h| h[k] = vs.size }
#=> {1=>3, 2=>3, 7=>2}
One way is to insert the expected keys and values into the new Hash:
h = { 1 => [1,1,1], 2 => [3,4,5], 7 => [9,12] }
h2 = {}
h.each {|k, v| h2[k] = v.length}
h2
# => {1=>3, 2=>3, 7=>2}
h.keys.zip(h.values.map &:size).to_h
Or you can try this,
h = { 1 => [1,1,1], 2 => [3,4,5], 7 => [9,12] }
Hash[h.map {|key, value| [key, value.length]}]
# => {1=>3, 2=>3, 7=>2}

Resources