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"};
Related
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" ] }
I want to replace all A characters present in an array with 15 using Swift 3.
Example array:
["4", "5", "6", "A", "A", "Q", "A"]
Desired result:
["4", "5", "6", "15", "15", "Q", "15"]
map to the rescue:
var a = ["4", "5", "6", "A", "A", "Q", "A"]
a = a.map({ $0 == "A" ? "15" : $0 })
print(a)// ["4", "5", "6", "15", "15", "Q", "15"]
EDIT: After error screenshot:
You have an array of characters and hence the above code is not working. Also, remember "15" is two characters and not one character. Hence, I have replaced character 'A' with string "15" and mapped it to an array of strings, instead
let player1 = "456AAQA"
var player1Cards = Array(player1.characters) // ["4", "5", "6", "A", "A", "Q", "A"]
var player1CardsStrings = player1Cards.map{$0 == "A" ? "15" : String($0)}
player1CardsStrings // ["4", "5", "6", "15", "15", "Q", "15"]
Tested on Playground.
Because your question is lacking information that you didn't gave at first, here is what you can do.
"for loop": You iterate and replace the value if needed.
That's a logic you could apply on almost all languages.
var array1 = ["4", "5", "6", "A", "A", "Q", "A"]
for index in 0 ... array1.count-1
{
if array1[index] == "A"
{
array1[index] = "15"
}
}
print("array1: \(array1)")
"for each loop": You iterate and replace the value if needed.
That's a logic you could apply on almost all languages (maybe less languages that the previous one)
var array2 = ["4", "5", "6", "A", "A", "Q", "A"]
for (index, object) in array2.enumerated()
{
if object == "A"
{
array2[index] = "15"
}
}
print("array2: \(array2)")
"map": the "map" iterate for you (here is the important part behind the magic), you check the value and replace the value if needed. The $0 represent the "current item".
Here is a specificity.
var array3 = ["4", "5", "6", "A", "A", "Q", "A"]
array3 = array3.map({
if $0 == "A"
{
return "15"
}
return $0
})
print("array3: \(array3)")
"map": the "map" iterate for you, you check the value and replace the value if needed with a ternary if test.
var array4 = ["4", "5", "6", "A", "A", "Q", "A"]
array4 = array4.map({$0 == "A" ? "15" : $0})
print("array4: \(array4)")
I'm gave 4 ways (I've could also have explicit more the map() with explicit closure, from the simplest to the more complicated. We can't know if you don't show your attempts where you are are stucked. Is it for loop? The basic algorithms?
Swift advanced user may be more fond of the last one, but for beginners, it's quite complex and "magic". So when they want to change it a little for a different test, they never know what to do.
Side note: I'm not a Swift developer, more an Objective-C, so it may be lacking of checks. This answers is to show different approaches, how you go from a "verbose" to a less "verbose" code, but that you need to master anyway. Even if you have issue with map(), you can "bypass" it and do it manually.
let values = ["4", "5", "6", "A", "A", "Q", "A"]
let mappedvalues = values.map({ (value: String) -> String in
if value != "A" {
return value
}
return "15"
})
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
I try to sort a String Array with numbers but i dont get the right order.
print(alleTouren) // ["1", "3", "2", "5", "15", "4"]
alleTouren = alleTouren.sorted(by: {$0 < $1})
print(alleTouren) // ["1", "15", "2", "3", "4", "5"]
I also tried alleTouren.sort(by:<) and alleTouren.sort() but i always get back the 15 too early. What i am doing wrong?
Since all strings can be converted to Int add the conversion to the closure.
var alleTouren = ["1", "3", "2", "5", "15", "4"]
alleTouren = alleTouren.sorted(by: { Int($0)! < Int($1)! })
Alternatively use the compare function of String with numeric option which is probably more efficient.
alleTouren = alleTouren.sorted(by: { $0.compare($1, options:.numeric) == .orderedAscending} )
The problem is that you seem to be saying you want to sort them as though they are numbers, but they are strings, so "1", "15", "2"... is correct. You could try converting $0 and $1 to integers and comparing these.
I'm not a Swift expert, but this seems to work:
alleTouren = alleTouren.sorted{let s0 = Int($0)
let s1 = Int($1)
return s0! < s1!}
I am trying to combine two two arrays to make a full deck of cards that looks like so:
[{card: "A", suit: "d"}, {card: "A", suit: "c"}, {card: "A", suit: "s"}, {card: "A", suit: "h"}, {card: "2", suit: "d"}.....]
.... this is what I have so far:
function newDeck(ranks, suits){
var ranks = [ "A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"]
var suits = ["d", "c", "s", "h"]
var deck= []
for (i = 0; i < suits.length; i++) {
for (j = 0; j < ranks.length; j++) {
this.deck[ranks.length*i+j] = new Card(ranks[j], suits[i]);
}
} console.log(newDeck)
}
Using Array.forEach you can do the following:
var ranks = [ "A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"];
var suits = ["d", "c", "s", "h"];
var deck= [];
suits.forEach(function(suit){
ranks.forEach(function(rank){
deck.push(new Card(rank, suit));
})
});
EDIT: and in case you haven't written the Card method yet:
function Card(rank, suit){
this.card = rank;
this.suit = suit;
}
If you combine the two arrays you will have an array:
["A","2","3","4","5","6","7","8","9","10","J","Q","K","d","c","s","h"]
which does not represent a full deck of card, whereas using an embedded for loop to print out card as you are now will so I don't think you just want to append one array to the other. Can you provide more context on what you want to do with the array?
However, to answer your question: if you want to append two arrays you can use:
var appendedArray = ranks.concat(suits);
which will result in the aforementioned array above
pertaining to your updated question: you are called "new Card(ranks[j], suits[i]);" have you made a Card constructor so that this is valid? if so, the code should be correct if the constructor matches how you are using it. Posting the code for the constructor would be helpful along with an update of what issue you are facing