## Laravel Factory with loop - laravel-5.5

### List comparison

```I use this question in interviews and I wonder what the best solution is.
Write a Perl sub that takes n lists, and then returns 2^n-1 lists telling you which items are in which lists; that is, which items are only in the first list, the second, list, both the first and second list, and all other combinations of lists. Assume that n is reasonably small (less than 20).
For example:
list_compare([1, 3], [2, 3]);
=> ([1], [2], [3]);
Here, the first result list gives all items that are only in list 1, the second result list gives all items that are only in list 2, and the third result list gives all items that are in both lists.
list_compare([1, 3, 5, 7], [2, 3, 6, 7], [4, 5, 6, 7])
=> ([1], [2], [3], [4], [5], [6], [7])
Here, the first list gives all items that are only in list 1, the second list gives all items that are only in list 2, and the third list gives all items that are in both lists 1 and 2, as in the first example. The fourth list gives all items that are only in list 3, the fifth list gives all items that are only in lists 1 and 3, the sixth list gives all items that are only in lists 2 and 3, and the seventh list gives all items that are in all 3 lists.
I usually give this problem as a follow up to the subset of this problem for n=2.
What is the solution?
Follow-up: The items in the lists are strings. There might be duplicates, but since they are just strings, duplicates should be squashed in the output. Order of the items in the output lists doesn't matter, the order of the lists themselves does.
```
```Your given solution can be simplified quite a bit still.
In the first loop, you can use plain addition since you are only ever ORing with single bits, and you can narrow the scope of \$bit by iterating over indices. In the second loop, you can subtract 1 from the index instead of producing an unnecessary 0th output list element that needs to be shifted off, and where you unnecessarily iterate m*n times (where m is the number of output lists and n is the number of unique elements), iterating over the unique elements would reduce the iterations to just n (which is a significant win in typical use cases where m is much larger than n), and would simplify the code.
sub list_compare {
my ( #list ) = #_;
my %dest;
for my \$i ( 0 .. \$#list ) {
my \$bit = 2**\$i;
\$dest{\$_} += \$bit for #{ \$list[ \$i ] };
}
my #output_list;
for my \$val ( keys %dest ) {
push #{ \$output_list[ \$dest{ \$val } - 1 ] }, \$val;
}
return \#output_list;
}
Note also that once thought of in this way, the result gathering process can be written very concisely with the aid of the List::Part module:
use List::Part;
sub list_compare {
my ( #list ) = #_;
my %dest;
for my \$i ( 0 .. \$#list ) {
my \$bit = 2**\$i;
\$dest{\$_} += \$bit for #{ \$list[ \$i ] };
}
return [ part { \$dest{ \$_ } - 1 } keys %dest ];
}
But note that list_compare is a terrible name. Something like part_elems_by_membership would be much better. Also, the imprecisions in your question Ben Tilly pointed out need to be rectified.
```
```First of all I would like to note that nohat's answer simply does not work. Try running it, and look at the output in Data::Dumper to verify that.
That said, your question is not well-posed. It looks like you are using sets as arrays. How do you wish to handle duplicates? How do you want to handle complex data structures? What order do you want elements in? For ease I'll assume that the answers are squash duplicates, it is OK to stringify complex data structures, and order does not matter. In that case the following is a perfectly adequate answer:
sub list_compare {
my #lists = #_;
for my \$list (#lists) {
my %in_list = map {\$_=>1} #\$list;
# We have this list.
}
}
}
If you want to adjust those assumptions, you'll need to adjust the code. For example not squashing complex data structures and not squashing duplicates can be done with:
sub list_compare {
my #lists = #_;
for my \$list (#lists) {
my %in_list = map {\$_=>1} #\$list;
# We have this list.
}
}
}
This is, however, using the stringification of the data structure to check whether things that exist in one exist in another. Relaxing that condition would require somewhat more work.
```
```Here is my solution:
Construct a hash whose keys are the union of all the elements in the input lists, and the values are bit strings, where bit i is set if the element is present in list i. The bit strings are constructed using bitwise or. Then, construct the output lists by iterating over the keys of the hash, adding keys to the associated output list.
sub list_compare {
my (#lists) = #_;
my %compare;
my \$bit = 1;
foreach my \$list (#lists) {
\$compare{\$_} |= \$bit foreach #\$list;
\$bit *= 2; # shift over one bit
}
my #output_lists;
foreach my \$item (keys %compare) {
push #{ \$output_lists[ \$compare{\$item} - 1 ] }, \$item;
}
return \#output_lists;
}
Updated to include the inverted output list generation suggested by Aristotle```

### How to define empty dict<string, int> in hacklang

```I have following shape:
const type A = shape(
'b' => dict<string, int>,
);
How do I create this shape with empty dict? For example from this function
function getA(): A {
return shape(
'b' => ???
);
}
```
```This is a part of the Hack array proposal
A dict array is a container mapping a valid arraykey to a value. This
mirrors the behavior of the Map class. This will be an array at
runtime with extra restrictions to allow it to be used safely like a
Map from the type checkers perspective. This focuses mainly on the
desired runtime behavior, but if there are questions for how it will
interact with the type checker I'll be happy to discuss. Literal
Constructor
A dict is constructed using the literal expression dict[].
\$dict = dict[]; // Empty dict-array
\$dict = dict['a' => 1, 'b' => 2, 'c' => 3]; // dict-array of 3 elements
This is a static expression, so it can be used in a static
initializer.
class C {
public static dict<string, int> \$dict = dict[
'a' => 1,
'b' => 2,
'c' => 3,
];
}
you don't need to define the type when creating dictionaries ( dict[] ) or vectors ( vec[] ) as generics are ignored in runtime
example :
function spamMessages(dict<string, string> \$messages): void
{
foreach(\$messages as \$user => \$message) {
echo \$user . ': ' . \$message;
}
}
function listUsers(vec<string> \$users): void
{
foreach(\$users as \$user) {
echo '-' . \$user;
}
}
\$messages = dict[
];
\$users = vec[
'azjezz'
];
spamMessages(\$messages);
listUsers(\$users);
in this example, the type checker is smart enough to see that \$message have both keys and values of type string so it won't raise any errors.
you can also create a dict array or a vector from a php-style array using the vec and dict helpers
\$array = [
'a' => 1,
'b' => 'c'
];
\$dict = dict(\$array);
in the above example, the type checker knows about the type of the keys in \$array, and since the dict helper is declare as dict<Tk, Tv>(array<Tk, Tv> \$array): dict<Tk, Tv> it knows that the returned dict array contains the same types for both keys and values.
sometimes you may not be able to tell the type checker about the types of array keys and values.
example :
\$array = json_decode('path/to/file.json');
you know that the json files contains an array of string keys and values for example, but here type checker thinks that \$array is of type mixed since there's no way to actually tell what's inside the file.
in order to get over this, you can use the as operator to tell the type checker about \$array type
\$array = json_decode('path/to/file.json') as array<_, _>;
notice that here we used _ instead of string and they type checker is gonna assume that \$array now is of type array<arraykey, mixed>, the reason is generics are not supported with the as operator as of now, but this might changed in future so we can do as array<string, string>
later you can create a dict out of that array :
\$dict = dict(\$array);
if you for example know that there's no way for that file to contain anything beside string keys and values and want to force that type you can use the following helper to cast it to a dict of type dict<string, string>, but i won't recommend it as it may cause an error while casting non-stringable objects or resources to string.
// KeyedContainer = array, dict, maps and other keyed containers
function forceStringDict(KeyedContainer<arraykey, mixed> \$container): dict<string, string>
{
\$dict = dict[];
foreach(\$container as \$k => \$v) {
\$dict[(string) \$k] = (string) \$v;
}
return \$dict;
}
\$dict = forceStringDict(\$dict);
```
```Have no idea what language features I used, but this does the trick.
function getA(): A {
return shape(
'b' => dict[]
);
}

### Assigning a value to the attribute of a mixed-in role

```I'm trying to work an example that uses the Enumeration role in Perl 6 (as part of fixing doc issue Enumeration role is not documented). I came up with this simple example:
class DNA does Enumeration {
my \$DNAindex = 0;
my %pairings = %( A => "T",
T => "A",
C => "G",
G => "T" );
method new( \$base-pair where "A" | "C" | "G" | "T" ) {
self.bless( key => \$base-pair,
value => %pairings{\$base-pair},
index => 33);
}
multi method gist(::?CLASS:D:) {
return "\$!key -> \$!value with \$!index";
}
}
for <A C G T>.roll( 16 ) -> \$letter {
my DNA \$base = DNA.new( \$letter );
say "Pairs ", \$base.pair, " with ", \$base.gist;
}
Theoretically, Enumeration has \$!index, and with index => 33 I try to assign a value to it; however, all it returns is something like
Pairs T => A with T -> A with 0
Any other way to assign a value to \$!index directly, and I get the "cannot assign to an immutable value I got in another question. That might be a bug, according to one of the answers; in that case, I'd like to know if there's some workaround to it.
```
```It's a bug Cannot change native role attribute from consuming class (nothing to do with the one mentioned in the answer you linked).
I don't know of a workaround.```

### Preferred method to reduce/filter a Map in Dart?

```Trying to find the cleanest way to reduce a Map in Dart. Looking for something akin to JavaScript's Array.prototype.filter()
Any suggestions? The following method leaves a lot to be desired:
Map ingredients = {
'flour': '250g',
'butter': '50g',
'egg': 1,
'water': '0.2l'
};
final flour = new Map.fromIterable(
ingredients.keys.where((k) => ingredients[k] == '250g'),
value: (k) => ingredients[k]
);
print(flour); // {flour: 250g}
```
```There is no built in support for Pairs in the core library. However if you find yourself doing this type of thing often, you could write a utility library. For example:
library pairs;
class Pair<K,V> {
Pair(this.k, this.v)
final K k;
final V v;
String toString() => '(\$k, \$v)';
}
Iterable<Pair> asPairs(Map map) => map.keys.map((k) => new Pair(k, map[k]));
Map fromPairs(Iterable<Pair> pairs) => new Map.fromIterables(
pairs.map((p) => p.k),
pairs.map((p) => p.v));
Then you can use it like this:
import 'src/pairs.dart';
Map flour = fromPairs(asPairs(ingredients).where((p) => p.v == '250g'));
print(flour); // {flour: 250g}
Perhaps this is something that could be contributed to the quiver package, a set of non-core utilities.```

### How to convert a List into a Map in Dart

```I looking for an on-the-shelf way to convert a List into a Map in Dart.
In python for example you can do:
l= [ ('a',(1,2)), ('b',(2,3)), ('c',(3,4) ) ]
d=dict(l)
==> {'a': (1, 2), 'c': (3, 4), 'b': (2, 3)}
The dict function expects a List of couple. For each couple, the first element is used as the key and the second as the data.
In Dart I saw the following method for a List : asMap(), but it's not doing what i expect: it use the list index as key.
My questions:
Do you known anything in Dart libraries to do this ?
If not, any plan to add such a feature in the core lib ?
Proposal:
List.toMap() //same as python dict.
List.toMap( (value) => [ value[0], value[1] ] ) //Using anonymous function to return a key and a value from a list item.
Thanks and Regards,
Nicolas
```
```There's no such method and I don't think there's any plan to add such function. You can file an issue if you consider this as important.
The List.asMap documentation is :
Returns an unmodifiable Map view of this.
It has the indices of this list as keys, and the corresponding elements as values.
However, you can do what you want like this :
Map dict(List l) {
final m = {};
l.forEach((e){ m[e[0]] = e[1]; });
return m;
}
main(){
print(dict([["a", "b"], ["c", "d"]])); // prints {a: b, c: d}
}
```
```In Dart 1.1, you can use this constructor of Map:
new Map.fromIterable(list, key: (v) => v[0], value: (v) => v[1]);
This would be closest to your original proposal.
```
`There is not yet a concept of tuples or pairs in dart (other than a two element Iterable). If Dart had such a concept, then issue 7088 proposes to solve this with a Map.fromPairs constructor.`