Create array and object in a loop - C - arrays

I'm following this tutorial and library on how to work with JSON in C.
https://linuxprograms.wordpress.com/2010/08/19/json_object_new_object/
I have to work on already developed code, so I cannot change library etc..
here's the code I need to devel; basically I need to create a JSON file with different varName, and fill it with arrays ( each varName has it own array ):
#include <json/json.h>
#include <stdio.h>
int main() {
/*Creating a json object*/
json_object *jobj = json_object_new_object();
/*Creating a json array*/
json_object *jarray = json_object_new_array();
json_object *jarray2 = json_object_new_array();
/*Creating json strings*/
json_object *jstring1 = json_object_new_string("10");
int j = 0;
char num[5];
char num2[5];
for (j = 0; j < 3; j++) {
sprintf(num, "%d", j);
printf("num % s\n", num);
jstring1 = json_object_new_string(num);
json_object_array_add(jarray, jstring1);
sprintf(num2, "%d", j + 50);
printf("num2 % s\n", num2);
jstring1 = json_object_new_string(num2);
json_object_array_add(jarray2, jstring1);
}
/*Form the json object*/
char *varName[] = { "categories", "stories" };
/*what if I have N i.e. 1000 varName element ???
how to put this in a loop
varName[i], could have different values */
json_object_object_add(jobj, varName[0], jarray);
json_object_object_add(jobj, varName[1], jarray2);
...
//json_object_object_add(jobj, varName[N], jarrayN); ?? how to do this in a loop ??
/*Now printing the json object*/
printf("The json object created: %s\n", json_object_to_json_string(jobj));
}
this print:
The json object created: { "categories": [ "0", "1", "2" ], "stories": [ "50", "51", "52" ] }
Which is fine, but how to do this in a loop statement?
I could have many varName elements, and each element has an individual array with different values.
Of course I cannot create N *jarray1 to *jarrayN and to the same with , because I do not know N from the beginning.
json_object_object_add(jobj, varName[0], jarray);
json_object_object_add(jobj, varName[N], jarrayN);
Hope my question is clear

Are you maybe looking for something like this?
#include <json-c/json.h>
#include <stdio.h>
#include <string.h>
static json_object *build_array(const char *var_name) {
printf("Building array for %s...\n", var_name);
json_object *array = json_object_new_array();
for (int j = 0; j < strlen(var_name); j++) {
char num[8];
sprintf(num, "%d", j);
json_object_array_add(array, json_object_new_string(num));
}
return array;
}
int main() {
json_object *root_obj = json_object_new_object();
// since we might not know the length of this array beforehand,
// a NULL string shall denote the last element.
char *var_names[] = {"categories", "stories", "cats", "dogs", NULL};
for (char **var_name_ptr = var_names; *var_name_ptr; var_name_ptr++) {
char *var_name = *var_name_ptr;
json_object *array = build_array(var_name);
json_object_object_add(root_obj, var_name, array);
}
printf("The json object created: %s\n", json_object_to_json_string(root_obj));
json_object_put(root_obj); // Release the root object
}
The output is
Building array for categories...
Building array for stories...
Building array for cats...
Building array for dogs...
The json object created: { "categories": [ "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" ], "stories": [ "0", "1", "2", "3", "4", "5", "6" ], "cats": [ "0", "1", "2", "3" ], "dogs": [ "0", "1", "2", "3" ] }

Related

C printing values of array with pointer values to a char

typedef struct {
char* value;
char* type;
} CARD;
CARD cards[52];
void initializeCards() {
char types[4][10] = {"Spade", "Club", "Hearts", "Diamonds"};
char values[13][1] = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "B", "D", "K"};
for (int i = 0; i < 4; i++) {
for (int e = 0; e < 13; e++) {
cards[i*13 + e].type = types[i];
cards[i*13 + e].value = values[e];
}
}
//This prints all sorts of weid characters.
for (int i=0; i<52; i++) {
printf("%s %s\n", cards[i].type, cards[i].value);
}
}//initializeCards.
I'm trying to make an array containing a deck of cards, but when I try to print the values
it prints all sorts of weird characters.
I tried using %s, %d, %c
I also tried using *cards[i].type or &cards[i].type
all without success.
What am I doing wrong?
Your array values doesn't have enough elements to store the terminating null-character, but you are trying to print that as strings (sequences of characters terminated by a null-character) later.
Allocate enough elements so that the array can hold terminating null-characters.
Wrong line:
char values[13][1] = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "B", "D", "K"};
Corrected:
char values[13][3] = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "B", "D", "K"};

Get the existing intersections between multiple object arrays

I have a couple of arrays which have some same ids. What I want to achieve is get the intersections between the arrays in plain javascript, no libraries. If there is a match of Ids and arraypicklist values are not equal between 2 or more arrays I should get an array with the matching Ids.
Below is my example which I tried but this ends up with no ids where I expect at least 1 match. In this case Id:123 as in the first and second array there is a match. So I would expect
intersection = [{"Id":"123","arrayPicklist":"Categorie__c"},{"Id":"123","arrayPicklist":"Regio__c"}];
fiddle:https://jsfiddle.net/ozckc0tw/4/
var buckets = [[{"Id":"123","arrayPicklist":"Categorie__c"}],
[{"Id":"123","arrayPicklist":"Regio__c"}],
[{"Id":"124","arrayPicklist":"Categorie__c"}],
[{"Id":"123","arrayPicklist":"Regio__c"},{"Id":"125","arrayPicklist":"Regio__c"},{"Id":"123","arrayPicklist":
"Regio__c"},{"Id":"126","arrayPicklist":"Regio__c"}]]
function IntersectionByKey(key) {
var i,
j,
k,
ret = [],
item,
args = [].slice.call(arguments, 1);
args.sort(function(a, b) {return a.length - b.length});
i:for(i=0; i<args[0].length; i++) {
item = [Object.assign(args[0][i], {})];
j:for(j=1; j<args.length; j++) {
for(k=0; k<args[j].length; k++) {
if(key in args[0][i] && args[0][i][key] == args[j][k][key]){
item.push(Object.assign(args[j][k], {}));
continue j;
}
}
continue i;
}
ret.push(item);
}
return ret;
}
var key = 'Id';
var intersection = IntersectionByKey.apply(null, [key].concat(buckets));
console.log('intersection '+JSON.stringify(intersection))
Done,Sorry, but I did not looked out your code, I tried my logic with your requirements, You can use it.
my logic
var buckets = [
[{
"Id": "123",
"arrayPicklist": "Categorie__c"
}],
[{
"Id": "123",
"arrayPicklist": "Regio__c"
}],
[{
"Id": "124",
"arrayPicklist": "Categorie__c"
}],
[{
"Id": "123",
"arrayPicklist": "Regio__c"
}, {
"Id": "125",
"arrayPicklist": "Regio__c"
}, {
"Id": "123",
"arrayPicklist": "Regio__c"
}, {
"Id": "126",
"arrayPicklist": "Regio__c"
}]
],
intersection = [{
"Id": "123",
"arrayPicklist": "Categorie__c"
}, {
"Id": "123",
"arrayPicklist": "Regio__c"
}];
var resArray = [];
for (var j = 0; j < intersection.length; j++) {
for (var i = 0; i < buckets.length; i++) {
for (var k = 0; k < buckets[i].length; k++) {
if (buckets[i][k].Id == intersection[j].Id && buckets[i][k].arrayPicklist == intersection[j].arrayPicklist) {
resArray.push(buckets[i][k]);
}
}
}
}
console.log(resArray);

Create arrays from 1D array after every nth occurrence using Angular JS

I have an array which looks like this
Array[20]
0 : "2"
1 : "3"
2 : "4"
3 : "5"
4 : "6"
5 : "7"
6 : "8"
7 : "9"
8 : "10"
9 : "11"
10: "12"
11: "13"
12: "14"
13: "15"
14: "16"
15: "17"
16: "18"
17: "19"
18: "20"
19: "12"
Now I want to create arrays after every 4th occurrence like this
First Array
0 : "2"
1 : "6"
2 : "10"
3 : "14"
4 : "18"
Second Array
0 : "3"
1 : "7"
2 : "11"
3 : "15"
4 : "19"
and so on...
Yet I have written this code
for (var i = 0; i < $scope.data.effort.length; i = i+ 4) {
efforts.push( $scope.data.effort[i]);
};
From above code I am getting only first array what should I need to do to get remaining arrays. Please help
All you need is to run an extra loop outside that which handles your starting index. LIke this:
efforts = []
for (var j = 0; j < arr.length / 4; j++) {
efforts[j] = []
for (var i = j; i < arr.length; i = i + 4) {
efforts[j].push(arr[i]);
};
console.log(efforts[j])
}
Here's working example: (simplified in JS, without $scope and all)
var arr = [
"2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14",
"15", "16", "17", "18", "19", "20", "12"
]
efforts = []
for (var j = 0; j < arr.length / 4; j++) {
efforts[j] = []
for (var i = j; i < arr.length; i = i + 4) {
efforts[j].push(arr[i]);
};
console.log(efforts[j])
}
Or, interestingly, you can use the beast, I mean, reduce to achieve the same. :)
var arr = [
"2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14",
"15", "16", "17", "18", "19", "20", "12"
]
efforts = arr.reduce(function(arr, cur, curIndex) {
arr[curIndex % 4] = arr[curIndex % 4] || [];
arr[curIndex % 4].push(cur);
return arr
}, [])
console.log(efforts)
Another simple way with array filter:
var originalArray =["2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20","21"];
var firstArray = originalArray.filter((el, index) => (index%4 === 0));
var secondArray = originalArray.filter((el, index) => (index%4 === 1));
and so on

How to delete brackets from array, but keep quotes

I have an array, with even number of elements:
var peoples = [
["1", "Adam", "Jones"],
["2", "Michael", "Jordan"],
["3", "Frank", "Forman"],
["4", "John", "Bryant"],
["5", "James", "Johnson"],
["6", "Vincent", "Carter"],
["7", "George", "Williams"],
["8", "Brandon", "Clarkson"]
];
and I’m trying to merge arrays in pairs by following pattern:
["1", "Adam", "Jones", "2", "Michael", "Jordan"]
["3", "Frank", "Forman","4", "John", "Bryant"]
etc.
I have a problem with following code:
for (var i = 0; i < peoples.length / 2; i++) {
array1[i].push(array2[i].join(","))
}
which is generating that result:
["1","Adam","Jones","2,Michael,Jordan"]
and it should be:
["1","Adam","Jones","2","Michael","Jordan"]
Here is my jsfiddle https://jsfiddle.net/danny3b/k5hza694/
I've already done it by myself. I was looking for concat() method.
for (var i = 0; i < peoples.length / 2; i++) {
array1[i] = array1[i].concat(array2[i])
}
https://jsfiddle.net/danny3b/rfju9949/
What join does is concatenating all of the strings in the array. Instead of that, you should insert all of the elements in there.

How to create a random shuffle from 2D array

Im trying to create a random function from a given 2d array. The code should be able to shuffle cards based on information in array.
string DeckCards [6][6] = ///determine size of deck //deck1
{
{"1A", "1B", "1C", "1D", "2A", "2B"},
{"2C", "2D", "3A", "3B", "3C", "3D"},
{"4A", "4B", "4C", "4D", "1A", "1B"},
{"1C", "1D", "2A", "2B", "2C", "2D"},
{"3A", "3B", "3C", "3D", "4A", "4B"},
{"4C", "4D", " ", " ", " ", " "}
};
void randomize(string DeckCards[6][6],int n)
{
srand( time(NULL) );
for(int i = n-1; i > 6; i--)
{
int j = rand() %(4+1);
swap(&DeckCards[i],[j]);
}
}
the error is too large to include

Resources