I'm getting error: incompatible integer convergion passing char when using strcmp and I don't understand why. If alfabet[k] and word[i] are the same types, then why does it give me an error in the second one?
Is that error not supposed to appear when one of the variables is not a string?
#include <stdlib.h>
#include <ctype.h>
#include <cs50.h>
#include <stdio.h>
#include <string.h>
// Points assigned to each letter of the alphabet
int POINTS[] = {1, 3, 3, 2, 1, 4, 2, 4, 1, 8, 5, 1, 3, 1, 1, 3, 10, 1, 1, 1, 1, 4, 4, 8, 4, 10};
int compute_score(string word);
int main(void)
{
// Get input words from both players
string word1 = get_string("Player 1: ");
string word2 = get_string("Player 2: ");
// Score both words
int score1 = compute_score(word1);
int score2 = compute_score(word2);
// TODO: Print the winner
if (score1 > score2) {
printf("The winner is Player 1!");
}
else if (score1 < score2) {
printf("The winner is Player 2!");
}
else {
printf("Both players have the same score, so it's a draw!");
}
}
int compute_score(string word)
{
int sum = 0;
for (int i = 0; i == strlen(word); i++) {
if (islower(word[i])) {
word[i] = toupper(word[i]);
}
string alfabet[] = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M",
"N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};
for (int k = 0; k < 26; k++){
if (strcmp(alfabet[k], word[i]) == 0) {
letter_postion = k;
break;
}
}
int first_score = POINTS[letter_position];
for (int j = 0; j < strlen(word); i++) {
sum = sum + first_score;
}
}
}
Related
I'm using discord.js and I want to create a "server" with passcode. I want the passcode to be 6 letters long, so far I can only do one.
It has to be random as well. Like "ZSHWJK" Instead of "AAAAAA"
Code:
var serverPasscode = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]
module.exports = {
name: "createserver",
description: "Creates a server",
run(message, args, client){
const newServer = new MessageEmbed()
.setTitle(`${message.author.name}'s server`)
.setFooter(`${serverPasscode[Math.floor(Math.random() * serverPasscode.length)]}`)
message.channel.send(newServer);
}
};
Right now this can only return one element which is not what I want.
You could use a for loop and create a function such as this:
function makeGuildPassword(length) {
var result = ''; // create empty string that you will add random characters to
var characters = // list of characters (you can change this however you want)
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
for (var i = 0; i < length; i++) { // create a loop
// add a random character to the string; restart the loop
result += characters.charAt(Math.floor(Math.random() * characters.length));
}
return result;
};
console.log(makeGuildPassword(6))
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 have the array ["a", "b", "c", "d", "e"]
I need a function to shift abc to the end of the array - ["d", "e", "a", "b", "c"]
function rotate(a, n) {
// The modulo here is a performance optimization... rotating by the length of the array has no effect. E.g. in this example, rotating 8 is the same as rotating 3.
for (var i = 0; i < n % a.length; i++) {
a.push(a.shift());
}
}
var a = ["a", "b", "c", "d", "e"];
rotate(a, 3);
console.log(a);
// Output:
// [ 'd', 'e', 'a', 'b', 'c' ]
EDIT
Non-destructive version using slice:
function rotate(a, n) {
n %= a.length;
return a.slice(n).concat(a.slice(0, n));
}
var a = ["a", "b", "c", "d", "e"];
console.log(rotate(a, 3));
// Output:
// [ 'd', 'e', 'a', 'b', 'c' ]
EDIT2
In response to the follow-up question in a comment, here's how you would copy the elements instead of moving them. (This is the non-destructive version.)
function copy(a, n) {
n %= a.length;
return a.concat(a.slice(0, n));
}
var a = ["a", "b", "c", "d", "e"];
console.log(copy(a, 3));
// Output:
// [ 'a', 'b', 'c', 'd', 'e', 'a', 'b', 'c' ]
Or here's an in-place version of copy:
function copy(a, n) {
for (var i = 0; i < n % a.length; i++) {
a.push(a[i]);
}
}
var a = ["a", "b", "c", "d", "e"];
copy(a, 3);
console.log(a);
// Output:
// [ 'a', 'b', 'c', 'd', 'e', 'a', 'b', 'c' ]
The only way I can think of is after the first sorting based on rating, I group all the names which have same rating together and sort that group based on quantity. It is a little complicated and I guess I need to implement a function to do it. Is there any shorter way to do it? Thanks.
// **Expected result**
// sortedNameArray = ["b", "e", "a", "f", "c", "g", "d", "h"]
// sortedRatingArray = [ 5, 5, 4, 3, 3, 3, 2, 2 ]
// sortedQuantityArray = [ 4, 3, 3, 5, 3, 2, 4, 3 ]
let nameArray = ["a", "b", "c", "d", "e", "f", "g", "h"]
let ratingArray = [ 4, 5, 3, 2, 5, 3, 3, 2]
let quantityArray = [ 3, 4, 3, 4, 3, 5, 2, 3]
let firstNameArray = Array(zip(nameArray, ratingArray)).sort { $0.1 > $1.1 }.map { $0.0 }
let firstRatingArray = Array(zip(ratingArray, ratingArray)).sort { $0.1 > $1.1 }.map { $0.0 }
let firstQuantityArray = Array(zip(quantityArray, ratingArray)).sort { $0.1 > $1.1 }.map { $0.0 }
// first sorting based on rating
firstNameArray // = ["b", "e", "a", "c", "f", "g", "d", "h"]
firstRatingArray // = [5, 5, 4, 3, 3, 3, 2, 2]
firstQuantityArray // = [4, 3, 3, 3, 5, 2, 4, 3]
// second sorting based on quantity.
Rather than maintaining three arrays that require synchronization, just maintain a single array of a simple struct.
struct Entry {
let name: String
let rating: Int
let quantity: Int
}
let entries = [ Entry(name: "a", rating: 4, quantity: 3),
Entry(name: "b", rating: 5, quantity: 4),
Entry(name: "c", rating: 3, quantity: 3),
Entry(name: "d", rating: 2, quantity: 4),
Entry(name: "e", rating: 5, quantity: 3),
Entry(name: "f", rating: 3, quantity: 5),
Entry(name: "g", rating: 3, quantity: 2),
Entry(name: "h", rating: 2, quantity: 3),
]
let sortedEntries = entries.sort { lhs, rhs in
if lhs.rating != rhs.rating {
return lhs.rating > rhs.rating
}
return lhs.quantity > rhs.quantity
}
With this, your algorithms should become trivial and require less computation.
If you require separate arrays at some point, it's trivial to unzip it (though I seldom find this necessary in practice):
let nameArray = entries.map { $0.name }
I have an array of chars that looks like this:
chars = ["x", "o", "o", "x", "x", "o", "o", "x", "x", "x", "o", "o"]
I need to get the number of consecutive chars and the index of that char. It should look like this:
[
{ index: 0, length: 1 }, # "x"
{ index: 1, length: 2 }, # "o", "o"
{ index: 3, length: 2 }, # "x", "x"
{ index: 5, length: 2 }, # "o", "o"
{ index: 7, length: 3 }, # "x", "x", "x"
{ index: 10, length: 2 } # "o", "o"
]
Is there an easy way to achieve this?
Not sure if you'd call this an easy way, but here's a one-line way of doing it. Resulting array is of the form [index, length].
chars.each_with_index.chunk {|i, _| i}.map {|_, y| [y.first.last, y.length]}
#=> [[0, 1], [1, 2], [3, 2], [5, 2], [7, 3], [10, 2]]
Two others ways of doing it:
Use Emumerable#slice_when (v.2.2+)
count = 0
arr = chars.slice_when { |a,b| a != b }.map do |arr|
sz = arr.size
h = { index: count, length: sz }
count += sz
h
end
#=> [{:index=>0, :length=>1}, {:index=>1, :length=>2}, {:index=>3, :length=>2},
# {:index=>5, :length=>2}, {:index=>7, :length=>3}, {:index=>10, :length=>2}]
Use a regex with a backreference
count = 0
arr = chars.join.scan(/((.)\2*)/).map do |run, _|
sz = run.size
h = { index: count, length: sz }
count += sz
h
end
#=> [{:index=>0, :length=>1}, {:index=>1, :length=>2}, {:index=>3, :length=>2},
# {:index=>5, :length=>2}, {:index=>7, :length=>3}, {:index=>10, :length=>2}]