I've looked around and tried different syntax's for this but I can't seem to get it to work. I know this is elementary, but it's something that shouldn't take too long to figure out.
I have the character array...
char *roster[2][14] = {
{"13", "10", "24", "25", "15", "1", "00", "4", "11", "23", "22", "32", "3", "35"},
{"Isaiah Briscoe", "Jonny David", "EJ Floreal", "Dominique Hawkins", "Isaac Humphries", "Skal Labissiere", "Marcus Lee", "Charles Matthews", "Mychal Mulder", "Jamal Murray", "Alex Poythress", "Dillon Pulliam", "Tyler Ulis", "Derrick Willis"}
};
Then I'm generating a random element from that array...
random = rand() % 14;
printf("What is %s 's number?", roster[2][random]);
Then I try to print it out, but it fails...
printf("What is %s 's number?", roster[2][random]);
It outputs
What is (null) 's number?
and lldb shows that the printf statement jumps into...
libsystem_c.dylib`strlen:
-> 0x7fff9a596d32 <+18>: pcmpeqb (%rdi), %xmm0
0x7fff9a596d36 <+22>: pmovmskb %xmm0, %esi
0x7fff9a596d3a <+26>: andq $0xf, %rcx
0x7fff9a596d3e <+30>: orq $-0x1, %rax
Array index starts from 0.
For char *roster[2][14];, the possible indices are
roster[0][random];
roster[1][random];
Arrays in c start at 0, so if you declare:
char *roster[2]
Then you can only reference roster[0] and roster[1].
printf("What is %s 's number?", roster[2][random]);
You access index out of bound invoking undefined behaviour .
Because you can have indices roster[0][random] and roster[1][random] not roster[2][random] because it is declared as -
char *roster[2][14] = {
{"13", "10", "24", "25", "15", "1", "00", "4", "11", "23", "22", "32", "3", "35"},
{"Isaiah Briscoe", "Jonny David", "EJ Floreal", "Dominique Hawkins", "Isaac Humphries", "Skal Labissiere", "Marcus Lee", "Charles Matthews", "Mychal Mulder", "Jamal Murray", "Alex Poythress", "Dillon Pulliam", "Tyler Ulis", "Derrick Willis"}
};
You can print these -
printf("What is %s 's number?", roster[1][random]);
Or -
printf("What is %s 's number?", roster[0][random]);
Related
For example, we can replace “a” or “A” with # and get “с#t” instead of “cat”. Letters to replace: a - #; i - 1; s - $; o - 0; t - +
Using a for-in or forEach() methods.
I used this option but it's easy and not flexible.
func replaceOld(characters: String) -> String {
let newChars = characters.replacingOccurrences(of: "a", with: "#")
.replacingOccurrences(of: "i", with: "1")
.replacingOccurrences(of: "s", with: "$")
.replacingOccurrences(of: "o", with: "0")
.replacingOccurrences(of: "t", with: "+")
return newChars
}
replaceOld(characters: "Swift is awesome")
print Sw1f+ 1$ #we$0me
I created an array and I want to loop through and change the values.
func replaceOld(characters: String) -> String {
var arrayOfChars = [("a", "#"), ("i", "1"), ("s", "$"), ("o", "0"), ("t", "+")]
....
}
But I still don't understand how to change the values and pass it to the argument characters.
Maybe something like this?
let myString = "Hello World"
let characterMapping: [Character: Character] = [
"e": "3",
"o": "0"
]
let newString = myString.map { character in
return characterMapping[character] ?? character
}
// Hello World -> H3ll0 W0rld
You could bake all this into a function, or even parameterize the mapping. Another thing to keep in mind is going to be capitalization, diacritics, localization, etc.
I have the following JSON object, from which I need to retrieve values of certain keys.
For example, in outer JSON object, I need only "timestamp" and "type", next from a nested "meta" object I need only "version", and from nested "payload" I want fields "reason", "type" and "condition" from its nested object "data"
{
"timestamp": "1568961295627",
"type": "test",
"namespace": "internal",
"meta": {
"version": "2.0-test",
"id": "123"
},
"payload": {
"data": {
"reason": "user_request",
"type": "asd",
"condition": "bad"
},
"contentType": "application/json"
}
}
I wrote a function to retrieve such data:
void log_values(json_t *data) {
json_t *obj = NULL;
json_t *nested = NULL;
syslog(LOG_INFO, "%s: ", json_string_value(json_object_get(data, "timestamp")));
syslog(LOG_INFO, "%s: ", json_string_value(json_object_get(data, "type")));
obj = json_object_get(data, "meta");
syslog(LOG_INFO, "%s: ", json_string_value(json_object_get(obj, "version")));
obj = json_object_get(data, "payload");
nested = json_object_get(obj, "data");
syslog(LOG_INFO, "%s: ", json_string_value(json_object_get(nested, "reson")));
syslog(LOG_INFO, "%s: ", json_string_value(json_object_get(nested, "type")));
syslog(LOG_INFO, "%s: ", json_string_value(json_object_get(nested, "condition")));
}
However, the code looks repetitive and I'm wondering if there is any way to generalize it?
The first thing which came to mind is to create a jagged array of pointers to keys needed for each stage, and then walk through the array and retrieve only certain keys on certain nesting level, for example:
char *nested0 = {"timestamp", "type"};
char *nested1 = {"anomaly", "version"};
char *nested2 = {"reason", "type", "condition"};
char *(*keys[])[] = { &nested0, &nested1, &nested2 }
But, this solution does not solve problem regarding where to store key names, which point to nested JSONs (e.g "meta, payload, data").
So, the question is: How to generalize the aforementioned code and what data structure should I use to store names of keys holding a json object and keys for which I need to get values.
Take a look at jsmn, it should fit your needs : https://github.com/zserge/jsmn
exemple of what you could do with jsmn :
[user#machine ~]$ ./json_parser_with_keys test.json timestamp type meta/version
timestamp=1568961295627
type=test
meta/version=2.0-test
[user#machine ~]$ ./json_parser_full test.json
/timestamp=1568961295627
/type=test
/namespace=internal
/meta/version=2.0-test
/meta/id=123
/payload/data/reason=user_request
/payload/data/type=asd
/payload/data/condition=bad
/payload/contentType=application/json
[user#machine ~]$
I have an array of strings, I need to compare this to another array of strings, but they may be in a different order. What's the best way to compare the two arrays?
This is what I have so far, just wondering if there is a simpler / more efficient way I'm missing.
func unorderedEqual(first, second []string) bool {
if len(first) != len(second) {
return false
}
for _, value := range first {
if !contains(value, second) {
return false
}
}
return true
}
func contains(needle string, haystack []string) bool {
for _, matchValue := range haystack {
if matchValue == needle {
return true
}
}
return false
}
Given that you are doing a length check, I'm going to go with the assumption that implies that they are 1:1, just ordered differently.
You can do this in one pass (each) using a map[string]bool to check existence in both. This utilizes the fact that the map returns the zero value of a bool, which is false, when the key is not present.
Disclaimer: Technically this is order O(n)*O(map). The Go Programming Language Specification does not make any performance guarantees for map types.
https://play.golang.org/p/2LUjN5LkXLL
func unorderedEqual(first, second []string) bool {
if len(first) != len(second) {
return false
}
exists := make(map[string]bool)
for _, value := range first {
exists[value] = true
}
for _, value := range second {
if !exists[value] {
return false
}
}
return true
}
If you want to get nit-picky about memory usage, you could save yourself storing a bunch of bools (which is usually negligible, but to each their own) by using a map[string]struct{} (the empty struct), and you just check existence a little differently, as in this example.
https://play.golang.org/p/MjwP_wCtYZV
Set
exists[value] = struct{}{}
Check
if _, ok := exists[value]; !ok {
return false
}
Ideally, this would have been a comment, but the TLDR is it is both more correct and faster to use Husain's sort and compare.
Details.
For anyone looking at the RayfenWindspear answer above (currently highest ranked), at first glance it looks right, but be aware that it does not check for exact equal-ness, but rather only that every element in the second list is in the first list. The converse also needs to be true, but is not checked by this method. Hence it fails this test (bb is repeated).:
assert.False(t, unorderedEqual([]string{"aa", "cc", "bb"}, []string{"aa", "bb", "bb"}))
Of course you can just run it twice to get the correct result, which is only a linear factor
func DoubleUnorderedEqual(a, b []string) bool {
return unorderedEqual(a, b) && unorderedEqual(b, a)
}
The suggestion for the sort-then-check by Husain should possibly be ranked higher, because it is correct, and is also faster for larger lists.
Here's Husain's code in an exported function:
func SortCompare(a, b []string) bool {
if len(a) != len(b) {
return false
}
sort.Strings(a)
sort.Strings(b)
for i, v := range a {
if v != b[i] {
return false
}
}
return true
}
And some tests you can run on it (which it passes)
func TestSortCompare(t *testing.T) {
assert.True(t, SortCompare([]string{"aa"}, []string{"aa"}))
assert.False(t, SortCompare([]string{"aa"}, []string{"bb"}))
assert.False(t, SortCompare([]string{"aa"}, []string{"bb", "cc"}))
assert.True(t, SortCompare([]string{"cc", "bb"}, []string{"bb", "cc"}))
assert.True(t, SortCompare([]string{"aa", "cc", "bb"}, []string{"aa", "bb", "cc"}))
assert.False(t, SortCompare([]string{"aa", "cc", "bb"}, []string{"aa", "bb", "bb"}))
}
And here is some sample benchmarking ....
func getStrings() ([]string, []string) {
a := []string{"a", "foo", "bar", "ping", "pong"}
b := []string{"pong", "foo", "a", "bar", "ping"}
return a, b
}
func BenchmarkSortCompare(b *testing.B) {
s0, s1 := getStrings()
var outcome bool
for n := 0; n < b.N; n++ {
outcome = SortCompare(s0, s1)
}
fmt.Println(outcome)
}
func BenchmarkDoubleUnorderedEqual(b *testing.B) {
s0, s1 := getStrings()
var outcome bool
for n := 0; n < b.N; n++ {
outcome = DoubleUnorderedEqual(s0, s1)
}
fmt.Println(outcome)
}
With the results ...
BenchmarkSortCompare-32 2637952 498 ns/op
BenchmarkDoubleUnorderedEqual-32 3060261 381 ns/op
So running the map method twice is slightly faster at this small size... but add a few more strings and the sort method wins out by a factor of 10. I did not take into account the impact of the degree of disorder in the strings but they are sufficiently disordered it is not an obviously unfair test at first glance.
func getStrings2() ([]string, []string) {
a := []string{"a", "foo", "bar", "ping", "pong", "b", "c", "g", "e", "f", "d", "h", "i", "j", "q", "l", "n", "o", "p", "k", "r", "s", "t", "u", "v", "w", "x", "y", "z"}
b := []string{"pong", "foo", "a", "bar", "ping", "p", "r", "q", "s", "u", "t", "v", "j", "x", "y", "z", "b", "e", "d", "c", "h", "g", "f", "i", "w", "k", "l", "n", "o"}
return a, b
}
func BenchmarkSortCompare2(b *testing.B) {
s0, s1 := getStrings2()
var outcome bool
for n := 0; n < b.N; n++ {
outcome = SortCompare(s0, s1)
}
fmt.Println(outcome)
}
func BenchmarkDoubleUnorderedEqual2(b *testing.B) {
s0, s1 := getStrings2()
var outcome bool
for n := 0; n < b.N; n++ {
outcome = DoubleUnorderedEqual(s0, s1)
}
fmt.Println(outcome)
}
The results:
BenchmarkSortCompare2-32 454641 2797 ns/op
BenchmarkDoubleUnorderedEqual2-32 44420 26714 ns/op
Conclusion - I'll be using Husain's sort and compare ....
Generic, language agnostic:
sort both with fastest available algorithm
iterate over table A and compare with B[currentIndexFromA]
first time you spot difference, you know they hold different data - throw!
you iterated over whole A? - they are the same
I don't know GO, but you seem to be naively searching for each element from A in B. In worst case scenario you get many many iterations over B. Sorting with performant algorithm seems to be way more efficient even though it's additional operation.
I unfortunately will not provide code sample, as I don't know GO.
Using this dedicated package, you would have to use []interface{} instead of []string then proceed as such
package main
import (
"fmt"
"github.com/deckarep/golang-set"
)
func main() {
some := []interface{}{"a", "b", "c"}
other := []interface{}{"a", "b", "d"}
fmt.Println(
mapset.NewThreadUnsafeSetFromSlice(some).
Difference(mapset.NewThreadUnsafeSetFromSlice(other)).Cardinality() == 0,
)
// Output: false
}
You can sort the arrays first and then check by index:
package main
import (
"fmt"
"sort"
)
func main() {
s1 := []string{"first", "second", "third"}
s2 := []string{"third", "first", "second"}
if len(s1) != len(s2) {
fmt.Println("not equal")
}
sort.Strings(s1)
sort.Strings(s2)
for i := 0; i < len(s1); i++ {
if s1[i] != s2[i] {
fmt.Println("not equal")
return
}
}
fmt.Println("equal")
}
Or in playground.
The idea with sorting is that it makes the comparison easier and faster. Sorting and then comparing index-wise is O(n log n), while 2-loop checking takes O(n^2).
I have a kindof complicated file format:
{
"color": [
45,
200,
34
],
"docnum": 5183,
"form": "avoir",
"graph": "jdm.N.flat",
"id": 0,
"lang": "fr",
"neighbors": 17,
"pos": "N",
"pzero": true,
"rank": 1,
"score": 0.0028284271,
"type": 1
},
{
"color": [
45,
200,
34
],
"docnum": 22809,
"form": "argent",
"graph": "jdm.N.flat",
"id": 1,
"lang": "fr",
"neighbors": 65,
"pos": "N",
"pzero": false,
"rank": 2,
"score": 0.0028284271,
"type": 1
},
This kind of list goes on, for hundreds of entries. I would like to read in the variable numbers, and a string (docnum, form, id, neighbors, rank, score) so i created a format string for this kind of input:
main(){
FILE* in=fopen("fr.N.bien2","r");
int maxwords=100;
int maxstringlen=100;
char* nodes=malloc(sizeof(char)*maxstringlen*maxwords);
if(!nodes){printf("Nodes couldn't be allocated!\n");}
int i=0;
int* IDs=malloc(sizeof(int)*3*maxwords);
int docnum,nei,rank;
float score;
char* pzero;
while(fscanf(in," { \"color\": [ 45, 200, 34 ], \"docnum\": %i, \"form\": %s \"graph\": \"jdm.N.flat\", \"id\": %i , \"lang\": \"fr\", \"neighbors\": %i , \"pos\": \"N\", \"pzero\": false, \"rank\": %i , \"score\": %f , \"type\" :1 },",&docnum,&nodes[i],&IDs[i],&nei,pzero,&rank,&score))
{
printf("node:%s,ID=%i\n",&nodes[i],IDs[i]);
i++;
}
}
It looks complicated, but it seems to be working, because I get the first instance right. The output is:
>>node:"avoir",,ID=0
However, output stops at that, even though the format is exactly repeating in the file (as you can see in the sample).
Am I missing something important here?
Is there an easier way to read in this kind of data from such a file?
And this complicated format is JSON
As the comments suggest, look for a library instead (they can be found following the previous link) there's many libraries and for different languages as well.
In fact, your question might be already answered here
First off, this is a very broad question, and it might come across as me asking for the community to write my code for me. That is not my intent, but I am so lost, I don't know how to give enough information.
I am attempting to use the cJSON library, written by Dave Gamble,
I found this is very useful to use for my embedded device for JSON parse and composing.
to read in the following JSON array
{
"name": "Jack",
"types":[23,56,78],
"format": {
"type": "rect",
"width": 1920, }
}
.. and parsing the getting the object worked with this method
cJSON *format = cJSON_GetObjectItem(json,"format");
int framerate = cJSON_GetObjectItem(format,"width")->valueint;
but I am not able to parse the key "name" and object simple key value ,
I tried this
cJSON *array = cJSON_GetArrayItem(json,"types");
int value = cJSON_GetArrayItem(format1,1)->valueint;
but did not work, how to parse the array object and simple key value..
Your json is just fine. You can iterate through array of values in cJSON:
cJSON * array = cJSON_GetObjectItem(json, "types");
for (i = 0 ; i < cJSON_GetArraySize(array) ; i++)
{
printf("%d ",cJSON_GetArrayItem(array, i)->valueint);
}
will print
23 56 78
I think JSON element should respect key:value format.
{
"name": "Jack",
"types":[{"type" : 23}, {"type" : 56}, {"type":78}],
"format": {
"type": "rect",
"width": 1920, }
}