How can I extract values from within a list - list

Let us say that I have a Map in dart which holds value in this format : String, List<MyModel>. Now the Map would look something like this -
{
'a' : [MyModel1, MyModel2],
'b' : [MyModel3],
'c' : [MyModel4, MyModel5]
}
I want to design a function that would return me this : [MyModel1, MyModel2,......,MyModel5] . I can easily do the same by iterating over values in the map and then use a nested loop to iterate over each value to finally extract each of the elements. However, what I want is a better way to do it (probably without using the two for loops as my Map can get pretty long at times.
Is there a better way to do it ?

You could use a Collection for and the ... spread operator, like this:
void main() {
Map<String, List<int>> sampleData = {
'a': [1, 2],
'b': [3],
'c': [4, 5, 6]
};
final output = mergeMapValues(sampleData);
print(output); // [1, 2, 3, 4, 5, 6]
}
// Merge all Map values into a single list
List<int> mergeMapValues(Map<String, List<int>> sampleData) {
final merged = <int>[for (var value in sampleData.values) ...value]; // Collection for
return merged;
}
Here's the above sample in Dartpad: https://dartpad.dev/?id=5b4d258bdf3f9468abbb43f7929f4b73

Related

filesystem::directory_iterator pass to json

I'm new at anything JSON.
I am trying to use this lib made by nlohmann:
https://github.com/nlohmann/json
I need to be able to loop over my folders, then loop over the items, and add them all to a JSON document.
auto jComponents = nlohmann::json{ {"Components", nlohmann::json::array()} };
for (auto& p : fs::directory_iterator(path, fs::directory_options::skip_permission_denied)) {
if (p.is_directory()) {
auto jComponent = nlohmann::json::array();
for (auto& sub : fs::directory_iterator(p, fs::directory_options::skip_permission_denied)) {
if (sub.path().extension() == ".png")
jComponent["image"] = sub.path();
else if (sub.path().extension() == ".ini")
jComponent["ini"] = sub.path();
}
jComponents.push_back(jComponent);
}
}
Your jComponents is not a json array, it is a json object with a property 'Components' whose value is an empty json array. You are calling the push_back function on a json object without a property name.
I think what you want is:
jComponents["Components"].push_back(jComponent);
The signature of the push_back function:
// (1)
void push_back(basic_json&& val);
void push_back(const basic_json& val);
// (2)
void push_back(const typename object_t::value_type& val);
// (3)
void push_back(initializer_list_t init);
The first version assumes this is a json array;
The second version assumes this is a json object;
For the third, if this is a json object, the init must contain only two elements and the first one must be a string; otherwise, assumes this is a json array.
// NOTE: Not actually tested
json array = {1, 2, 3};
// [1, 2, 3]
array.push_back(4);
// [1, 2, 3, 4]
array.push_back({"a", 5});
// [1, 2, 3, 4, {a: 5}]
json object = {{"a", 1}, {"b", 2}};
// {a: 1, b: 2}
object.push_back(json::object_t::value_type("c", 3));
// {a: 1, b: 2, c: 3}
object.push_back({"d", 4});
// {a: 1, b: 2, c: 3, d: 4}
object.push_back(5);
// Throws

Unable to understand lists in dart consider the example provided

I am developing an app in flutter. For which I am using lists of map but there something that I am unable to undertand. Consider the following cases:
SCENARIO 1
void main() {
List<Map<String,String>> _reminders = [];
Map<String , String> _tempMap = {};
for (int i = 0; i < 5; i++) {
_tempMap.clear();
_tempMap.putIfAbsent('M' , () => 'm ' + i.toString());
_tempMap.putIfAbsent('D' , () => 'd : ' + i.toString());
_reminders.add(_tempMap);
// or _reminders.insert(i, _tempMap);
}
print(_reminders.toString());
return;
}
to which the result is as follows
[{M: m 4, D: d : 4}, {M: m 4, D: d : 4}, {M: m 4, D: d : 4}, {M: m 4, D: d : 4}, {M: m 4, D: d : 4}]
SCENARIO 2
void main() {
List<Map<String,String>> _reminders = [];
for (int i = 0; i < 5; i++) {
Map<String , String> _tempMap = {};
_tempMap.putIfAbsent('M' , () => 'm ' + i.toString());
_tempMap.putIfAbsent('D' , () => 'd : ' + i.toString());
_reminders.add(_tempMap);;
}
print(_reminders.toString());
return;
}
to which the result is as follows
[{M: m 0, D: d : 0}, {M: m 1, D: d : 1}, {M: m 2, D: d : 2}, {M: m 3, D: d : 3}, {M: m 4, D: d : 4}]
As far as I understand, these scenarios should give similar results. Also in my use case scenario 2 is the correct way as it gives me the result that I want. Please note the above examples have been changed to similify the question. The usage in my original code is much more complex.
Dart, like many other programming languages including java, stores objects as reference, and not contiguous memory blocks. In the first case, in all the iterations of the loop, you have added the same Map using the _reminders.add(_tempMap). Your intuition that "Everytime I add the Map, a copy is created of the current state of Map and that copy is appended to the list" is incorrect.
From my understanding, both are different
The problem is with _tempMap.clear(); in the SCENARIO 1. You have used the global variable for map object and when you apply clear inside the for loop all the previously added entries will be cleared and map becomes empty.
when i = 0 => {} => clear() => all entries will be cleared => New item inserted.
when i = 1 => {"Item inserted in 0th iteration"} => clear() => all entries will be cleared => New item inserted.
So for every iteration map is cleared and holds only last iterated value. After for loop is completed it contains only the last iterated value(i=4) since we are clearing the global map variable every time when a new iteration starts.
EDIT :
You can print the map values inside the for loop and can check yourself.
for (int i = 0; i < 5; i++) {
print('\n $i => ${_tempMap} \n');

RethinkDB Multiple emits in Map

I've been trying out RethinkDB for a while and i still don't know how to do something like this MongoDB example:
https://docs.mongodb.com/manual/tutorial/map-reduce-examples/#calculate-order-and-total-quantity-with-average-quantity-per-item
In Mongo, in the map function, I could iterate over an array field of one document, and emit multiple values.
I don't know how to set the key to emit in map or return more than one value per document in the map function.
For example, i would like to get from this:
{
'num' : 1,
'lets': ['a','b,'c']
}
to
[
{'num': 1, 'let' : 'a' },
{'num': 1, 'let' : 'b' },
{'num': 1, 'let' : 'c' }
]
I'm not sure if I should think this differently in RethinkDB or use something different from map-reduce.
Thanks.
I'm not familiar with Mongo; addressing your transformation example directly:
r.expr({
'num' : 1,
'lets': ['a', 'b', 'c']
})
.do(function(row) {
return row('lets').map(function(l) {
return r.object(
'num', row('num'),
'let', l
)
})
})
You can, of course, use map() instead of do() (in case not a singular object)

Compact way to write a list of lists

I am writing a program that outputs a list of ordered lists of numbers. Say the output is as follows:
[1,1,1];
[1,1,2]
I would like to look at the output by eye and make some sense of it, but my output is hundreds to thousands of lines long. I would like to write the output in the following more compact format: [1,1,1/2], where the slash indicates that in the third slot I can have a 1 or a 2. So, for a longer example, [1/2, 1/3, 5, 8/9] would be the compact way of writing [1,1,5,8];[1,1,5,9];[1,3,5,8]; etc. Can anyone suggest a pseudocode algorithm for accomplishing this?
Edit: All of the lists are the same length. Also, I expect in general to have multiple lists at the end. For example {[1,1,2], [1,1,3], [1,2,4]} should become {[1,1,2/3], [1,2,4]}.
What'd I do is use a hash at each element in the first list. You'd then iterate through the remaining lists, and for each position in the other lists, you'd check against the hash in the first / original list for that index to see if you'd seen it before. So you'd end up with something like:
[1 : {1}, 1: {1, 3}, 5: {5}, 8: {8, 9}]
And then when printing / formatting the list, you'd just print each key in the hash, except you'd use slashes or whatever.
EDIT: Bad Psuedocode (python)(untested):
def shorten_list(list_of_lists):
primary_list = list_of_lists[0]
hash_values = [{} * len(primary_list)]
for i in range(len(list_of_lists)):
current_list = list_of_lists[i]
for j in range(current_list):
num = current_list[j]
if num not in hash_values[j]:
hash_values[j] = j
for i in range(len(hash_values)):
current_dict = hash_values[i]
print primary_list[i]
for key in current_dict:
if key != primary_list[i]:
print '/', key
Here's actual code to sort the lists the way you wanted. But maybe the most useful visualization would be a scatter plot. Import the data into your favorite spreadsheet, and plot away.
$(document).ready( function(){
var numbers = [
[1, 1, 5, 8],
[1, 1, 5, 9],
[1, 3, 5],
[1, 1, 5, 10, 15]];
$('#output').text(JSON.stringify(compactNumbers(numbers)));
});
function compactNumbers(numberlists){
var output = [];
for(var i = 0; i < numberlists.length; i++){
for(var j = 0; j < numberlists[i].length; j++) {
if(!output[j]) output[j] = [];
if($.inArray(numberlists[i][j], output[j]) == -1){
output[j].push(numberlists[i][j]);
}
}
}
return(output);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="output"></div>

In C++ using NaCl how to sort a JSON object by value?

I'm using PicoJSON to handle JSON that I get from JavaScript into C++.
If I have a JSON with keys and values of the form {"val1":3, "val2":4} I can get the value of every specific key like so:
picojson::value v;
const string json2("{\"val1\":3,\"val2\":4}");
int val1 = (int)v.get("val1").get<double>(); // val1 will be equal to 3
int val2 = (int)v.get("val2").get<double>(); // val2 will be equal to 4
The problem is that I have an array of objects coming from JavaScript in the form of JSON that look like [{"name": 3},{"name": 1},{"name": 2}]. So now the code will look like this:
picojson::value v;
const string json1("[{\"name\": 3},{\"name\": 1},{\"name\": 2}]");
I am expected to sort them so the expected output should be:
"[{\"name\": 1},{\"name\": 2},{\"name\": 3}]"
Do I have to use a 'for loop' with a linked list to somehow extract that data to sort it? If so, how?
Maybe this can be extracted using regular expressions? If so, how?
Should the array can be converted into array of arrays in order to sort it? If so, how?
Do I have to build a struct or a vector to get a sortable data structure recognisable by
C++? If so, how?
Note: The number of elements varies - it can be greater/smaller.
EDIT:
Can this task be solved if the data structure is in this form (just like I had with {"val1":3, "val2":4} ) :
{"name3": 3, "name1" : 1, "name2": 2, "name97" : 97, ... }
I am flexible to changing it so that C++ would be able to handle it.
Would it then be possible to traverse every key and sort in by value ? If yes, how to do it?
You can put your data into a vector and sort it.
array arr = v.get<array>();
vector<int> vi;
for (array::const_iterator it = arr.begin(); it != arr.end(); ++it) {
vi.push_back((int)(*it).get("name").get<double>());
}
sort(vi.begin(), vi.end());
stringstream ss;
vector<int>::const_iterator it;
for (ss<<"[", it = vi.begin(); (it+1) != vi.end(); ++it) {
ss<<"{\"name\": "<<(*it)<<"},";
}
ss<<"{\"name\": "<<(*it)<<"}]";
cout<<"Output: "<<ss.str()<<endl;
Here is outputs:
Input: [{"name": 3},{"name": 1},{"name": 2}]
Output: [{"name": 1},{"name": 2},{"name": 3}]