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

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}]

Related

How can I extract values from within a 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

How to get element in specific index from NSMutable dictionary (Swift 3)

I need to get the first element from NSMutable dictionary. I tried to get the element using for loop. but I am not getting the correct element because the Dictionary does not follow order. Is there any way I can get the element?
Here is my code:
for (count, i) in myMutableDict.enumerated() {
if count == 2 {
print(i.key)
}
}
As you know dictionary is un ordered collection Type.
let dictionary:Dictionary = ["YYZ": "Toronto Pearson", "DUB": "Dublin"];
for(index,obj) in dictionary.enumerated() {
print("index- \(index) - Object- \(obj)");
print("key- \(obj.key) - value- \(obj.value)");
}
Enumeration will provide you index and Objects of dictionary as above code says. If you want to work with index then you need to get all keys and keep it sorted so that you can get your key by providing index. And from that key you can get value from dictionary object. Piece of code is given below.
var keyList = Array(dictionary.keys);
keyList = keyList.sorted();
print("keyList \(keyList)");
let keyAtIndex = keyList[1];
print("value = \(dictionary[keyAtIndex]!)");

I need a code which sums different numbers

I got a very difficult assignment as I am new to python, I hope you will be able to help me.
I wrote this code:
def hours_per_student(student_course,course_hours):
new={}
for key in student_course.keys():
for val in student_course.values():
for m in range(len(val)):
if not new.has_key(key):
new[key]=course_hours[val[m]]
else:
new[key]=new[key]+course_hours[val[m]]
return new
for these dictionaries:
student_course = {'rina' : ['math', 'python'], 'yossi' : ['chemistry', 'biology'], 'riki' : ['python']}
course_hours = {'math' : 4, 'python' : 4, 'chemistry' : 6, 'biology' : 5}
And I need to get this:
hours_per_student(student_course, course_hours)
to return this:
{'rina': 8, 'yossi': 11, 'riki': 4}
But I keep getting identical numbers for each key.
You shouldn't be iterating over .values() if you're already iterating over .keys(), just use the key to get the value. Or where you have for m in len(val), just do for m in val and then reference m instead of val[m](the naming here stinks but I discuss that later). Python is much better at iteration than that. For instance, instead of the line
for val in student_course.values():
you should try something like
for courses in student_course[key]:
for course in courses:
if key not in new:
new[key] = course_hours[course]
else:
new[key] += course_hours[course]
Naming your variables intelligently will make it easier for you to keep track of what's happening. For example, each value in student_course is a list of courses, so you should name it that, not something ambiguous like val. Similarly, each element in courses is the name of a course, so name it as such.
Here you go:
solution = {student: sum([hours.get(course, 0) for course in s_courses]) for student, s_courses in student_course.items()}
Here are the things I found lacking in your code:
When iterating over your students, you could have just created a key for each of them, and then add the hours per course.
Naming variables so you understand what they mean is confused, refrain from using new, key or val.
You don't have to use keys() function, iterating a dictionary using for key in dictionary works the same way.
Here's a fixed code snippet:
def hours_per_student(students, course_hours):
total_hours = {}
for student in students:
courses = students[student]
total_hours[student] = 0
for course in courses:
total_hours[student] += course_hours[course]
return total_hours

How to compare pairs by other field only in c++?

Im having this issue with comparing pairs. I want use find() to my vector which contains pairs like this:
vector<pair<PersonID, Cost>> friendlist;
PersonID and Cost are both just regular ints. And the problem here is that I want to specifically use the find() just on the PersonID, I'm not interested on the Cost.
if(friendlist.begin(), friendlist.end(), std::make_pair(toid, Cost)) !=
friendlist.end() )
toid here is the id I want to look for within the vector. So what I should do with the other field that make_pair requires?
std::find_if(friendlist.begin(), friendlist.end(),
[=](const std::pair<PersonID, Cost>& elem) {
return elem.first == toid;
});

Using jopendocument with coldfusion/railo, how to add table row?

I'm using jopendocument 1.2 with Railo 3.3.1.000
from http://www.jopendocument.org/start_text_2.html
List<Map<String, String>> months = new ArrayList<Map<String, String>>();
months.add(createMap("January", "-12", "3"));
months.add(createMap("February", "-8", "5"));
months.add(createMap("March", "-5", "12"));
months.add(createMap("April", "-1", "15"));
months.add(createMap("May", "3", "21"));
template.setField("months", months);
How to write that code in cfml, or anyone have experience with jopendocument to add row in odt template file with cfml?
List<Map<String, String>> months = new ArrayList<Map<String,
String>>();
In CF terms, that code creates an array of structures. Because java is strongly typed the code uses generics to indicate what type of objects each one contains
List< Map<...> > // Array containing structures
Map< String, String > // Structure containing "String" values
Fortunately CF arrays are java.util.List objects internally and structures are java.util.Map objects. So you only need to create a CF array of structures with the proper keys and values. Then pass the array into template.setField(...).
I was not sure which keys to use in the structure, so I downloaded the "test.odt" template from jOpenDocument-template-1.2.zip. It revealed each structure should contain three (3) keys, one for each column in the table: name, min, max. As long as you populate the structures with strings, this should work:
// Create an array of structures. Each structure represents a table row.
// The key names for columns 1-3 are: "name", "min", "max"
months = [
{name="January", min="-12", max="3"}
, {name="February", min="-8", max="5"}
, {name="March", min="-5", max="12"}
, {name="April", min="-1", max="15"}
, {name="May", min="3", max="21"}
, {name="June", min="5", max="32"}
];
// populate table rows
template.setField("months", months);