text stringlengths 1 2.12k | source dict |
|---|---|
c++, object-oriented
Title: Data format conversion program code
Question: This program converts a proprietary text data format to the conf or ini file format. I have some questions on the code:
Is the high level code design coherent and easy to read?
Does the code use 'good code design practice'?
How could this code be improved?
The input format is a filename to describe the 'subject' of the key value pairs in the file. The filename is mapped to a [section] in the ini file format.
The input files contain key value pairs separated by a colon.
generate.sh can be used to create the input files.
generate.sh:
#!/bin/bash
if [ $# -ne 1 ]; then
echo "Usage: generate <directory>"
exit 1
fi
directory=$1
lastchar=${directory: -1}
if [ $lastchar != '/' ]; then
directory="${directory}/"
fi
printf "SPORT : AX3\nNEWS : Sky7\nCOMEDY : Art5\n" > ${directory}channels.txt
printf "ADDRESS : 192.168.4.33\nPORT : 5088\n" > ${directory}server.txt
Implementation code (main.cpp):
#include <iostream>
#include <string>
#include <filesystem>
#include <fstream>
#include <sstream>
#include <unordered_map>
#include <vector>
class config {
public:
using keyvalues = std::unordered_map<std::string, std::string>;
config() {}
config(std::istream& istrm) {
parse(istrm);
}
config(const std::string& contents) {
std::stringstream strm(contents);
parse(strm);
}
config(config& cfg) = default;
void set(const std::string& section, const std::string& key, const std::string& value) {
conf[section][key] = value;
}
bool remove(const std::string& section, const std::string& key) {
auto sectionitems = conf.find(section);
// if section not found, return fail to remove
if (sectionitems == conf.end()) {
return false;
} | {
"domain": "codereview.stackexchange",
"id": 43760,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, object-oriented",
"url": null
} |
c++, object-oriented
// if key not found, return fail to remove
auto keyValue = sectionitems->second.find(key);
if (keyValue == sectionitems->second.end()) {
return false;
}
return sectionitems->second.erase(keyValue) != sectionitems->second.end();
}
using iterator = std::unordered_map<std::string, keyvalues>::iterator;
iterator begin() { return conf.begin(); }
iterator end() { return conf.end(); }
const std::string serialise() {
std::string serialised;
for (auto& section : conf) {
serialised += '[' + section.first + "]\n";
for (auto keyvalue : section.second) {
serialised += keyvalue.first + '=' + keyvalue.second + '\n';
}
}
return serialised;
}
private:
std::unordered_map<std::string, keyvalues> conf;
void parse(std::istream& strm) {
std::string line;
std::string sectionname;
while (std::getline(strm, line, '\n')) {
if (!line.empty()) {
if (line.size() > 2 && line[0] == '[' && line[line.size() - 1] == ']') {
sectionname = line.substr(1, line.size() - 2);
}
else {
// get key and value for this section
const std::string key = line.substr(0, line.find('='));
const std::string value = line.substr(line.find('=') + 1);
conf[sectionname][key] = value;
}
}
}
}
};
std::ostream& operator<<(std::ostream& strm, config& cfg) {
for (auto& section : cfg) {
strm << "section name: " << section.first << '\n';
for (auto& keyvalue : section.second) {
strm << "key: " << keyvalue.first << ", value: " << keyvalue.second << '\n';
}
}
return strm;
} | {
"domain": "codereview.stackexchange",
"id": 43760,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, object-oriented",
"url": null
} |
c++, object-oriented
class FileHandler {
public:
static std::vector<std::string> GetFilenames(const std::string& directoryName) {
std::vector<std::string> files;
const std::filesystem::path folder{ directoryName };
for (auto const& dir_entry : std::filesystem::directory_iterator{folder})
{
files.push_back(dir_entry.path().string());
}
return files;
}
static const std::string GetFilenamePart(const std::string& fullpath) {
const std::filesystem::path filepath { fullpath };
return filepath.stem().string();
}
// generate file and return full path to generated file
static const std::string GenerateFilename(const std::string& directory, const std::string& filename) {
return directory.back() != SEPARATOR ? directory + SEPARATOR + filename : directory + filename;
}
private:
#ifdef _WIN32
static const char SEPARATOR{ '\\' };
#else
static const char SEPARATOR{ '/' };
#endif
};
class StringTransformer {
public:
static const std::pair<std::string, std::string> SplitOn(const std::string& s, const char delim) {
size_t pos = s.find(delim);
if (pos != std::string::npos) {
return { s.substr(0, pos), s.substr(pos + 1) };
}
else {
return { "","" };
}
}
};
int main(int argc, char* argv[]) {
if (argc < 2 || argc > 3) {
std::cout << "Usage: prop2ini <directory> [config filename]\n";
return 1;
}
const std::string directory = argv[1];
const std::string filename = argc == 3 ? argv[2] : "config.conf";
const std::string fullpath = FileHandler::GenerateFilename(directory, filename);
// get files in directory
std::vector<std::string> files = FileHandler::GetFilenames(directory);
config cfg;
for (auto file : files) {
const std::string section = FileHandler::GetFilenamePart(file);
std::ifstream inputFile(file); | {
"domain": "codereview.stackexchange",
"id": 43760,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, object-oriented",
"url": null
} |
c++, object-oriented
std::ifstream inputFile(file);
std::string line;
while (std::getline(inputFile, line)) {
auto keyValue = StringTransformer::SplitOn(line, ':');
cfg.set(section, keyValue.first, keyValue.second);
}
}
const std::string serialised = cfg.serialise();
std::ofstream outputFile(fullpath, std::ios::app);
outputFile << serialised;
// informational message
std::cout << "proprietary configuration files in " << directory << " copied to " << filename << '\n';
}
Answer: Simplify generate.sh
You should not have to worry about the trailing slash in the directory name if you just add one unconditionally:
printf "SPORT : AX3\nNEWS : Sky7\nCOMEDY : Art5\n" > $1/channels.txt
The above will always do what you want, as two or more consecutive slashes just count as one. Another option to avoid the issue would be to just do:
cd $1
printf "SPORT : AX3\nNEWS : Sky7\nCOMEDY : Art5\n" > channels.txt
However, that is a bit unsafe: what if the directory you pass doesn't exist? The cd would then fail, but the subsequent command would then cause channels.txt to be written to the current directory. A good way to avoid this is to tell the shell to abort on any errors, by setting the -e flag as soon as possible:
#!/bin/sh
set -e
... | {
"domain": "codereview.stackexchange",
"id": 43760,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, object-oriented",
"url": null
} |
c++, object-oriented
Also avoid explicitly using Bash if you don't use any Bash-only features, instead use /bin/sh as the shell. The latter might be Bash or another POSIX-compliant shell, and is guaranteed to exist on UNIX systems, while /bin/bash might not.
Unnecessary use of class
class FileHandler contains no member variables and only static member functions. There is no advantage to put those in a class, just put them outside, and keep them static. You could consider putting them in a namespace instead, but if these functions are only going to be used by other code in the same .cpp file, I don't see a reason for that either.
Avoid dealing with differences in path separators
While Windows normally uses backslashes as a separator of path components, it also accepts forward slashes. But even better, since you are using std::filesystem, store paths in std::filesystem::path, which handles concatenation of path components for you. For example:
namespace fs = std::filesystem;
static fs::path GenerateFilename(const fs::path& directory, const fs::path& filename) {
return directory / filename;
}
Of course now this function is so simple that you don't even need it anymore. A lot of your code simplifies by using std::filesystem::path to hold everything that is a directory or filename. Only convert them to std::string if absolutely necessary.
Avoid storing filenames in a temporary vector
There is no point in having GetFilenames() loop over the directory, storing all filenames in a std::vector, and then have the code in main() loop again over that vector. Instead, just loop over the directory in main():
const std::filesystem::path directory = argv[1];
...
for (auto const& dir_entry : directory) {
std::ifstream inputFile(dir_entry.path());
...
} | {
"domain": "codereview.stackexchange",
"id": 43760,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, object-oriented",
"url": null
} |
c++, object-oriented
Is class config necessary?
Similarly to storing filenames in a temporary vector, do you actually need to store the configuration into an instance of class config before you write it out? It seems to me that you could write directly to the output file while you are reading the input:
for (auto const& dir_entry : directory) {
outputFile << '[' << dir_entry.path().string() << "]\n";
std::string line;
std::ifstream inputFileopen(dir_entry.path());
while (std::getline(inputFile, line)) {
auto keyValue = StringTransformer::SplitOn(line, ':');
outputFile << keyValue.first << '=' << 'keyValue.second' << '\n';
}
}
Missing error checking
At no point do you check whether input and output files are read or written to correctly, and neither do you validate the keys and values.
Make sure you check after reading the last line of an input file that inputFile.eof() == true, and after writing the output close() it and then check that outputFile.good() == true. If any of those are false, print an error message to std::cerr and exit the program with EXIT_FAILURE.
Also consider what happens if the key in one of the input files contains an =, what to do with leading/trailing spaces, if there are differences in how booleans, numbers and strings are represented in prop vs. INI files. Can prop files have comments in them? What about lines without a : or with an empty key or value? | {
"domain": "codereview.stackexchange",
"id": 43760,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, object-oriented",
"url": null
} |
python, python-3.x, configuration
Title: Extracting username, password and host from a config file
Question: The code below calls the parse_config() function which populates the global variables user, passwd and host which are later used in main() function:
#!/usr/bin/env python3
import sys
import configparser
def parse_config(cfg):
"""
Read the configuration file.
"""
global user, passwd, host
if cfg.has_option('login', 'username'):
user = cfg['login']['username']
else:
sys.exit(1)
if cfg.has_option('login', 'password'):
passwd = cfg['login']['password']
else:
sys.exit(1)
if cfg.has_option('server', 'host'):
host = cfg['server']['host']
else:
host = 'localhost'
def main():
config = configparser.ConfigParser()
with open('conf.ini', encoding='utf-8') as conf_f:
config.read_file(conf_f)
parse_config(config)
print(f'username: {user}, password: {passwd}, host: {host}')
if __name__ == '__main__':
main()
As using the global variables is not encouraged, then how should one rewrite this script? Perhaps by returning the local variables from the parse_config() function? Like this:
#!/usr/bin/env python3
import sys
import configparser
def parse_config(cfg):
"""
Read the configuration options.
"""
if cfg.has_option('login', 'username'):
user = cfg['login']['username']
else:
sys.exit(1)
if cfg.has_option('login', 'password'):
passwd = cfg['login']['password']
else:
sys.exit(1)
if cfg.has_option('server', 'host'):
host = cfg['server']['host']
else:
host = 'localhost'
return user, passwd, host
def main():
config = configparser.ConfigParser()
with open('conf.ini', encoding='utf-8') as conf_f:
config.read_file(conf_f)
user, passwd, host = parse_config(config)
print(f'username: {user}, password: {passwd}, host: {host}')
if __name__ == '__main__':
main() | {
"domain": "codereview.stackexchange",
"id": 43761,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, configuration",
"url": null
} |
python, python-3.x, configuration
if __name__ == '__main__':
main()
Or perhaps it's fine to use global variables in this case?
Answer: Global variables
Don’t use them. The second version of your code is better.
Function names & doc strings
If you typed help(parse_config), the displayed help might say:
>>> help(parse_config)
parse_config(cfg):
Read the configuration options.
>>>
This is truly confusing. The help text describes the function as reading the configuration, but nowhere does it say where it would be reading it from. Maybe it reads the information from a hard-coded filename? And it must read it into a the cfg structure that is passed to the function, or else what is the purpose of the cfg argument?
And is there “parsing” going on? Reading text, and extracting information from it?
No! The configuration reading and parsing has already been done by configparser.read_file(config_f). This function is neither reading nor parsing the configuration. It should be renamed, and the docstring expanded to say what it is doing, what it expects, and what it returns.
Raise exceptions
Don’t use sys.exit(). Raise an exception, instead. sys.exit() immediately terminates the Python interpreter. Test frameworks often are written in Python, so exiting the Python interpreter makes testing much, much harder.
As a bonus, the exception can describe the problem better. “Configuration is missing the ‘user’ element in [login’]” is much clearer than an exit code of 1, which is also the the error code for a missing password!
God function
The second version of the function returns everything: username, password, and host. Unfortunately, it returns it as a tuple of three values, with no clear indication as to what those values are. If you needed just the host name at another point, you can’t just fetch the one piece you need; you have to get everything.
You could split it up into 3 functions:
def username_from_config(cfg):
...
def password_from_config(cfg):
... | {
"domain": "codereview.stackexchange",
"id": 43761,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, configuration",
"url": null
} |
python, python-3.x, configuration
def password_from_config(cfg):
...
def host_from_config(cfg):
...
The main() function can query each required value, instead of getting all the values.
Alternately, you could return a namedtuple of the information:
from typing import NamedTuple
class Config(NamedTuple):
user: str
passwd: str
host: str
def parse_config(cfg) -> Config:
...
return Config(user, passwd, host)
def main():
...
config = parse_config(cfg)
print(f'username: {config.user}, password: {config.passwd}, host: {config.host}')
You are still returning a “god” object, but at least the values are stored in named fields. | {
"domain": "codereview.stackexchange",
"id": 43761,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, configuration",
"url": null
} |
performance, c, hash-map
Title: Hash table C implementation - Separate Chaining
Question: I've written a C implementation of a hashmap of strings including the basic operations and a strategy for handling hash collisons.
Additionally, I've included some tests, specifically for cases involving hash collisions which, I confess, gave me a bit of trouble initially.
Thank you in advance for your time :)
ps, if you prefer to view on github: https://github.com/JosephSBoyle/HashMap
hashmap.h
#include <stddef.h>
#include "hashmap.c"
/* Create a hashmap.*/
Node** hm_create(void);
/* Add an item to the hashmap */
void hm_add(Node** hmap, char key[], char value[]);
/* Remove an item from the hashmap */
void hm_del(Node** hmap, char key[]);
/** Get an item from the hashmap
* @returns the value corresponding to 'key' or the terminating character '\0'
* if no such item exists. */
char* hm_get(Node** hmap, char key[]);
hashmap.c
#define BUCKETS 1000000
#define PRIME_SEED_1 17
#define PRIME_SEED_2 97
#define KEY_CHARS 128
#define VALUE_CHARS 128
#define NODE_SIZE sizeof(Node)
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include <assert.h>
/* A key-value node in a single-linked list. */
typedef struct Node Node;
struct Node {
Node* next;
char key[KEY_CHARS];
char value[VALUE_CHARS];
};
Node* create_sentinel_node(){
void* ptr = malloc(NODE_SIZE);
if (ptr == NULL){
exit(EXIT_FAILURE);
} else {
Node* node = (Node*)ptr; // safely typecast the pointer
node->next = NULL;
strcpy(node->key, "\0");
strcpy(node->value, "\0");
return node;
}
}
size_t modular_hash(char* string) {
size_t hash = 0;
for (char* character=string; *character != '\0'; character++) {
hash += ((int)*character + PRIME_SEED_1) * PRIME_SEED_2;
}
return hash;
} | {
"domain": "codereview.stackexchange",
"id": 43762,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, c, hash-map",
"url": null
} |
performance, c, hash-map
Node** hm_create(void){
static Node* keys[BUCKETS] = {};
for (size_t i=0; i<BUCKETS; i++){
keys[i] = create_sentinel_node();
}
return keys;
}
void hm_add(Node** hmap, char key[], char value[]){
Node* node = hmap[modular_hash(key)];
if (strcmp(node->value, "\0") == 0){
// there's no item in this bucket.
strcpy(node->key, key);
strcpy(node->value, value);
return;
}
while(true){
if (strcmp(node->key, key) == 0){
// the key already exists as a node in the linked list
// so we can simply replace the value.
strcpy(node->value, value);
return;
}
if (node->next == NULL){
// no more nodes, append a new node to the linked list.
void* ptr = malloc(NODE_SIZE);
if (ptr == NULL){
exit(EXIT_FAILURE);
}
Node* new_node = (Node*)ptr; // safely typecast the pointer
new_node->next = NULL;
strcpy(node->value, value);
strcpy(new_node->key, key);
node->next = new_node;
return;
}
node = node->next;
}
}
void hm_del(Node** hmap, char key[]){
size_t khash = modular_hash(key);
Node* node = hmap[khash];
void* prev_node = NULL;
Node* head = node;
// find the node
while (strcmp(head->key, key) != 0){
if (head->next == NULL){
// the key doesn't exist in this hashmap.
return;
}
head = head->next;
prev_node = head;
} | {
"domain": "codereview.stackexchange",
"id": 43762,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, c, hash-map",
"url": null
} |
performance, c, hash-map
// are we deleting the first node?
if (prev_node == NULL){
// are we deleting the only node?
if (head->next == NULL){
// reset the node to the sentinel node.
strcpy(node->value, "\0");
strcpy(node->key, "\0");
} else {
// we are deleting the first of n>1 nodes.
hmap[khash] = head->next;
}
} else {
// there must be a previous node.
Node* prev_node = (Node*)prev_node;
// is this the last node?
if (head->next == NULL){
prev_node->next = NULL;
} else {
// we are deleting neither the first nor the last node.
prev_node->next = head->next;
}
free(head);
}
}
char* hm_get(Node** hmap, char key[]){
Node* node = hmap[modular_hash(key)];
// skip list elements in the bucket (linked list) that don't match our key.
while (strcmp(node->key, key) != 0){
if (node->next==NULL){
return "\0";
}
node = node->next;
}
return node->value;
}
tests.c
#include "hashmap.h"
/** TESTS
* These tests test the collision handling of the hashmap.
* NOTE: To cause collisions, replace the return value of the hash function with a constant int, e.g `return 0;`
*/
void main(){
// test adding and getting an item
Node** hm0 = hm_create();
hm_add(hm0, "bob", "x");
char* a = hm_get(hm0, "bob");
assert(strcmp(a, "x") == 0);
// test deleting an item that doesn't exist
Node** hm1 = hm_create();
hm_del(hm1, "bob");
char* b = hm_get(hm1, "bob");
assert(strcmp(b, "\0") == 0);
// test getting a deleted item
Node** hm2 = hm_create();
hm_add(hm0, "bob", "the dog");
hm_del(hm2, "bob");
char* c = hm_get(hm2, "bob");
assert(strcmp(c, "\0") == 0); | {
"domain": "codereview.stackexchange",
"id": 43762,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, c, hash-map",
"url": null
} |
performance, c, hash-map
// test overwriting a value
Node** hm3 = hm_create();
hm_add(hm3, "bob", "foo");
hm_add(hm3, "bob", "bar");
char* d = hm_get(hm3, "bob");
assert(strcmp(d, "bar") == 0);
// test deleting the last item
Node** hm4 = hm_create();
hm_add(hm4, "bob", "foo");
hm_add(hm4, "alice", "bar");
hm_add(hm4, "jane", "baz");
hm_del(hm4, "jane");
char* e = hm_get(hm4, "jane");
assert(strcmp(e, "\0") == 0);
// test deleting an item in the middle of the linked list.
Node** hm5 = hm_create();
hm_add(hm5, "bob", "abc");
hm_add(hm5, "alice", "123");
hm_add(hm5, "jane", "xyz");
hm_del(hm5, "alice");
char* f = hm_get(hm5, "alice");
assert(strcmp(f, "\0") == 0);
printf(
"############################\n"
"----- ALL TESTS PASSED -----\n"
"############################\n"
);
}
```
Answer:
hashmap.c in hashmap.h??
Very unusual to #include "hashmap.c" in a header file. Header files are expected to not generate code, just define and declare things.
Best to remove #include "hashmap.c"
Strange string compare
Simplify
// if (strcmp(node->value, "\0") == 0){
if (node->value[0] == 0) {
// strcpy(node->key, "\0");
node->key[0] = 0;
Use const
When referenced data does not change, use const.
// void hm_add(Node** hmap, char key[], char value[]){
void hm_add(Node** hmap, const char key[], const char value[]) {
Prevent buffer overflow
strcpy() risks buffer overflow. Consider protection. Example:
// strcpy(node->value, value);
snprintf(node->value, sizeof node->value, "%s", value); | {
"domain": "codereview.stackexchange",
"id": 43762,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, c, hash-map",
"url": null
} |
performance, c, hash-map
Of course if the string is too long, better code would detect that and complain. Even better, save a copy of the string with strdup().
Bug: hash
modular_hash() does not limit its return value to [0...BUCKETS). I'd expect a mod:
size_t modular_hash(const char* string) {
size_t hash = 0;
for (char* character=string; *character != '\0'; character++) {
hash += ((int)*character + PRIME_SEED_1) * PRIME_SEED_2;
}
hash %= BUCKETS; // add
return hash;
}
Weak hash
Does not vary on order.
modular_hash("abc") == modular_hash("bca") == modular_hash("cab") == ...
Tip: mod by prime
Using hash %= BUCKETS; above, with BUCKETS as a prime or not, makes little difference if the hash function was good. Yet with a modest or weak hash, using a prime for BUCKETS improves the overall hash. I recommend changing BUCKETS from 1000000 to a prime near that.
Pointless cast
Cast (int)*character in modular_hash(char* string) serves no purpose. If anything a cast to unsigned makes some sense.
Good for only 1 map
hm_create(void) uses static Node* keys[BUCKETS] = {}; limiting us to 1 hash map. Better to allocate to allow multiple instantiations of the hash map.
Unneeded include
#include <stddef.h> not needed in hashmap.h.
Unneeded cast
Casts does not improve safety - not needed to convert a void * to some object pointer..
// Node* node = (Node*)ptr; // safely typecast the pointer
Node* node = ptr;
"\0"??
Every place where "\0" (2 null characters, one explicit, one implied) is used can be replaced with "".
Good test code
Return distinction
hm_get() returns a pointer to "" when none is found. Yet if the item in the table was "", we do not know if the function succeeded or failed. Instead, consider returning NULL on failure.
Fixed hash size
A more advanced hash table would adjust the hash table size as needed.
Comments
IHO, a satisfying amount of comments. | {
"domain": "codereview.stackexchange",
"id": 43762,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, c, hash-map",
"url": null
} |
javascript
Title: how to structure js code for login page
Question: I have the following js script for my logon page. It feels like a long run on sentence. It works but wondering if there is a better way to structure this.
window.onload = function(){
//define form elements
const remBox = document.querySelector('input[type="checkbox"]');
const alerts = document.getElementsByClassName('alerts');
const form = document.querySelector('form');
const formEmail = document.querySelector('input[type="email"]');
const formPassword = document.querySelector('input[type="password"]');
//define local storage for remember me
const localStorageEmail = localStorage.getItem("lsEmail");
const localStoragePassword = localStorage.getItem("lsPassword");
if(localStorageEmail === null)formEmail.value = '';
else formEmail.value = localStorageEmail;
// create listeners
document.querySelector('input[type="submit"]').addEventListener('click',submit);
document.querySelector('input[type="email"]').addEventListener("focus", focus);
document.querySelector('input[type="password"]').addEventListener("focus", focus);
//window.addEventListener("pageshow", clearBack);
//localStorage has valid email - fill form with email and dummy password
if(localStorageEmail !== null){
formEmail.value = localStorageEmail;
formPassword.value = localStoragePassword;
//check remember me box
document.querySelector('input[type="checkbox"]').checked=true;
}
function submit(){
event.preventDefault();
const emailPass = {};
let responseData = {};
formEmail.value = formEmail.value.toLowerCase();
const eflag = emailCheck(formEmail.value);
const pflag = passwordCheck(formPassword.value);
if(eflag && pflag){
emailPass.formEmail = formEmail.value;
emailPass.formPassword = formPassword.value;
//responseData = sendData2('http://d78d-96-230-240-153.ngrok.io/lagin/public/login.php',emailPass); | {
"domain": "codereview.stackexchange",
"id": 43763,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript",
"url": null
} |
javascript
responseData = sendData2('login.php',emailPass);
responseData.then(function(response){
if(response.email == 'FOUND' && response.password == 'MATCH'){
// Remember me box
if(remBox.checked === false){
localStorage.removeItem('lsEmail');
}else{
localStorage.setItem("lsEmail", formEmail.value);
localStorage.setItem("lsPassword", formPassword.value);
}
form.submit();
}else if(response.email == 'NOT FOUND'){
alerts[0].innerHTML = "Email address not found. Register or enter a valid email address";
alerts[0].classList.remove("hide");
alerts[0].classList.add("show");
formEmail.value = '';
}else if(response.password == 'NO MATCH'){
alerts[1].innerHTML = 'Password does not match. Please re-enter';
alerts[1].classList.remove("hide");
alerts[1].classList.add("show");
formPassword.value = '';
}else if(response.email == 'DATABASE CORRUPT'){
document.querySelector('body').innerHTML = '<div><h1>FATAL ERROR: Database corrupt</h1></div>';
}else if(response.email == 'NOT GET OR POST'){
document.querySelector('body').innerHTML = '<div><h1>FATAL ERROR: Network error. Invalid request method</h1></div>';
}else{
document.querySelector('body').innerHTML = '<div><h1>FATAL ERROR: Unknown error login.js</h1></div>';
}
});
}else{
console.log('client side eflag = ' + eflag + ' pflag = ' + pflag);
}
} | {
"domain": "codereview.stackexchange",
"id": 43763,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript",
"url": null
} |
javascript
function emailCheck(email){
// function checks for a valid email address name@server.domain
const parts = [String.raw`^(?:[a-z0-9!#$%&'*+/=?^_\`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_\`{|}~-]+)*|`,
String.raw`"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")`,
String.raw`@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|`,
String.raw`\[(?:(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9]))\.){3}(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9])|`,
String.raw`[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])$`];
const mailformat = parts.join('');
if(!email.match(mailformat)){
alerts[0].innerHTML = "Please enter a valid email address";
alerts[0].classList.remove("hide");
alerts[0].classList.add("show");
return false;
}else{
return true;
}
}
function passwordCheck(password){
if(password.length < 1){
alerts[1].innerHTML = '1 or more characters required';
alerts[1].classList.remove("hide");
alerts[1].classList.add("show");
return false;
}
return true;
}
function focus(event){
if(event.target.type == 'email'){
alerts[0].classList.remove("show");
alerts[0].classList.add("hide");
formEmail.value = '';
}else{
alerts[1].classList.remove("show");
alerts[1].classList.add("hide");
formPassword.value='';
}
}
function clearBack(){
if(remBox.checked === false)formEmail.value = '';
} | {
"domain": "codereview.stackexchange",
"id": 43763,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript",
"url": null
} |
javascript
function clearBack(){
if(remBox.checked === false)formEmail.value = '';
}
/* using axios for async request
function getAjax(url, success) {
var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
xhr.open('GET', url);
xhr.onreadystatechange = function() {
if (xhr.readyState>3 && xhr.status==200) success(xhr.responseText);
};
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.send();
return xhr;
} */
};
Answer: There looks to be a lot of
alerts[0].innerHTML = "Please enter a valid email address";
alerts[0].classList.remove("hide");
alerts[0].classList.add("show");
or similar variations. You could create a function, taking in the innerHTML and array index to reduce this vastly.
You can create a second function just taking in the array index when you only need to toggle the class.
Ontop of this you may want to look at having the hide class properties already applied to your element and then you only have the show class to add and remove. | {
"domain": "codereview.stackexchange",
"id": 43763,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript",
"url": null
} |
c, parsing, linux
Title: Iterate over a process' maps file
Question: The following logic provides iteration over /proc/<PID>/maps for a Linux process. What I'm primarily (though not solely) interested in for this review is whether or not I've made any invalid assumptions about the layout of the maps file.
iterate_map.h
#ifndef REAP_ITERATE_MAP_H
#define REAP_ITERATE_MAP_H
#include <stdio.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <unistd.h>
#define REAP_PATH_SIZE 256
enum reapRetValue {
REAP_RET_OK, /**< The function was successful.*/
REAP_RET_DONE, /**< The iteration is finished.*/
REAP_RET_BAD_USAGE, /**< A funciton was called with invalid arguments.*/
REAP_RET_OUT_OF_MEMORY, /**< A memory allocation failed.*/
REAP_RET_NO_PERMISSION, /**< No permission to access a requested resource.*/
REAP_RET_NOT_FOUND, /**< A requested resource was not found.*/
REAP_RET_TOO_MANY_LINKS, /**< Too many symbolic links encountered.*/
REAP_RET_FILE_READ, /**< Failed to read from a file.*/
REAP_RET_OTHER, /**< Catch-all error.*/
};
/**
* @brief Iterates over all line in a /proc/<PID>/maps file.
*
* @note User code should not access the iterator's fields.
*/
typedef struct reapMapIterator {
FILE *file;
} reapMapIterator;
/**
* @brief Result generated by a reapMapIterator.
*/
typedef struct reapMapResult {
unsigned long start; /**< The start of the memory section.*/
unsigned long end; /**< The end of the memory section.*/
unsigned int offset; /**< The offset of the memory section in the referent file.*/
int permissions; /**< The permissions of the memory section.*/
dev_t device; /**< The device number of the referent file.*/
ino_t inode; /**< The inode of the referent file.*/
char name[REAP_PATH_SIZE]; /**< The name of the referent file.*/
} reapMapResult; | {
"domain": "codereview.stackexchange",
"id": 43764,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, parsing, linux",
"url": null
} |
c, parsing, linux
/**
* @brief Initializes an iterator.
*
* @param pid The PID.
* @param iterator A pointer to the iterator.
*
* @return REAP_RET_OK if successful and an error code otherwise.
*/
int
reapMapIteratorInit(pid_t pid, reapMapIterator *iterator);
/**
* @brief Closes an iterator.
*
* @param iterator A pointer to the iterator.
*/
void
reapMapIteratorClose(reapMapIterator *iterator);
/**
* @brief Gets the next result.
*
* @param iterator A pointer to the iterator.
* @param[out] result A pointer to the result to be populated.
*
* @return REAP_RET_OK if a result was found, REAP_RET_DONE if the iteration is finished, and an
* error code otherwise.
*/
int
reapMapIteratorNext(const reapMapIterator *iterator, reapMapResult *result);
#endif // REAP_ITERATE_MAP_H
iterate_map.c
#include <errno.h>
#include <string.h>
#include <sys/sysmacros.h>
#include <sys/types.h>
#include <reap/iterate_map.h>
static int
translateErrno(void)
{
switch (errno) {
case EINVAL: return REAP_RET_BAD_USAGE;
case EACCES: return REAP_RET_NO_PERMISSION;
case ELOOP: return REAP_RET_TOO_MANY_LINKS;
case ENOENT:
case ENOTDIR:
case EIO: return REAP_RET_FILE_READ;
case ENOMEM: return REAP_RET_OUT_OF_MEMORY;
default: return REAP_RET_OTHER;
}
}
int
reapMapIteratorInit(pid_t pid, reapMapIterator *iterator)
{
char buffer[100];
if (pid <= 0 || !iterator) {
return REAP_RET_BAD_USAGE;
}
snprintf(buffer, sizeof(buffer), "/proc/%li/maps", (long)pid);
iterator->file = fopen(buffer, "r");
if (!iterator->file) {
return translateErrno();
}
return REAP_RET_OK;
}
void
reapMapIteratorClose(reapMapIterator *iterator)
{
if (iterator && iterator->file) {
fclose(iterator->file);
iterator->file = NULL;
}
} | {
"domain": "codereview.stackexchange",
"id": 43764,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, parsing, linux",
"url": null
} |
c, parsing, linux
int
reapMapIteratorNext(const reapMapIterator *iterator, reapMapResult *result)
{
int num_matches;
unsigned int major, minor;
unsigned long inode;
char r, w, x;
char line[256];
if (!iterator || !iterator->file || !result) {
return REAP_RET_BAD_USAGE;
}
if (!fgets(line, sizeof(line), iterator->file)) {
if (ferror(iterator->file)) {
return REAP_RET_FILE_READ;
}
else {
return REAP_RET_DONE;
}
}
num_matches = sscanf(line, "%lx-%lx %c%c%c%*c %x %x:%x %lu %s", &result->start, &result->end, &r, &w, &x,
&result->offset, &major, &minor, &inode, result->name);
if (num_matches < 9) {
return REAP_RET_OTHER;
}
if (num_matches == 9) {
result->name[0] = '\0';
}
result->permissions = 0;
if (r == 'r') {
result->permissions |= PROT_READ;
}
if (w == 'w') {
result->permissions |= PROT_WRITE;
}
if (x == 'x') {
result->permissions |= PROT_EXEC;
}
result->device = makedev(major, minor);
result->inode = inode;
return REAP_RET_OK;
}
Answer: If user code is not supposed to access the innards of a reapMapIterator, it's best to make it an incomplete type in the header, and define it only in the implementation. A small change is needed to the interface, so that reapMapIteratorInit() returns an allocated reapMapIterator and reapMapIteratorClose() also frees the memory.
I don't like the translation of errno values to reapRetValue - the former are much more usable, given that strerror() already exists to provide translated user messages. | {
"domain": "codereview.stackexchange",
"id": 43764,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, parsing, linux",
"url": null
} |
array, vba, excel
Title: Loop between two Arrays and change values based on condition
Question: Instead of using 45 IF conditions , I put my two ranges into variant arrays.
Then I used the below code to loop between them and change values of the first array arr1 second elements based on condition.
the first range is only 10K rows and the second range is just 45 rows and code takes about 0.7 second to finish.
I tried to use Application optimizations like (Calculation, ScreenUpdating ,) but it makes no difference on speed.
In advanced grateful for all your help.
Option Explicit
Option Compare Text
Sub LoopTwoArrays2()
Dim ws1 As Worksheet: Set ws1 = ThisWorkbook.Sheets(1)
Dim ws2 As Worksheet: Set ws2 = ThisWorkbook.Sheets(2)
Dim arg As Range, brg As Range
Set arg = ws1.Range("P2:Q" & ws1.Cells(Rows.Count, "P").End(xlUp).Row)
Set brg = ws2.Range("A2:B" & ws2.Cells(Rows.Count, "A").End(xlUp).Row)
Dim arr1 As Variant, arr2 As Variant
arr1 = arg.Value2
arr2 = brg.Value2
Dim i As Long, k As Long
For i = LBound(arr1) To UBound(arr1)
For k = LBound(arr2) To UBound(arr2)
If arr1(i, 1) = arr2(k, 1) Then
arr1(i, 2) = arr2(k, 2)
End If
Next k
Next i
arg.Value = arr1
End Sub
Answer: As @Greedo mentioned, it is much simpler to write a formula, be that XLOOKUP or a combination of INDEX and MATCH with fast results and easier maintenance.
However, if you still need to do VBA for whatever reason, then add a reference to Microsoft Scripting Runtime: | {
"domain": "codereview.stackexchange",
"id": 43765,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "array, vba, excel",
"url": null
} |
array, vba, excel
and then use something like this:
Option Explicit
Option Compare Text
Sub LoopTwoArrays2()
Dim ws1 As Worksheet: Set ws1 = ThisWorkbook.Sheets(1)
Dim ws2 As Worksheet: Set ws2 = ThisWorkbook.Sheets(2)
Dim arg As Range, brg As Range
Set arg = ws1.Range("P2:Q" & ws1.Cells(Rows.Count, "P").End(xlUp).Row)
Set brg = ws2.Range("A2:B" & ws2.Cells(Rows.Count, "A").End(xlUp).Row)
Dim arr1() As Variant, arr2() As Variant
RangeToArray arg, arr1
RangeToArray brg, arr2
Dim i As Long, k As Long
Dim dict As New Dictionary
For k = UBound(arr2, 1) To LBound(arr2, 1) Step -1
dict(arr2(k, 1)) = arr2(k, 2)
Next k
On Error Resume Next
For i = LBound(arr1, 1) To UBound(arr1, 1)
arr1(i, 2) = dict(arr1(i, 1))
Next i
On Error GoTo 0
arg.Value2 = arr1
End Sub
Private Sub RangeToArray(ByRef rng As Range, ByRef arr() As Variant)
If rng.Areas(1).Count = 1 Then
ReDim arr(1 To 1, 1 To 1)
arr(1, 1) = rng.Value2
Else
arr = rng.Value2
End If
End Sub
Note that when reading the values from a range you are not guaranteed to get an array hence the need for RangeToArray method.
Also, instead of using:
On Error Resume Next
For i = LBound(arr1, 1) To UBound(arr1, 1)
arr1(i, 2) = dict(arr1(i, 1))
Next i
On Error GoTo 0
you might want something like:
For i = LBound(arr1, 1) To UBound(arr1, 1)
If dict.Exists(arr1(i, 1)) Then
arr1(i, 2) = dict(arr1(i, 1))
Else
arr1(i, 2) = Empty 'Or whatever
End If
Next i
which gives you more control on the return value, if the lookup fails. | {
"domain": "codereview.stackexchange",
"id": 43765,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "array, vba, excel",
"url": null
} |
python
Title: Print next item in a list for a given item in the list in python
Question: I have a list
list = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday']
If I give an input of Saturday, then it should return the next day (Sunday) and the previous day (Friday). My program works, but I am looking for a simple function to print the next value in the list for a given item.
My code below :
list = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday']
give_day = input('Enter the day : ')
index_give_day = list.index(give_day)
len_list = len(list)-1
next_day = list[0 if index_give_day == len_list else index_give_day +1]
prev_day = list[index_give_day -1]
print(next_day)
print(prev_day)
Answer: Don't make the list yourself; use calendar.day_name. Among other reasons, this will support localisation, where your current code does not.
You don't need conditionals, and you don't even need to modulate your index. Since the array is so small, the simplest indexing solution is probably just to duplicate it and index directly.
Consider applying .title() for a more forgiving name lookup.
Suggested
from calendar import day_name
weekdays = tuple(day_name)*2
name = input('Enter the weekday name: ').title()
day = weekdays.index(name)
prev_day, next_day = weekdays[day-1], weekdays[day+1]
print(next_day)
print(prev_day)
Output
Enter the weekday name: saturday
Sunday
Friday | {
"domain": "codereview.stackexchange",
"id": 43766,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python",
"url": null
} |
algorithm, c, homework, e-commerce, checksum
Title: CS50 pset1: credit card classification and checksum validation
Question: I wrote the following code for the cs50 pset1 credit and it passes all the checks. However, I think that it is too long (specially the last part) and would like to improve it. I would be very grateful, if someone could check my code and give me some feedback.
#include <cs50.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int main(void)
{
//Ask user for the credit card number and store the input in a string
string card_number;
card_number = get_string("Number: ");
// Store the string length
int string_length = strlen(card_number);
//Iterate through each character to check if it is a digit
for (int character = 0; character < string_length; character++)
{
if (!isdigit(card_number[character]))
{
printf("INVALID\n");
break;
}
}
//Calculate the check_sum
int check_sum = 0;
for (int character = string_length - 1; character >= 0; character -= 2)
{
check_sum += card_number[character] - '0';
}
for (int character = string_length - 2; character >= 0; character -= 2)
{
int digit = ((card_number[character] - '0') * 2);
while (digit > 0)
{
check_sum += (digit % 10);
digit /= 10;
}
} | {
"domain": "codereview.stackexchange",
"id": 43767,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "algorithm, c, homework, e-commerce, checksum",
"url": null
} |
algorithm, c, homework, e-commerce, checksum
//Print the credit card provider
if (check_sum % 10 == 0 && string_length == 15 && card_number[0] == '3' && card_number[1] == '4')
{
printf("AMEX\n");
}
else if (check_sum % 10 == 0 && string_length == 15 && card_number[0] == '3' && card_number[1] == '7')
{
printf("AMEX\n");
}
else if (check_sum % 10 == 0 && string_length == 13 && card_number[0] == '4')
{
printf("VISA\n");
}
else if (check_sum % 10 == 0 && string_length == 16 && card_number[0] == '4')
{
printf("VISA\n");
}
else if (check_sum % 10 == 0 && string_length == 16 && card_number[0] == '5' && card_number[1] == '1')
{
printf("MASTERCARD\n");
}
else if (check_sum % 10 == 0 && string_length == 16 && card_number[0] == '5' && card_number[1] == '2')
{
printf("MASTERCARD\n");
}
else if (check_sum % 10 == 0 && string_length == 16 && card_number[0] == '5' && card_number[1] == '3')
{
printf("MASTERCARD\n");
}
else if (check_sum % 10 == 0 && string_length == 16 && card_number[0] == '5' && card_number[1] == '4')
{
printf("MASTERCARD\n");
}
else if (check_sum % 10 == 0 && string_length == 16 && card_number[0] == '5' && card_number[1] == '5')
{
printf("MASTERCARD\n");
}
else
{
printf("INVALID\n");
}
} | {
"domain": "codereview.stackexchange",
"id": 43767,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "algorithm, c, homework, e-commerce, checksum",
"url": null
} |
algorithm, c, homework, e-commerce, checksum
}
Answer: You should break the code up into functions, one of the functions should be to check if each character is a digit and that function should return a bool value that indicates success or failure. In the current code if there is an invalid character the loop stops when it finds an in valid character, but the program still performs the check for the company that issued the card. If the card number is not valid the program should not continue with the processing.
Testing of code should always test negative paths as well as positive tests. This means that the testing should test bad values as well as good values.
Use the Proper Types
The C library function strlen(char* str) return the type size_t, this is the largest unsigned integer value the computer you are using can use. It would be much better if string_length was declared as size_t.
Initialize Variables in the Declarations
In C the language doesn't provide a default initialization of the variable so variables should be initialized as part of the declaration. For readability and maintainability each variable should be declared and initialized on its own line.
//Ask user for the credit card number and store the input in a string
char* card_number = get_string("Number: ");
// Store the string length
size_t string_length = strlen(card_number);
bool isValid = check_for_invalid_input(card_number, string_length);
Putting it All Together
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
static bool check_for_invalid_input(char* card_number, size_t len)
{
//Iterate through each character to check if it is a digit
for (int character = 0; character < len; character++)
{
if (!isdigit(card_number[character]))
{
printf("INVALID\n");
return false;
}
}
return true;
}
static int calculate_check_sum(char* card_number, size_t len)
{
int check_sum = 0; | {
"domain": "codereview.stackexchange",
"id": 43767,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "algorithm, c, homework, e-commerce, checksum",
"url": null
} |
algorithm, c, homework, e-commerce, checksum
static int calculate_check_sum(char* card_number, size_t len)
{
int check_sum = 0;
for (int character = len - 1; character >= 0; character -= 2)
{
check_sum += card_number[character] - '0';
}
for (int character = len - 2; character >= 0; character -= 2)
{
int digit = ((card_number[character] - '0') * 2);
while (digit > 0)
{
check_sum += (digit % 10);
digit /= 10;
}
}
return check_sum;
}
static void report_card_issuer(int check_sum, char* card_number, size_t string_length)
{
if (check_sum % 10 == 0 && string_length == 15 && card_number[0] == '3' && card_number[1] == '4')
{
printf("AMEX\n");
}
else if (check_sum % 10 == 0 && string_length == 15 && card_number[0] == '3' && card_number[1] == '7')
{
printf("AMEX\n");
}
else if (check_sum % 10 == 0 && string_length == 13 && card_number[0] == '4')
{
printf("VISA\n");
}
else if (check_sum % 10 == 0 && string_length == 16 && card_number[0] == '4')
{
printf("VISA\n");
}
else if (check_sum % 10 == 0 && string_length == 16 && card_number[0] == '5' && card_number[1] == '1')
{
printf("MASTERCARD\n");
}
else if (check_sum % 10 == 0 && string_length == 16 && card_number[0] == '5' && card_number[1] == '2')
{
printf("MASTERCARD\n");
}
else if (check_sum % 10 == 0 && string_length == 16 && card_number[0] == '5' && card_number[1] == '3')
{
printf("MASTERCARD\n");
}
else if (check_sum % 10 == 0 && string_length == 16 && card_number[0] == '5' && card_number[1] == '4')
{
printf("MASTERCARD\n");
}
else if (check_sum % 10 == 0 && string_length == 16 && card_number[0] == '5' && card_number[1] == '5')
{
printf("MASTERCARD\n");
}
else
{
printf("INVALID\n");
}
} | {
"domain": "codereview.stackexchange",
"id": 43767,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "algorithm, c, homework, e-commerce, checksum",
"url": null
} |
algorithm, c, homework, e-commerce, checksum
int main(void)
{
//Ask user for the credit card number and store the input in a string
char* card_number = get_string("Number: ");
// Store the string length
size_t string_length = strlen(card_number);
bool isValid = check_for_invalid_input(card_number, string_length);
if (isValid)
{
int check_sum = calculate_check_sum(card_number, string_length);
report_card_issuer(check_sum, card_number, string_length);
}
else
{
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
} | {
"domain": "codereview.stackexchange",
"id": 43767,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "algorithm, c, homework, e-commerce, checksum",
"url": null
} |
c#, random
Title: Generate random int based on a 32 characters long string seed
Question: I want to generate a random seed based on a string value (which is ~32 characters long).
I don't want to use string.GetHashCode() since I may later will need a working implementation in another language (C++, Python, JavaScript) (Yes I will need to get rid of Random() too then and all other .NET classes).
I also want the whole input string to be relevant for the seed and not just a fraction of it.
This is the solution I came up with:
Fiddle: https://dotnetfiddle.net/G9Qr7r
I basically generate 8 Random instances with a Int32 seed based on a part of the SHA256 array. Everytime I generate a random number I switch to the next Random Instance.
code:
using System;
using System.Security.Cryptography;
using System.Text;
public class Program
{
public static void Main()
{
Sha256Random rnd = new("Well, hello there");
for (int i = 0; i < 100; i++)
{
Console.WriteLine(rnd.Next(0,100));
}
}
}
public class Sha256Random
{
private int[] seeds = default!;
private Random[] rnd = new Random[8];
private int rndIdx = 0;
public Sha256Random(string seed)
{
GenerateSeeds(seed);
}
public int Next()
{
if(rndIdx>= 8)
rndIdx=0;
return rnd[rndIdx++].Next();
}
public int Next(int min, int max)
{
if (rndIdx >= 8)
rndIdx = 0;
return rnd[rndIdx++].Next(min, max);
}
public int Next(int max)
{
if (rndIdx >= 8)
rndIdx = 0;
return rnd[rndIdx++].Next(max);
}
private void GenerateSeeds(string value)
{
using var hash = SHA256.Create();
byte[] bytes = hash.ComputeHash(Encoding.ASCII.GetBytes(value));
seeds = new int[bytes.Length/4]; | {
"domain": "codereview.stackexchange",
"id": 43768,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, random",
"url": null
} |
c#, random
for (int i = 0; i < seeds.Length; i++)
{
int idx = i*4;
seeds[i] = bytes[idx] | bytes[idx+1] << 8 | bytes[idx+2] << 16 | bytes[idx+3] << 24;
}
rnd = new Random[seeds.Length];
for (int i = 0; i < seeds.Length; i++)
{
rnd[i] = new Random(seeds[i]);
}
}
}
I feel like it's overengineered?!
Answer: In general, I would prefer the simplest code that satisfies all of the criteria. In this case, that means having a single Random instance, initialized with String.GetHashCode(). I understand that GetHashCode isn't easily portable to other platforms, but neither is Random. If making it easily portable to other platforms becomes a requirement, you can replace them at that time. You might end up using SHA256 for that, and then that's one thing you wouldn't need to change, but it's also possible you would choose something else and need to change anyway.
As for the existing implementation, the seeds are only needed temporarily to initialize the Random instances and therefore should not be part of the object state. You have the value 8 hard-coded in several places, I would probably replace that with rnd.Length.
Getting further into matters of taste, I would prefer:
public int Next(int min, int max)
{
rndIdx = (rndIdx + 1) % rnd.Length;
return rnd[rndIdx].Next(min, max);
} | {
"domain": "codereview.stackexchange",
"id": 43768,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, random",
"url": null
} |
python, performance, recursion, dynamic-programming
Title: Find all non-crossing tuples which has the same content with a given tableau
Question: Let T be a semistandard Young tableau of rectangular shape. For example,
[[1,2,4],[3,5,6]]
is such a tableau, where [1,2,4] and [3,5,6] are columns. All non-crossing tuples with the same content as T are
[((1, 2, 3), (4, 5, 6)),
((1, 2, 4), (3, 5, 6)),
((1, 2, 6), (3, 4, 5)),
((1, 4, 5), (2, 3, 6)),
((1, 5, 6), (2, 3, 4))]
For example, (1,2,3), (4,5,6) are non-crossing in the sense of Definition 1.8 of page 9 of the paper (The the non-crossing property has been programmed below).
Explicitly, non-crossing property is defined as follows:
Given two k-element subsets I and J of {1, \ldots, n}, denote by min(J) the minimal element in J and by max(I) the maximal element in I, we write I < J if max(I)<min(J). The sets I and J are called weakly separated if at least one of the
following two conditions holds:
J-I can be partitioned into a disjoint union J-I = J' \sqcup J'' so that J' < I-J < J'';
I-J can be partitioned into a disjoint union I-J = I' \sqcup I'' so that I' < J-I < I''.
A pair I={i_1< \ldots < i_k}, J={j_1<\ldots<j_k} of k-element subsets of [n] is said to be non-crossing if for each 1 \le a < b \le k, either the pair {i_a, i_{a+1}, \ldots, i_b}, {j_a, j_{a+1}, \ldots, j_b} is weakly separated, or {i_{a+1}, \ldots, i_{b-1}} \ne {j_{a+1}, \ldots, j_{b-1}}.
An m-tuple (a_1, \ldots, a_m), each a_i is a sorted list, is called non-crossing m-tuple if any two a_i, a_j (i \ne j) are non-crossing.
Moreover, ((1, 2, 3), (4, 5, 6))
has content [1,2,3,4,5,6] which is the same as the content of
[[1,2,4],[3,5,6]].
I have a program which works. But I would like to make it faster.
from numpy import array
from collections import Counter
import itertools
def flatten(l):
return [item for sublist in l for item in sublist]
def NonCrossingTupleWithSameContentAsT(T):
if not T or not T[0]:
return [] | {
"domain": "codereview.stackexchange",
"id": 43769,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, recursion, dynamic-programming",
"url": null
} |
python, performance, recursion, dynamic-programming
def NonCrossingTupleWithSameContentAsT(T):
if not T or not T[0]:
return []
k = len(T[0])
m = len(T) # number of columns of T
content = sorted(flatten(T))
r=[]
for c in candidates(Counter(content), k):
if IsNonCrossingList(c):
r.append(tuple(sorted(c)))
r=removeDuplicatesListOfLists(r)
return r
def candidates(content, k):
m=sum(content.values())/k
if len(content) < k:
return
for I in itertools.combinations(content, k):
# We ensure that elements inside a k-tuple are sorted
T = (tuple(sorted(I)), )
if m == 1:
yield T
else:
for L in candidates(content - Counter(I), k):
yield T + L
def IsNonCrossing(I,J): # I,J have the same size
k = len(I)
for a in range(k - 1):
for b in range(a + 1, k):
if (I[a+1:b] == J[a+1:b] and
not IsWeaklySeparated(I[a:b+1], J[a:b+1])):
return False
return True
def IsNonCrossingList(L):
return all(IsNonCrossing(I, J) for I, J in itertools.combinations(L, 2))
def IsWeaklySeparated(I,J): # I,J have the same size
r1 = sorted(set(I).difference(J))
r2 = sorted(set(J).difference(I))
if not r1 or not r2:
return True
if min(r1) >= min(r2):
r1, r2 = r2, r1
for i in range(len(r1) - 1):
if r2[0] < r1[i+1]:
return r2[-1] <= r1[i+1]
return r1[-1] <= r2[0]
def removeDuplicatesListOfLists(l):
l.sort()
r=list(l for l,_ in itertools.groupby(l))
return r
We can test the program by
r1=[[1,2,4],[3,5,6]]
%time r3=list(NonCrossingTupleWithSameContentAsT(r1))
r3
But it takes very long time in larger example. For example,
r1=[[1, 3, 6], [1, 3, 7], [2, 4, 7], [2, 4, 9], [5, 8, 9]]
%time r3=list(NonCrossingTupleWithSameContentAsT(r1))
r3
Do you know how to make the program faster? | {
"domain": "codereview.stackexchange",
"id": 43769,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, recursion, dynamic-programming",
"url": null
} |
python, performance, recursion, dynamic-programming
Do you know how to make the program faster?
Answer: First, a general review, then a speedier solution.
Numpy is imported, but doesn't appear to be used.
PEP-8 is the recommended (not required) style guide for python code. It includes suggestions for placement of import statements, name formatting, whitespace, etc. Whatever style you chose, be consistent. Your naming style does not seem consistent: some functions start with an uppercase letter, others with a lower case letter. Same with variable names.
m doesn't appear to be used in NonCrossingTupleWithSameContentAsT()
Choose meaningful variable names. When you look at your code in 6 months, will you remember what I and J are?
As of Python 3.7, the implementation of dict remembers the order if insertion of elements. Counter is a subclass of dict, so the keys are in insertion order as well. Math operations on Counters maintain the order. If the population is sorted, itertools.combinations() produces results in order as well. So, some of the sorting calls can be eliminated.
In IsNonCrossing() it may make sense to break out of the inner loop whenever I[a+1:b] != J[a+1:b].
If you add some code to NonCrossingTupleWithSameContentAsT to count and print the number of iterations of the loop, and the length of r, before and after duplicates are removed, you will find for the second example, that there are
1074900 candidates generated,
26460 non-crossing candidates, and
236 unique non-crossing candidates. | {
"domain": "codereview.stackexchange",
"id": 43769,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, recursion, dynamic-programming",
"url": null
} |
python, performance, recursion, dynamic-programming
That's a lot of extra work.
In general, generating all possible combinations and filtering the results will be slow, except for small problems. The key is to try to only generate unique valid combinations. This can be done by modifying candidates() to check each tuple before adding it to a candidate to ensure it is non-crossing to each of the previous tuples and also not smaller than any of the previous tuples in the candidate.
With the modified candidates, my computer generates the results in about 0.25 seconds compared to 22.5 seconds for the original code.
Lastly, we can cache calls to is_noncrossing(). That reduces the time to about 0.125 seconds. A roughly 150:1 speedup.
import itertools
import functools
from collections import Counter
def flatten(l):
return [item for sublist in l for item in sublist]
def noncrossing_tuples(T):
if T and T[0]:
return list(candidates(Counter(sorted(flatten(T))), len(T[0])))
else:
return []
def candidates(content, k, candidate=()):
if len(content) < k:
if len(content) == 0 and candidate:
yield candidate
else:
return
for I in itertools.combinations(content, k):
# tuples in candidate are in non-decreaseing order
if candidate and I < candidate[-1]:
continue
# new tuple is non-crossing with the other tuples
if all(is_noncrossing(I, J) for J in candidate):
yield from candidates(content - Counter(I), k, candidate + (I,))
@functools.cache
def is_noncrossing(I,J): # I,J have the same size
k = len(I)
for a in range(k - 1):
for b in range(a + 1, k):
if (I[a+1:b] == J[a+1:b] and
not is_weakly_separated(I[a:b+1], J[a:b+1])):
return False
return True
def is_weakly_separated(I,J): # I,J have the same size
r1 = sorted(set(I).difference(J))
r2 = sorted(set(J).difference(I)) | {
"domain": "codereview.stackexchange",
"id": 43769,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, recursion, dynamic-programming",
"url": null
} |
python, performance, recursion, dynamic-programming
if not r1 or not r2:
return True
if r1[0] >= r2[0]:
r1, r2 = r2, r1
for i in range(len(r1) - 1):
if r2[0] < r1[i+1]:
return r2[-1] <= r1[i+1]
return r1[-1] <= r2[0]
Note, I haven't tested the code extensively. For the two test cases it returns the same results as yours, without checking for duplicates. But I have a nagging feeling that there may be cases where it generates duplicate candidates. So it might be wise to still check for them. | {
"domain": "codereview.stackexchange",
"id": 43769,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, recursion, dynamic-programming",
"url": null
} |
javascript, beginner, html, css
Title: Javascript : Etch-a-sketch
Question: I am a beginner in javascript and I have made this project as a part of The odin project.
Feautres:
Draw by hovering the mouse on grid
Erase
Clear the entire sketch at once
Reset the grid size
I have created the grid using only flexbox.
Here is my code:
function createGrid(grid, rowSize, colSize) {
for (let i = 0; i < rowSize; i++) {
grid[i] = document.createElement("div");
grid[i].setAttribute("id", "container");
let pixels = [];
for (let j = 0; j < colSize; j++) {
pixels[j] = document.createElement("div");
pixels[j].setAttribute("id", "pixel");
grid[i].appendChild(pixels[j]);
}
}
return grid;
}
function appendArray(pDiv, cDiv) {
cDiv.forEach((div) => pDiv.appendChild(div));
return pDiv;
}
(() => {
const GRID_WIDTH = 16;
const GRID_HEIGHT = 16;
const sketchEl = document.querySelector("#sketch");
const eraseEl = document.querySelector("#erase");
const buttonsEl = document.querySelector(".buttons");
let gridCont = document.querySelector("#grid-container");
let grid = [];
let state;
grid = createGrid(grid, GRID_WIDTH, GRID_HEIGHT);
gridCont = appendArray(gridCont, grid);
buttonsEl.addEventListener("click", changeState);
gridCont.addEventListener("mouseover", eventHandler, false); | {
"domain": "codereview.stackexchange",
"id": 43770,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, beginner, html, css",
"url": null
} |
javascript, beginner, html, css
gridCont.addEventListener("mouseover", eventHandler, false);
function changeState(event) {
state = event.target.id;
switch (state) {
case "reset":
sketchReset();
break;
case "gridSize":
sizeReset();
}
}
function sketchReset() {
const pixels = document.querySelectorAll("#pixel");
pixels.forEach((pxl) =>
pxl.setAttribute("style", "background-color:'transparent';")
);
}
function sizeReset() {
let size = parseInt(prompt("Enter grid size (MAX=100) : "));
if (size <= 100) {
grid.length = 0;
grid = createGrid(grid, size, size);
gridCont.innerHTML = "";
gridCont = appendArray(gridCont, grid);
}
}
function eventHandler(event) {
if (event.target.id !== "pixel") {
return;
}
changeColor(event);
}
function changeColor(event) {
if (state === "eraser") {
event.target.setAttribute("style", "background-color:'transparent';");
return;
}
event.target.setAttribute("style", "background-color:black;");
}
})();
body {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
#header {
font-size: 2.5em;
}
.flex-container {
display: flex;
gap: 2em;
}
.buttons {
display: flex;
flex-direction: column;
justify-content: center;
gap: 2em;
}
.button {
font-size: x-large;
}
.grid-container {
display: flex;
height: 30em;
width: 30em;
border: 1px solid black;
}
.grid-container > div {
flex: 1;
display: flex;
flex-direction: column;
} | {
"domain": "codereview.stackexchange",
"id": 43770,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, beginner, html, css",
"url": null
} |
javascript, beginner, html, css
.grid-container > div {
flex: 1;
display: flex;
flex-direction: column;
}
.grid-container > div > * {
flex: 1;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Etch-a-Sketch</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<script src="index.js" defer></script>
<h1 id="header">Etch-a-sketch!</h1>
<div class="flex-container">
<div class="buttons">
<button class="button" id="sketch">Sketch</button>
<button class="button" id="eraser">Erase</button>
<button class="button" id="reset">Reset</button>
<button class="button" id="gridSize">Grid Size</button>
</div>
<div id="grid-container" class="grid-container"></div>
</div>
</body>
</html>
Answer: I'm going to only focus on the Javascript code in my answer.
function createGrid(grid, rowSize, colSize) {
for (let i = 0; i < rowSize; i++) {
grid[i] = document.createElement("div");
grid[i].setAttribute("id", "container");
let pixels = [];
for (let j = 0; j < colSize; j++) {
pixels[j] = document.createElement("div");
pixels[j].setAttribute("id", "pixel");
grid[i].appendChild(pixels[j]);
}
}
return grid;
}
I'm not sure why this takes a grid argument, given that the name is createGrid. Just create the array within the function.
Secondly, ids are supposed to be unique. For a group of similar elements, you should use a class instead. See this SO question for more info.
function appendArray(pDiv, cDiv) {
cDiv.forEach((div) => pDiv.appendChild(div));
return pDiv;
}
There already is a function to append multiple children to an element: Element#append. The invocation is a bit different, as you'll need to use spread syntax to pass an array, ie. gridCont.append(...grid). | {
"domain": "codereview.stackexchange",
"id": 43770,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, beginner, html, css",
"url": null
} |
javascript, beginner, html, css
gridCont.addEventListener("mouseover", eventHandler, false);
eventHandler is an undescriptive name. I would rename it to something like gridMouseover.
function changeState(event) {
state = event.target.id;
switch (state) {
case "reset":
sketchReset();
break;
case "gridSize":
sizeReset();
}
}
In my opinion, reset and gridSize shouldn't affect the global state, as they are one-time actions. As written, your code works, though restructuring the code will help for future modifications.
function changeState(event) {
switch (event.target.id) {
case "reset":
sketchReset();
break;
case "gridSize":
sizeReset();
break;
case "sketch":
case "reset":
state = event.target.id;
break;
}
}
const pixels = document.querySelectorAll(".pixel");
(code modified to align with the createGrid change)
There's no need for querySelectorAll here - just use document.getElementsByClassName("pixel") for better performance and more code clarity.
function changeColor(event) {
if (state === "eraser") {
event.target.setAttribute("style", "background-color:'transparent';");
return;
}
event.target.setAttribute("style", "background-color:black;");
}
This doesn't need to use the entire event object, just the pixel element that's being hovered, so only pass that as the argument.
Full code:
function createGrid(rowSize, colSize) {
let grid = [];
for (let i = 0; i < rowSize; i++) {
grid[i] = document.createElement("div");
grid[i].setAttribute("class", "container");
let pixels = [];
for (let j = 0; j < colSize; j++) {
pixels[j] = document.createElement("div");
pixels[j].setAttribute("class", "pixel");
}
grid[i].append(...pixels);
}
return grid;
} | {
"domain": "codereview.stackexchange",
"id": 43770,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, beginner, html, css",
"url": null
} |
javascript, beginner, html, css
(() => {
const GRID_WIDTH = 16;
const GRID_HEIGHT = 16;
const sketchEl = document.querySelector("#sketch");
const eraseEl = document.querySelector("#erase");
const buttonsEl = document.querySelector(".buttons");
let gridCont = document.querySelector("#grid-container");
let state;
let grid = createGrid(GRID_WIDTH, GRID_HEIGHT);
gridCont.append(...grid);
buttonsEl.addEventListener("click", changeState);
gridCont.addEventListener("mouseover", gridMouseover, false);
function changeState(event) {
switch (event.target.id) {
case "reset":
sketchReset();
break;
case "gridSize":
sizeReset();
break;
case "sketch":
case "reset":
state = event.target.id;
break;
}
}
function sketchReset() {
const pixels = document.querySelectorAll(".pixel");
Array.from(pixels).forEach((pxl) =>
pxl.setAttribute("style", "background-color:'transparent';")
);
}
function sizeReset() {
let size = parseInt(prompt("Enter grid size (MAX=100) : "));
if (size <= 100) {
grid = createGrid(size, size);
gridCont.innerHTML = "";
gridCont.append(...grid);
}
}
function gridMouseover(event) {
if (!event.target.classList.contains("pixel")) {
return;
}
changeColor(event.target);
}
function changeColor(pixel) {
if (state === "eraser") {
pixel.setAttribute("style", "background-color:'transparent';");
return;
}
pixel.setAttribute("style", "background-color:black;");
}
})();
body {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
#header {
font-size: 2.5em;
}
.flex-container {
display: flex;
gap: 2em;
}
.buttons {
display: flex;
flex-direction: column;
justify-content: center;
gap: 2em;
}
.button {
font-size: x-large;
}
.grid-container {
display: flex;
height: 30em;
width: 30em;
border: 1px solid black;
} | {
"domain": "codereview.stackexchange",
"id": 43770,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, beginner, html, css",
"url": null
} |
javascript, beginner, html, css
.grid-container > div {
flex: 1;
display: flex;
flex-direction: column;
}
.grid-container > div > * {
flex: 1;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Etch-a-Sketch</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<script src="index.js" defer></script>
<h1 id="header">Etch-a-sketch!</h1>
<div class="flex-container">
<div class="buttons">
<button class="button" id="sketch">Sketch</button>
<button class="button" id="eraser">Erase</button>
<button class="button" id="reset">Reset</button>
<button class="button" id="gridSize">Grid Size</button>
</div>
<div id="grid-container" class="grid-container"></div>
</div>
</body>
</html>
Some suggestions for future improvements:
only draw pixels while the mouse is held - check out the mousedown and mouseup events.
display validation errors for sizeReset. | {
"domain": "codereview.stackexchange",
"id": 43770,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, beginner, html, css",
"url": null
} |
c++, game, c++20, sfml, cmake
Title: Reimplementation of Diep.io in C++ with SFML and Box2D
Question: Here's my attempt at reimplementing part of https://diep.io/, a 2D game where tanks battle with each other. The tanks are circular and they have cannons which fire bullets. The bullets can hit other tanks and they disappear after three seconds. Here's a random YouTube video if you want to see how the original game works: https://www.youtube.com/watch?v=9R6zsD5rdd8.
I'm using Box2D for the physics and SFML for graphics and input. Currently, I have only implemented basic tanks and bullets, but I want to make sure the overall structure is good before continuing so that I don't spend a bunch of time refactoring later. I plan on implementing health and damage in the future but I'm not asking for help on those.
arena.fwd.h:
#ifndef CPPDIEP_ARENA_FWD_H
#define CPPDIEP_ARENA_FWD_H
/// @file
/// Forward declaration for Arena used to avoid circular dependencies.
namespace cppdiep {
class Arena;
} // namespace cppdiep
#endif // CPPDIEP_ARENA_FWD_H
arena.h:
#ifndef CPPDIEP_ARENA_H
#define CPPDIEP_ARENA_H
#include "arena.fwd.h"
#include <concepts>
#include <cstdint>
#include <memory>
#include <utility>
#include <vector>
#include <Box2D/Common/b2Math.h>
#include <Box2D/Dynamics/b2World.h>
#include <SFML/Graphics/Color.hpp>
#include <SFML/Graphics/RenderTarget.hpp>
#include "bullet.h"
#include "tank.h"
#include "time.h"
namespace cppdiep {
/// The Arena class manages all of the objects in the game.
class Arena {
public:
/// Construct an arena.
/// @param size the side length of the arena.
/// @param time_step the number of seconds that each time step represents.
Arena(float size, float time_step);
/// Draw the arena to an SFML render target.
/// @param target the SFML render target to draw to.
void draw(sf::RenderTarget &target) const;
/// Advance the state of the arena by one time step.
void step(); | {
"domain": "codereview.stackexchange",
"id": 43771,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, game, c++20, sfml, cmake",
"url": null
} |
c++, game, c++20, sfml, cmake
/// Advance the state of the arena by one time step.
void step();
/// Spawn a non-tank object in the arena.
/// @tparam ObjectType the type of the object to spawn
/// @param args the arguments to be forwarded to the object's constructor
/// @return A reference to the new object.
// clang-format and doxygen doen't handle the requires expression properly.
// clang-format off
template <std::derived_from<Object> ObjectType, typename... Args>
/// @cond
requires(!std::derived_from<ObjectType, Tank>)
/// @endcond
ObjectType &spawnObject(Args &&...args) {
ObjectType *object = new ObjectType(*this, std::forward<Args>(args)...);
objects.emplace_back(object);
return *object;
}
// clang-format on
/// Spawn a tank in the arena.
/// @tparam TankType the type of the tank to spawn
/// @param args the arguments to be forwarded to the tank's constructor
/// @return A reference to the new tank.
template <std::derived_from<Tank> TankType, typename... Args>
TankType &spawnObject(Args &&...args) {
TankType *tank = new TankType(*this, std::forward<Args>(args)...);
tanks.emplace_back(tank);
return *tank;
}
/// Get the time step size.
/// @return The time step size.
float getTimeStep() const { return time_step; }
/// Get the current time.
/// @return The current time in steps.
Time getTime() const { return time; }
private:
friend Object;
/// Alias for the type of the smart pointers used to store the polymorphic
/// objects.
/// @tparam ObjectType the type of the object that the pointer points to.
template <std::derived_from<Object> ObjectType>
using ObjectPtr = std::unique_ptr<ObjectType, typename ObjectType::Deleter>;
/// Alias for the type of the container used to store objects.
/// @tparam ObjectType the type of the objects stored in the container.
template <std::derived_from<Object> ObjectType>
using ObjectContainer = std::vector<ObjectPtr<ObjectType>>; | {
"domain": "codereview.stackexchange",
"id": 43771,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, game, c++20, sfml, cmake",
"url": null
} |
c++, game, c++20, sfml, cmake
/// Get the arena's Box2D world.
/// @return A reference to the arena's Box2D world.
b2World &getB2World() { return b2_world; }
/// @copydoc getB2World()
const b2World &getB2World() const { return b2_world; }
/// The Box2D world of the arena. The gravity vector is zero since the world
/// is horizontal. This has to be destructed after all of the objects have
/// been destructed since the destructors of the objects will access the world
/// to destroy their bodies.
b2World b2_world{b2Vec2(0.f, 0.f)};
/// Container of all of the objects in the arena except for tanks.
ObjectContainer<Object> objects;
/// Container of all of the tanks in the arena. Tank barrels can overlap with
/// other objects, so they have to be kept separately and drawn in a
/// consistent order after other objects.
ObjectContainer<Tank> tanks;
/// The number of seconds in each time step.
const float time_step;
/// The current time as the number of time steps since the arena was created.
Time time = 0;
};
} // namespace cppdiep
#endif // CPPDIEP_ARENA_H
arena.cpp:
#include "arena.h"
#include <array>
#include <concepts>
#include <memory>
#include <utility>
#include <vector>
#include <Box2D/Collision/Shapes/b2ChainShape.h>
#include <Box2D/Common/b2Math.h>
#include <Box2D/Dynamics/b2Body.h>
#include <Box2D/Dynamics/b2Fixture.h>
#include <Box2D/Dynamics/b2World.h>
#include <SFML/Graphics/RenderTarget.hpp>
#include "box2d_categories.h"
#include "bullet.h"
#include "render_utils.h"
#include "tank.h"
#include "time.h"
namespace cppdiep { | {
"domain": "codereview.stackexchange",
"id": 43771,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, game, c++20, sfml, cmake",
"url": null
} |
c++, game, c++20, sfml, cmake
namespace cppdiep {
Arena::Arena(float size, float time_step) : time_step(time_step) {
b2BodyDef border_body_def;
b2Body &border_body = *b2_world.CreateBody(&border_body_def);
std::array border_vertices = {
b2Vec2(size / 2.f, size / 2.f), b2Vec2(-size / 2.f, size / 2.f),
b2Vec2(-size / 2.f, -size / 2.f), b2Vec2(size / 2.f, -size / 2.f)};
b2ChainShape border_chain;
border_chain.CreateLoop(border_vertices.data(), border_vertices.size());
b2FixtureDef border_fixture_def;
border_fixture_def.shape = &border_chain;
border_fixture_def.friction = 0.25f;
border_fixture_def.restitution = 0.25f;
border_fixture_def.filter.categoryBits = box2d_categories::BORDER;
border_fixture_def.filter.maskBits = box2d_categories::TANK;
border_body.CreateFixture(&border_fixture_def);
}
void Arena::draw(sf::RenderTarget &target) const {
target.clear(colors::BACKGROUND);
// Bullets are drawn first so that they are underneath the tank barrels.
for (const ObjectPtr<Object> &object : objects) {
object->draw(target);
}
for (const ObjectPtr<Tank> &tank : tanks) {
tank->draw(target);
}
}
void Arena::step() {
// Replace objects that need to be destroyed with objects moved from the end
// of the vector. Iterating in reverse simplifies things since we don't have
// to worry about skipping over objects when removing an object.
auto new_end = objects.end();
for (auto it = objects.rbegin(); it != objects.rend(); ++it) {
if ((*it)->step()) {
*it = std::move(*--new_end);
}
}
objects.erase(new_end, objects.end());
// The tanks have to be rendered in a consistent order because their barrels
// may overlap with other tanks.
std::erase_if(tanks,
[](const ObjectPtr<Tank> &tank) { return tank->step(); });
b2_world.Step(time_step, 8, 3);
++time;
}
} // namespace cppdiep
object.h:
#ifndef CPPDIEP_OBJECT_H
#define CPPDIEP_OBJECT_H | {
"domain": "codereview.stackexchange",
"id": 43771,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, game, c++20, sfml, cmake",
"url": null
} |
c++, game, c++20, sfml, cmake
} // namespace cppdiep
object.h:
#ifndef CPPDIEP_OBJECT_H
#define CPPDIEP_OBJECT_H
#include <Box2D/Common/b2Math.h>
#include <Box2D/Dynamics/b2Body.h>
#include <Box2D/Dynamics/b2World.h>
#include <SFML/Graphics/RenderTarget.hpp>
#include "arena.fwd.h"
namespace cppdiep {
/// A game object, such as a tank, a bullet, or a polygon.
class Object {
public:
Object(const Object &) = delete;
/// Get the current position of the object.
/// @return The current position of the object.
b2Vec2 getPosition() const { return getB2Body().GetPosition(); }
/// Get the current velocity of the object.
/// @return The current velocity of the object.
b2Vec2 getVelocity() const { return getB2Body().GetLinearVelocity(); }
/// Draw the object to an SFML render target.
/// @param target the SFML render target to draw to.
virtual void draw(sf::RenderTarget &target) const = 0;
protected:
/// Construct an object.
/// @param arena the arena that contains the object. The object will keep a
/// reference to the arena so the
/// @param b2_body_def the Box2D body definition that will be used to create
/// the object's body.
Object(Arena &arena, const b2BodyDef &b2_body_def);
/// Destruct an object.
virtual ~Object();
/// Advance the state of the object by one time step and return whether the
/// object should be destroyed now.
/// @return Whether the object should be destroyed now.
virtual bool step() {
// Health and damage haven't been implemented yet so this just returns
// false.
return false;
}
/// Get a reference to the arena that contains the object.
/// @return A reference to the arena that contains the object.
Arena &getArena() const { return arena; }
/// Get a reference to the Box2D body of the object.
/// @return A reference to the Box2D body of the object.
b2Body &getB2Body() { return b2_body; }
/// @copydoc getB2Body()
const b2Body &getB2Body() const { return b2_body; }
private:
friend Arena; | {
"domain": "codereview.stackexchange",
"id": 43771,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, game, c++20, sfml, cmake",
"url": null
} |
c++, game, c++20, sfml, cmake
private:
friend Arena;
/// A deleter that the arena passes to the smart pointer. This is necessary
/// since the destructor is not public.
struct Deleter {
void operator()(Object *object) const { delete object; }
};
/// The arena that contains the object.
Arena &arena;
/// The Box2D body of the object.
b2Body &b2_body;
};
} // namespace cppdiep
#endif // CPPDIEP_OBJECT_H
object.cpp:
#include "object.h"
#include "arena.h"
namespace cppdiep {
Object::Object(Arena &arena, const b2BodyDef &b2_body_def)
: arena(arena), b2_body(*arena.getB2World().CreateBody(&b2_body_def)) {}
Object::~Object() { arena.getB2World().DestroyBody(&b2_body); }
} // namespace cppdiep
tank.h:
#ifndef CPPDIEP_TANK_H
#define CPPDIEP_TANK_H
#include <Box2D/Collision/Shapes/b2Shape.h>
#include <Box2D/Common/b2Math.h>
#include <Box2D/Dynamics/b2Body.h>
#include <Box2D/Dynamics/b2Fixture.h>
#include <Box2D/Dynamics/b2World.h>
#include <SFML/Graphics/Color.hpp>
#include <SFML/Graphics/RenderTarget.hpp>
#include "arena.fwd.h"
#include "object.h"
#include "render_utils.h"
namespace cppdiep {
/// A generic tank.
class Tank : public Object {
public:
/// Get the radius of the tank body.
/// @return the radius of the tank body.
float getRadius() const {
return getB2Body().GetFixtureList()->GetShape()->m_radius;
}
/// Get the current target position of the tank.
/// @return the target position of the tank relative to the tank's position.
virtual b2Vec2 getTarget() const = 0;
/// Get the direction of the tank's target relative to the tank.
/// @return The direction of the tank's target as an angle in radians.
float getTargetAngle() const {
b2Vec2 target = getTarget();
return std::atan2(target.y, target.x);
}
/// Get the color of the tank.
/// @return The color of the tank.
sf::Color getColor() const { return color; }
void draw(sf::RenderTarget &target) const override; | {
"domain": "codereview.stackexchange",
"id": 43771,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, game, c++20, sfml, cmake",
"url": null
} |
c++, game, c++20, sfml, cmake
void draw(sf::RenderTarget &target) const override;
protected:
/// Construct a Tank.
/// @param arena the arena that contains the tank.
/// @param position the initial position of the tank.
/// @param radius the radius of the tank's body.
/// @param color the color of the tank.
Tank(Arena &arena, const b2Vec2 &position, float radius,
const sf::Color &color);
/// Helper function for drawing cannons.
/// @param target the SFML render target to draw to.
/// @param length the length of the barrel. The barrel starts from the center
/// of the tank.
/// @param width the width of the barrel.
/// @param angle the angle that the cannon is pointing towards in radians.
void drawCannon(sf::RenderTarget &target, float length, float width,
float angle) const;
/// Apply a force to move the tank.
/// @param vec the direction and speed to move in. A magnitude of 1 represents
/// full speed.
void move(const b2Vec2 &vec) {
getB2Body().ApplyForceToCenter(getMoveForce() * vec, true);
}
/// Fire the tank's cannon(s).
virtual void fire() = 0;
private:
friend Arena;
/// Draw the tank's cannon(s).
/// @param target the SFML render target to draw to.
virtual void drawCannons(sf::RenderTarget &target) const = 0;
/// Get the magnitude of the force used to move the tank.
/// @param the magnitude of the force used to move the tank.
virtual float getMoveForce() const = 0;
/// The color of the tank.
sf::Color color;
};
} // namespace cppdiep
#endif // CPPDIEP_TANK_H
tank.cpp:
#include "tank.h"
#include <Box2D/Collision/Shapes/b2CircleShape.h>
#include <Box2D/Common/b2Math.h>
#include <Box2D/Dynamics/b2Body.h>
#include <Box2D/Dynamics/b2Fixture.h>
#include <Box2D/Dynamics/b2World.h>
#include <SFML/Graphics/CircleShape.hpp>
#include <SFML/Graphics/Color.hpp>
#include <SFML/Graphics/RectangleShape.hpp>
#include <SFML/Graphics/RenderTarget.hpp> | {
"domain": "codereview.stackexchange",
"id": 43771,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, game, c++20, sfml, cmake",
"url": null
} |
c++, game, c++20, sfml, cmake
#include "arena.h"
#include "box2d_categories.h"
#include "render_utils.h"
namespace cppdiep {
namespace {
b2BodyDef makeB2BodyDef(const b2Vec2 &position) {
b2BodyDef body_def;
body_def.type = b2_dynamicBody;
body_def.position = position;
body_def.fixedRotation = true;
body_def.linearDamping = 1.f;
return body_def;
}
} // namespace
Tank::Tank(Arena &arena, const b2Vec2 &position, float radius,
const sf::Color &color)
: Object(arena, makeB2BodyDef(position)), color(color) {
b2CircleShape body_shape;
body_shape.m_radius = radius;
b2FixtureDef fixture_def;
fixture_def.shape = &body_shape;
fixture_def.density = 1.f;
fixture_def.friction = 0.3f;
fixture_def.restitution = 0.25f;
fixture_def.filter.categoryBits = box2d_categories::TANK;
fixture_def.filter.maskBits = box2d_categories::TANK |
box2d_categories::BORDER |
box2d_categories::BULLET;
getB2Body().CreateFixture(&fixture_def);
}
void Tank::draw(sf::RenderTarget &target) const {
drawCannons(target);
drawCircle(target, getPosition(), getRadius(), getColor());
}
void Tank::drawCannon(sf::RenderTarget &target, float length, float width,
float angle) const {
sf::RectangleShape cannon_shape(sf::Vector2f(length, width));
cannon_shape.setOrigin(0.f, width / 2.f);
cannon_shape.setPosition(convertVector(getPosition()));
cannon_shape.setFillColor(colors::CANNON);
cannon_shape.setOutlineThickness(OUTLINE_THICKNESS);
cannon_shape.setOutlineColor(darken(colors::CANNON));
cannon_shape.setRotation(radiansToDegrees(angle));
target.draw(cannon_shape);
}
} // namespace cppdiep
basic_tank.h:
#ifndef CPPDIEP_BASIC_TANK_H
#define CPPDIEP_BASIC_TANK_H
#include <SFML/Graphics/RenderTarget.hpp>
#include "tank.h"
namespace cppdiep {
/// A tank with a single cannon.
class BasicTank : public Tank {
protected:
using Tank::Tank;
void fire() override; | {
"domain": "codereview.stackexchange",
"id": 43771,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, game, c++20, sfml, cmake",
"url": null
} |
c++, game, c++20, sfml, cmake
private:
void drawCannons(sf::RenderTarget &target) const override;
float getMoveForce() const override { return 15.f * getRadius(); }
};
} // namespace cppdiep
#endif // CPPDIEP_BASIC_TANK_H
basic_tank.cpp:
#include "basic_tank.h"
#include <cmath>
#include <Box2D/Common/b2Math.h>
#include <SFML/Graphics/RenderTarget.hpp>
#include "arena.h"
#include "bullet.h"
namespace cppdiep {
void BasicTank::drawCannons(sf::RenderTarget &target) const {
float radius = getRadius();
drawCannon(target, 2 * radius, radius, getTargetAngle());
}
void BasicTank::fire() {
b2Vec2 target_vec = getTarget();
target_vec.Normalize();
float bullet_radius = getRadius() / 2.f;
float impulse_magnitude = 10.f * getRadius();
// The bullet is spawned in the barrel just outside of the tank body to avoid
// teleportation due to the bullet intersecting the tank body. This causes
// some teleportation if the spawned bullet intersects another object. In the
// future, collisions between a bullet and the tank that fired it will be
// disabled and the bullet will be spawned inside the tank body.
getArena().spawnObject<Bullet>(
getPosition() + (getRadius() + bullet_radius) * target_vec, getVelocity(),
impulse_magnitude * target_vec, bullet_radius, getColor());
// Simulate recoil by applying the same impulse in the opposite direction to
// the tank.
getB2Body().ApplyLinearImpulse(-impulse_magnitude * target_vec,
getB2Body().GetWorldCenter(), true);
}
} // namespace cppdiep
external_control_tank.h:
#ifndef CPPDIEP_EXTERNAL_CONTROL_TANK_H
#define CPPDIEP_EXTERNAL_CONTROL_TANK_H
#include <concepts>
#include <Box2D/Common/b2Math.h>
#include "tank.h"
namespace cppdiep { | {
"domain": "codereview.stackexchange",
"id": 43771,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, game, c++20, sfml, cmake",
"url": null
} |
c++, game, c++20, sfml, cmake
#include <concepts>
#include <Box2D/Common/b2Math.h>
#include "tank.h"
namespace cppdiep {
/// A tank controlled externally using the move() and fire() methods.
/// @tparam BaseTank the type of the tank to be controlled externally.
template <std::derived_from<Tank> BaseTank>
class ExternalControlTank final : public BaseTank {
public:
using BaseTank::BaseTank;
/// Apply a force to move the tank in the direction of the given vector.
/// @param vec a vector indicating the direction and speed to move in. A
/// magnitude of 1 indicates full speed.
void move(const b2Vec2 &vec) { BaseTank::move(vec); }
/// @copydoc Tank::getTarget()
b2Vec2 getTarget() const override { return target; }
/// Set the target point of the tank. This is the point that the tank will aim
/// towards.
/// @param target the target point relative to the position of the tank.
void setTarget(const b2Vec2 &target) { this->target = target; }
/// Fire the tank's cannon(s).
void fire() { BaseTank::fire(); }
private:
/// The current target point of the tank.
b2Vec2 target{0.f, 0.f};
};
} // namespace cppdiep
#endif // CPPDIEP_EXTERNAL_CONTROL_TANK_H
bullet.h:
#ifndef CPPDIEP_BULLET_H
#define CPPDIEP_BULLET_H
#include <Box2D/Common/b2Math.h>
#include <Box2D/Dynamics/b2Body.h>
#include <Box2D/Dynamics/b2Fixture.h>
#include <Box2D/Dynamics/b2World.h>
#include <SFML/Graphics/RenderTarget.hpp>
#include "arena.fwd.h"
#include "object.h"
#include "render_utils.h"
#include "time.h"
namespace cppdiep {
/// A bullet fired from a cannon. Bullets disappear after three seconds.
class Bullet : public Object {
public:
/// Get the radius of the bullet.
/// @return The radius of the bullet.
float getRadius() const {
return getB2Body().GetFixtureList()->GetShape()->m_radius;
}
void draw(sf::RenderTarget &target) const override; | {
"domain": "codereview.stackexchange",
"id": 43771,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, game, c++20, sfml, cmake",
"url": null
} |
c++, game, c++20, sfml, cmake
void draw(sf::RenderTarget &target) const override;
protected:
/// Construct a bullet.
/// @param arena the arena that contains the bullet.
/// @param position the initial position of the bullet.
/// @param velocity the initial velocity of the bullet.
/// @param impulse the impulse applied to the bullet on top of the initial
/// velocity.
/// @param radius the radius of the bullet.
/// @param color the color of the bullet.
Bullet(Arena &arena, const b2Vec2 &position, const b2Vec2 &velocity,
const b2Vec2 &impulse, float radius, const sf::Color &color);
bool step() override;
private:
friend Arena;
/// The color of the bullet.
sf::Color color;
/// The time when the bullet should be destroyed.
Time destroy_time;
};
} // namespace cppdiep
#endif // CPPDIEP_BULLET_H
bullet.cpp:
#include "bullet.h"
#include <Box2D/Collision/Shapes/b2CircleShape.h>
#include <Box2D/Dynamics/b2Body.h>
#include <Box2D/Dynamics/b2World.h>
#include <SFML/Graphics/RenderTarget.hpp>
#include "arena.h"
#include "box2d_categories.h"
#include "render_utils.h"
namespace cppdiep {
namespace {
b2BodyDef makeB2BodyDef(const b2Vec2 &position, const b2Vec2 &velocity) {
b2BodyDef body_def;
body_def.type = b2_dynamicBody;
body_def.position = position;
body_def.linearVelocity = velocity;
body_def.linearDamping = 0.5f;
body_def.angularDamping = 0.5f;
body_def.bullet = true;
return body_def;
}
} // namespace | {
"domain": "codereview.stackexchange",
"id": 43771,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, game, c++20, sfml, cmake",
"url": null
} |
c++, game, c++20, sfml, cmake
Bullet::Bullet(Arena &arena, const b2Vec2 &position, const b2Vec2 &velocity,
const b2Vec2 &impulse, float radius, const sf::Color &color)
: Object(arena, makeB2BodyDef(position, velocity)), color(color),
destroy_time(arena.getTime() + 3.f / arena.getTimeStep()) {
b2CircleShape body_shape;
body_shape.m_radius = radius;
b2FixtureDef fixture_def;
fixture_def.shape = &body_shape;
fixture_def.density = 1.f;
fixture_def.friction = 0.3f;
fixture_def.restitution = 0.25f;
fixture_def.filter.categoryBits = box2d_categories::BULLET;
fixture_def.filter.maskBits =
box2d_categories::BULLET | box2d_categories::TANK;
getB2Body().CreateFixture(&fixture_def);
getB2Body().ApplyLinearImpulse(impulse, getB2Body().GetWorldCenter(), true);
}
void Bullet::draw(sf::RenderTarget &target) const {
drawCircle(target, getPosition(), getRadius(), color);
}
bool Bullet::step() {
if (Object::step()) {
return true;
}
return getArena().getTime() >= destroy_time;
}
} // namespace cppdiep
box2d_categories.h:
#ifndef CPPDIEP_B2_CATEGORIES_H
#define CPPDIEP_B2_CATEGORIES_H
#include <Box2D/Common/b2Settings.h>
namespace cppdiep {
/// Box2D collision category bitmasks.
namespace box2d_categories {
/// Box2D collision category bitmask for the arena border.
inline constexpr uint16 BORDER = 1u << 0;
/// Box2D collision category bitmask for tanks.
inline constexpr uint16 TANK = 1u << 1;
/// Box2D collision category bitmask for bullets.
inline constexpr uint16 BULLET = 1u << 2;
} // namespace box2d_categories
} // namespace cppdiep
#endif // CPPDIEP_B2_CATEGORIES_H
render_utils.h:
#ifndef CPPDIEP_RENDER_UTILS_H
#define CPPDIEP_RENDER_UTILS_H
/// @file
/// Constants and helper functions used for rendering.
#include <numbers>
#include <Box2D/Common/b2Math.h>
#include <SFML/Graphics/CircleShape.hpp>
#include <SFML/Graphics/Color.hpp>
#include <SFML/Graphics/RenderTarget.hpp>
#include <SFML/System/Vector2.hpp>
namespace cppdiep { | {
"domain": "codereview.stackexchange",
"id": 43771,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, game, c++20, sfml, cmake",
"url": null
} |
c++, game, c++20, sfml, cmake
namespace cppdiep {
/// Colors used for rendering.
namespace colors {
/// Color for blue tanks and bullets.
inline const sf::Color BLUE(0, 178, 225);
/// Color for red tanks and bullets.
inline const sf::Color RED(241, 78, 84);
/// Color for tank cannons.
inline const sf::Color CANNON(153, 153, 153);
/// Background color of the arena.
inline const sf::Color BACKGROUND(205, 205, 205);
} // namespace colors
/// The thickness of the outlines around the objects. This is negative to make
/// the outline inside the edge of the object.
inline constexpr float OUTLINE_THICKNESS = -0.125f;
/// Darken a color to get the color of the outline.
/// @param color the color to darken.
/// @return The darkened color.
inline sf::Color darken(const sf::Color &color) {
return sf::Color(color.r * 0.75, color.g * 0.75, color.b * 0.75, color.a);
}
/// Draw a circle.
/// @param target the SFML render target to draw to.
/// @param position the position of the center of the circle.
/// @param radius the radius of the circle.
/// @param color the color of the circle.
inline void drawCircle(sf::RenderTarget &target, const b2Vec2 &position,
float radius, const sf::Color &color) {
sf::CircleShape shape(radius);
shape.setOrigin(radius, radius);
shape.setPosition(position.x, position.y);
shape.setFillColor(color);
shape.setOutlineThickness(OUTLINE_THICKNESS);
shape.setOutlineColor(darken(color));
target.draw(shape);
}
/// Convert radians to degrees.
/// @param radians an angle in radians.
/// @return The angle in degrees.
inline float radiansToDegrees(float radians) {
return radians * 180.f / std::numbers::pi_v<float>;
}
/// Convert a Box2D vector to an SFML vector.
/// @param b2_vec a Box2D vector.
/// @return The SFML vector.
inline sf::Vector2f convertVector(const b2Vec2 &b2_vec) {
return sf::Vector2f(b2_vec.x, b2_vec.y);
} | {
"domain": "codereview.stackexchange",
"id": 43771,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, game, c++20, sfml, cmake",
"url": null
} |
c++, game, c++20, sfml, cmake
/// Convert an SFML vector to a Box2D vector.
/// @param sf_vec an SFML vector.
/// @return The Box2D vector.
inline b2Vec2 convertVector(const sf::Vector2f &sf_vec) {
return b2Vec2(sf_vec.x, sf_vec.y);
}
} // namespace cppdiep
#endif // CPPDIEP_RENDER_UTILS_H
time.h:
#ifndef CPPDIEP_TIME_H
#define CPPDIEP_TIME_H
#include <cstdint>
namespace cppdiep {
/// The signed integer type that will be used to represent time in the arena as
/// a number of steps.
using Time = std::int64_t;
} // namespace cppdiep
#endif // CPPDIEP_TIME_H
main.cpp:
#include <Box2D/Common/b2Math.h>
#include <SFML/Graphics/RenderWindow.hpp>
#include <SFML/Graphics/View.hpp>
#include <SFML/Window/ContextSettings.hpp>
#include <SFML/Window/Event.hpp>
#include <SFML/Window/Keyboard.hpp>
#include <SFML/Window/Mouse.hpp>
#include "arena.h"
#include "basic_tank.h"
#include "external_control_tank.h"
#include "render_utils.h"
int main() {
// Set up the window.
sf::ContextSettings settings;
settings.antialiasingLevel = 4;
sf::RenderWindow window(sf::VideoMode(800, 800), "CppDiep",
sf::Style::Titlebar | sf::Style::Close, settings);
constexpr int frame_rate = 60;
window.setFramerateLimit(frame_rate);
constexpr float arena_size = 20.f;
// The Y size of the view is negative to flip things vertically since SFML
// uses a downwards vertical axis while the arena uses an upwards vertical
// axis.
sf::View view(sf::Vector2f(0.f, 0.f), sf::Vector2f(arena_size, -arena_size));
window.setView(view);
// Create the arena and spawn two tanks for testing.
cppdiep::Arena arena(arena_size, 1.f / frame_rate);
auto &tank =
arena.spawnObject<cppdiep::ExternalControlTank<cppdiep::BasicTank>>(
b2Vec2(0.f, 0.f), 1.f, cppdiep::colors::BLUE);
arena.spawnObject<cppdiep::ExternalControlTank<cppdiep::BasicTank>>(
b2Vec2(0.f, 5.f), 1.f, cppdiep::colors::RED); | {
"domain": "codereview.stackexchange",
"id": 43771,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, game, c++20, sfml, cmake",
"url": null
} |
c++, game, c++20, sfml, cmake
while (window.isOpen()) {
// Make the tank cannon point towards the mouse.
b2Vec2 mouse_position = cppdiep::convertVector(
window.mapPixelToCoords(sf::Mouse::getPosition(window)));
tank.setTarget(mouse_position - tank.getPosition());
// Process events.
sf::Event event;
while (window.pollEvent(event)) {
if (event.type == sf::Event::Closed) {
window.close();
} else if (event.type == sf::Event::MouseButtonPressed &&
event.mouseButton.button == sf::Mouse::Left) {
tank.fire();
}
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::W)) {
tank.move(b2Vec2(0.f, 1.f));
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::A)) {
tank.move(b2Vec2(-1.f, 0.f));
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::S)) {
tank.move(b2Vec2(0.f, -1.f));
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::D)) {
tank.move(b2Vec2(1.f, 0.f));
}
arena.step();
arena.draw(window);
window.display();
}
}
CMakeLists.txt:
cmake_minimum_required(VERSION 3.18)
project(
CppDiep
DESCRIPTION "Diep.io reimplemented in C++ with SFML and Box2D"
LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
if(MSVC)
add_compile_options(/W4 /WX)
else()
add_compile_options(-Wall -Wextra -pedantic -Werror)
endif()
find_package(
SFML 2.5
COMPONENTS graphics
REQUIRED)
find_package(Box2D REQUIRED)
add_executable(cppdiep arena.cpp basic_tank.cpp bullet.cpp main.cpp object.cpp
tank.cpp)
target_link_libraries(cppdiep PRIVATE sfml-graphics Box2D)
Github link: https://github.com/bkrl/cppdiep/tree/72222654a22320b2372a306894047e59ecace9a8
When you run the code, it should create a window with a blue tank and a red tank. You can move the blue tank with the WASD keys and aim with the mouse. Left-clicking will fire a bullet. Bullets collide with tanks but should pass through the border. | {
"domain": "codereview.stackexchange",
"id": 43771,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, game, c++20, sfml, cmake",
"url": null
} |
c++, game, c++20, sfml, cmake
Answer: Overall the code looks quite nice; a lot of attention to details of the C++ language, it's readable and concise.
Upgrade Box2D
It seems you are using an older version of Box2D. Since Box2D 2.4.0, the structure of the header files has changed significantly, and your code doesn't compile with the newer version.
If you are "stuck" with an old version of a library and can't upgrade it (yet), then at least make sure the documentation and build system of your project correctly specify the desired version of that library.
Template specialization vs. if constexpr
I see you have two specializations of spawnObject(); one that spawns non-Tank objects, one that spawns Tanks. However, the code it mostly identical except for the container in which the object is put. Consider using if constexpr instead:
template <std::derived_from<Object> ObjectType, typename... Args>
ObjectType &spawnObject(Args &&...args) {
ObjectType *object = new ObjectType(*this, std::forward<Args>(args)...);
if constexpr (std::derived_from<ObejctType, Tank>) {
tanks.emplace_back(object);
} else {
objects.emplace_back(object);
}
return *object;
} | {
"domain": "codereview.stackexchange",
"id": 43771,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, game, c++20, sfml, cmake",
"url": null
} |
c++, game, c++20, sfml, cmake
Use more auto where appropriate
In Arena::draw(), you can use auto inside the for-statements to avoid having to write out the types of object and tank.
In Arena::step(), you can use auto in the parameter list of the lambda you pass to std::erase_if().
While auto might hide the type of a variable you declare, often you don't care about the actual type. Furthermore, type deducation can sometimes prevent errors; sometimes you can write the wrong type name but an implicit cast is possible, so the compiler won't complain.
Use algorithms consistently
It looks to me like you should be able to use std::erase_if() for objects in Arena::step(), just like you do for tanks.
If you don't need the algorithm to preserve order, consider using std::ranges::partition() (see this post).
Don't store a reference to the Arena in Object
Your game has only one Arena, but you add a reference to it to every instance of Object. Apart from the constructor using it to initialize b2_body, most objects don't need that reference afterwards. Instead, consider passing a reference to arena only to those functions that need it, like BasicTank::fire() and Bullet::step().
You can even remove the use of getArena() from Bullet::step(), by having Bullet not store the "destroy time" of the bullet, but just the remaining steps left, and then decrement that each time step() is called.
Naming things
spawnObject() could be renamed to spawn(), the Object part looks redundant.
convertVector() is a bit vague. Also, what if you had three vector types to deal with in your code? I'd split the two overloads into to_Vector2f() and a to_b2Vec2().
drawCannons() implies it draws multiple cannons, yet only one cannon is ever drawn per tank. Are you planning for multi-cannon tanks? If not I would rename it to drawCannon().
Reduce the size of main()
Most of your functions are very small, but main() stands out as being the longest. Consider refactoring it and splitting off some of the things it does into separate functions. | {
"domain": "codereview.stackexchange",
"id": 43771,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, game, c++20, sfml, cmake",
"url": null
} |
c#, enum
Title: Parse Flags enum from array of booleans
Question: I need to get from an array of booleans to a Flags enum.
Here's what my enum looks like:
[Flags]
public enum UserContactPreferences { None = 0, SMS = 1, Email = 2, Phone = 4 }
Here's what my parsing code looks like currently.
private UserContactPreferences GetContactPreferences(bool email, bool phone, bool sms)
{
var contactByEmail = email ? UserContactPreferences.Email : UserContactPreferences.None;
var contactByPhone = phone ? UserContactPreferences.Phone : UserContactPreferences.None;
var contactBySms = sms ? UserContactPreferences.SMS : UserContactPreferences.None;
return contactByEmail | contactByPhone | contactBySms;
}
That's horrible! I must be able to do better. Any ideas?
Answer: Well, you need some sort of mapping between the parameters and the enum values, so you can't actually avoid having three almost same pieces of code. But you can make your code shorter by using ifs and |= instead of ternary operators:
private UserContactPreferences GetContactPreferences(bool email, bool phone, bool sms)
{
var preferences = UserContactPreferences.None;
if (email)
preferences |= UserContactPreferences.Email;
if (phone)
preferences |= UserContactPreferences.Phone;
if (sms)
preferences |= UserContactPreferences.SMS;
return preferences;
}
If you had more parameters (though that would be a code smell), it might be worth considering something like using a dictionary. But I'm not sure it's a good idea, it's certainly longer than the previous version:
private UserContactPreferences GetContactPreferences(bool email, bool phone, bool sms)
{
var dictionary = new Dictionary<UserContactPreferences, bool>
{
{ UserContactPreferences.Email, email },
{ UserContactPreferences.Phone, phone },
{ UserContactPreferences.SMS, sms }
};
var preferences = UserContactPreferences.None; | {
"domain": "codereview.stackexchange",
"id": 43772,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, enum",
"url": null
} |
c#, enum
var preferences = UserContactPreferences.None;
foreach (var kvp in dictionary)
{
if (kvp.Value)
preferences |= kvp.Key;
}
return preferences;
} | {
"domain": "codereview.stackexchange",
"id": 43772,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, enum",
"url": null
} |
json, typescript
Title: Converting one JSON schema to another
Question: Recently on Stack Overflow, a now deleted question was wondering how to convert one particular model of JSON that their code was outputting to another. The OPs main issue was that the JSON generated by their sheet_to_json (I assume it was some sort of CSV file) looked like so:
[
{ 'First name': 'A', 'Last Name': 'B', 'Some random number': 3 },
{ 'First name': 'C', 'Last Name': 'D', 'Some random number': 5 },
{ 'First name': 'E', 'Last Name': 'F', 'Some random number': 8 }
]
However, the model they wanted and what they send to the DB looked like so:
export interface SomeInterface {
firstName: string,
lastName: string,
someRandomNumber: number
}
this got me thinking as to how a method that can convert one style to another would look like. After much trial and error, and googling, I came up with the following:
function mapData(state: any, mapper: Record<string, string>) {
let final : SomeInterface []= [];
state.forEach((x, i) => {
let initialValue: any = {};
let obj : any = {};
let converted = Object.keys(x).map((z : string) => {
let mappedLabel = mapper[z];
obj[mappedLabel] = (x as any)[z];
return {...obj};
}, {}).reduce((obj2, item) => {
return {
...obj2,
[i]: item
}
}, initialValue)
//State before the below code is "0" : {..myModel}, "1": {...myModel}
// hence the extra object.keys to get the actual model that is behind the indexed key
Object.keys(converted).forEach(x => {
let actualObject = converted[x] as SomeInterface;
final.push(actualObject);
});
});
return final;
}
whereby state is the original object we wish to convert and mapper is the mapping of the original keys to the desired keys, ex:
const LABEL_TO_KEY: Record<string, string> = {
'First name': 'firstName',
'Last Name': 'lastName',
'Some random number': 'someRandomNumber'
} | {
"domain": "codereview.stackexchange",
"id": 43773,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "json, typescript",
"url": null
} |
json, typescript
I've only really been professionally coding in TS/JS for ~2 years, so I am sure this is not the ideal state. If this were C# (my bread and butter for the past 5 years) then leveraging LINQ would make this be a very straight forward problem. I would love any constructive criticism
playground of my solution
Answer: Disclaimer: I don't know Typescript, so this answer will be written in vanilla JS. However, it should be simple to add types to make it idiomatic TS.
To be honest, I have no idea what the code in let converted = ... is doing. It seems excessively complicated for the simple task of translating all of the keys in an object.
I decided to rewrite your code based on the problem description:
function mapData(state, mapper) {
return state.map((x) =>
Object.fromEntries(
Object.entries(x).map((entry) => {
let [key, value] = entry;
return [mapper[key], value];
})
)
);
}
Playground Link
Since we're transforming each element of the initial array, Array#map is what we should use, not Array#forEach, as it creates a new array by calling a transforming function on every element of the original array.
For the transforming function itself, essentially what we're doing is converting each object into an array of [key, value] entries with Object.enteries, mapping the key to the corresponding key in mapper by returning a [mapper[key], value] pair, and finally converting the array of key-value pairs back to an object with Object.fromEntries. | {
"domain": "codereview.stackexchange",
"id": 43773,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "json, typescript",
"url": null
} |
javascript, jquery, html, event-handling, form
Title: Setting all hidden fields based on id
Question: I am working on a web page where there is a checkbox with a value and a hidden field. I want to ask your opinion on whether this logic is sound.
My logic
The checkbox has a value that matches the id of the hidden field. I have a function that sets all the hidden field values based on whether that checkbox is checked. If it's checked it will set all the hidden values to true if it's not checked it will set all the hidden fields to false.
html
<input type="checkbox" value="1" name="chkProduct">
<input value="true" id="sourceisSelected_1" type="hidden">
JS Script
$("[name='chkProduct']").click(function () {
var section = $(this).attr("value");
if ($(this).is(" :checked")) {
$("[id='sourceisSelected_" + section + "']").val(true);
$("[id='sourceSection_" + section + "']").show();
$("[data-value='" + section + "']").each(function (index, value) {
$(this).attr("disabled", false);
})
}
else {
$("[id='sourceisSelected_" + section + "']").val(false);
$("[id='sourceSection_" + section + "']").hide();
$("[data-value='" + section + "']").each(function (index, value) {
$(this).attr("disabled", true);
})
}
})
Answer:
I want to ask your opinion on whether this logic is sound. | {
"domain": "codereview.stackexchange",
"id": 43774,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, jquery, html, event-handling, form",
"url": null
} |
javascript, jquery, html, event-handling, form
Answer:
I want to ask your opinion on whether this logic is sound.
It is somewhat unclear how the values are used and thus difficult to judge the soundness of the logic. Perhaps in the server-side code there is a need to have a value of false sent for an unchecked checkbox, which is not the default behavior.
One answer to Force a checkbox to always submit, even when unchecked suggests this approach of using a hidden input.
In some of the answers to Tri-state Check box in HTML? there is a suggestion of using the HTML5 Indeterminate state checkboxes though that likely doesn't help with getting the data on the server-side - perhaps it may only be helpful for hierarchical checkboxes, as the MDN documentation explains:
There are not many use cases for this property. The most common is when a checkbox is available that "owns" a number of sub-options (which are also checkboxes). If all of the sub-options are checked, the owning checkbox is also checked, and if they're all unchecked, the owning checkbox is unchecked. If any one or more of the sub-options have a different state than the others, the owning checkbox is in the indeterminate state.
Review
This code, while brief, is somewhat repetitive, which goes against the Don't Repeat Yourself principle. Between the if block and the else block the only differences appear to be true, false and the call to the .hide() or .show() method. This could be simplified by:
storing the value used in the condition as a boolean variable
utilizing that variable in the call to .val(), as well as calling the .toggle() method and passing the negated value of the boolean value instead of the .hide() and .show() methods
removing the call to .each() and just calling the .attr() on the jQuery collection of elements that match the data-value attribute, since that method will "set one or more attributes for every matched element."1 | {
"domain": "codereview.stackexchange",
"id": 43774,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, jquery, html, event-handling, form",
"url": null
} |
javascript, jquery, html, event-handling, form
The code below illustrates such an approach. It also uses the const keyword, which was mentioned in this previous review.
$("[name='chkProduct']").click(function() {
const section = $(this).attr("value");
const checked = $(this).is(" :checked");
$("[id='sourceisSelected_" + section + "']").val(checked);
$("[id='sourceSection_" + section + "']").toggle(checked);
$("[data-value='" + section + "']").attr("disabled", !checked);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js" /></script>
<input type="checkbox" value="1" name="chkProduct" />
<input value="true" id="sourceisSelected_1" type="hidden">
<select data-value="1" disabled>
<option>Ferrari</option>
<option>Porche</option>
</select>
<div>
<input type="radio" data-value="1" disabled id="radio_1" name="prod1radio"><label for="radio_1">Radio 1</label>
</div>
<div>
<input type="radio" data-value="1" disabled id="radio_2" name="prod1radio"><label for="radio_2">Radio 2</label>
</div>
<div style="display: none" id="sourceSection_1"><img src="https://www.gravatar.com/avatar/02ab07612ab1bf8e8e49c909d21f9de0?s=64&d=identicon&r=PG" /></div> | {
"domain": "codereview.stackexchange",
"id": 43774,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, jquery, html, event-handling, form",
"url": null
} |
python, numpy, matplotlib
Title: Plotting determinant probabilities
Question: This is a fun exercise that tries to answer the following question: if the elements from a square matrix are randomly chosen from 0 to 9, is it more like that the determinant would be even or odd?
I'm pretty sure there are different ways of optimizing this piece of code.
The first one that comes to my mind is to use only generators (maybe?) and not use the for loop to fill values.
import itertools
import math
import matplotlib.pyplot as plt
import numpy as np
n = 4
lst = list(itertools.product([0, 1], repeat=n))
algo = list(itertools.product(lst, repeat=n))
determinants = np.abs(np.linalg.det(algo))
determinants = np.where(determinants % 2 == 0, 0, 1)
square = math.ceil((math.sqrt(len(determinants)))) ** 2
# fill with generic value if not a perfect square
for num in range(square - len(determinants)):
determinants = np.append(determinants, -1)
matrix = np.reshape(determinants, (int(math.sqrt(square)), int(math.sqrt(square))))
fig, ax = plt.subplots() # or
ax.imshow(matrix, cmap="Greens")
plt.show()
All suggestions are welcome :D
Answer: The n you care about isn't really 4, it's 4**2 = 16.
Don't use lists, itertools or for loops in a Numpy context.
Don't use np.where in this case; you can replace that entire operation with % 2 alone.
Don't use math.* methods when there are Numpy equivalents.
Don't concatenate-append. Instead, just use slices on a pre-allocated array.
When you reshape to your matrix, leave one of the dimensions implied as -1.
Suggested
The fill step could look like
side = round(np.ceil(np.sqrt(len(determinants))))
filled = np.empty(side**2)
filled[:len(determinants)] = determinants
filled[len(determinants):] = -1
but your operation will always be a perfect square, so just delete that, leaving this code which is equivalent to your original:
import matplotlib.pyplot as plt
import numpy as np
n = 16 | {
"domain": "codereview.stackexchange",
"id": 43775,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, numpy, matplotlib",
"url": null
} |
python, numpy, matplotlib
n = 16
lst = np.arange(2**n)
as_bytes = np.stack(
(np.right_shift(lst, n//2), lst),
axis=-1,
).astype(np.uint8)
algo = np.unpackbits(
as_bytes, axis=1,
).reshape((-1, 4, n//4))
determinants = np.abs(np.linalg.det(algo)) % 2
side = round(np.ceil(np.sqrt(len(determinants))))
matrix = determinants.reshape((side, -1))
fig, ax = plt.subplots()
ax.imshow(matrix, cmap="Greens")
plt.show()
Output | {
"domain": "codereview.stackexchange",
"id": 43775,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, numpy, matplotlib",
"url": null
} |
rust
Title: Zero the excess digits of an array
Question: I wrote some code that set the last few elements of an array to zero. I call these last elements the "excess":
const MAX_DIGITS: usize = 20;
pub fn zero_excess_digits(digits: &mut [u8; MAX_DIGITS], n_digits: usize) {
for i in n_digits..MAX_DIGITS {
digits[i] = 0;
}
}
However, Clippy considers this a needless_range_loop and suggests I write the code like this:
const MAX_DIGITS: usize = 20;
pub fn zero_excess_digits_iter_for(digits: &mut [u8; MAX_DIGITS], n_digits: usize) {
for d in digits.iter_mut().take(MAX_DIGITS).skip(n_digits) {
*d = 0;
}
}
Usually when I've used Clippy, it's given me solid advice. But in this case, I just don't see it. I've tried both versions in Godbolt/Compiler Explorer: https://godbolt.org/z/7G8McseKs
it optimizes my original version to a call to memset (12 lines of asm);
for the .iter_mut() version, it generates code for the loop (30 lines of asm! Unacceptable!)
I tried using a .for_each() instead of for ... and it went down to 24 lines of asm.
Is there some deep insight from Clippy that I'm missing? Is there a more idiomatic way of writing this "zero the excess" code?
Answer: There's a simpler and more idiomatic solution:
digits[n_digits..].fill(0);
You could also do:
for d in &mut digits [n_digits..MAX_DIGITS] {
*d = 0;
}
However, these work slightly differently then your original. If n_digits is > MAX_DIGITS, the slice versions will panic on the slice. But your original version will do nothing, because the range is considered empty. | {
"domain": "codereview.stackexchange",
"id": 43776,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "rust",
"url": null
} |
python, python-3.x, hash-map
Title: Implementation of building nested dictionary from list
Question: I have a value test-1 and a list of keys as below:
[
["initial", "short_title"],
["later", "datasets", "item_okmiwt"],
["general_title"]
]
I wanted the resulting dictionary like this:
{'initial': {'short_title': 'test-1'}, 'later': {'datasets': {'item_okmiwt': 'test-1'}}, 'general_title': 'test-1'}
I have written the following code for implementing the above result:
def set_copy_to_attr(value, copy_to_attr):
"""Method to copy value to copy_to config."""
def build_nested_dict(element, result={}):
if len(element) == 1:
result[element[-1]] = pid_value
return result
else:
for el in element:
result[el] = {}
element.remove(el)
build_nested_dict(element, result[el])
for _element in copy_to_attr:
_dict = build_nested_dict(_element)
if _dict:
return _dict
I am getting the desired result, Is this approach can be optimized more?
Answer: Broadly: this kind of dictionary soup is a problem, and is often evidence of inadequate domain modelling and deserialisation. But you haven't shown enough of your actual application to say more.
Two things will slow you down: mutating element via .remove(), and recursing. Python is bad at recursing, and for input of sufficient depth this will easily blow the stack.
Add PEP484 type hints - even though, since this is dictionary soup, typing is made more difficult.
Rather than _dict (making it look like a private), typically to avoid Python keywords, the underscore is a suffix i.e. dict_.
Suggested
from pprint import pprint
from typing import Any, Iterable
def set_copy_to_attr(
value: Any,
copy_to_attr: Iterable[Iterable[Any]],
) -> dict:
dict_ = {}
for *values, leaf in copy_to_attr:
nested = dict_
for v in values:
nested[v] = nested = {}
nested[leaf] = value
return dict_ | {
"domain": "codereview.stackexchange",
"id": 43777,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, hash-map",
"url": null
} |
python, python-3.x, hash-map
return dict_
def test() -> None:
copy_to_attr = [
["initial", "short_title"],
["later", "datasets", "item_okmiwt"],
["general_title"]
]
copied = set_copy_to_attr('test-1', copy_to_attr)
pprint(copied)
if __name__ == '__main__':
test()
Output
{'general_title': 'test-1',
'initial': {'short_title': 'test-1'},
'later': {'datasets': {'item_okmiwt': 'test-1'}}} | {
"domain": "codereview.stackexchange",
"id": 43777,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, hash-map",
"url": null
} |
performance, programming-challenge, primes, rust
Title: Project Euler #51: "Prime digit replacements" in Rust
Question: Problem: https://projecteuler.net/problem=51
"Find the smallest prime which, by replacing part of the number (not necessarily adjacent digits) with the same digit, is part of an eight prime value family."
repository: https://github.com/steven-omaha/euler51
dependencies: num
This code is my attempt at solving Project Euler challenge #51. This code takes ~ 1000 ms to run on my PC.
Comments from me:
primes.rs is intentionally generic, as most a good amount of Project Euler challenges involve prime numbers. This is normally a separate package.
combination.rs produces Vec<bool> elements, like [1, 0, 0, 1, 1]. These vectors are used in main.rs to identify the positions where a digit should be replaced.
Main concerns for review:
Single-thread performance. I am aware of multithreading, but I'm not interested in that in the scope of this review. Am I giving away performance improvements somewhere?
code cleanliness
any code smells
Things that I'm aware are suboptimal:
apply_transformation does too much and would better be two functions (see comments there). I was thinking on how to transfer the data between the (hypothetical) two different functions. I tried that by collecting to a Vec, but that had some performance penalty. I think the best would be to implement Map, but I have never done that.
I have a feeling that transforming an int to an array of digits via char is suboptimal, but I have not measured that.
main.rs:
mod combination;
mod primes;
use combination::PositionCombinations;
use primes::Primes;
type Int = u64;
// EXAMPLE 1
// const MIN_VALUE: Int = 10;
// const MAX_VALUE: Int = 99;
// const LENGTH: usize = 2;
// const MIN_LENGTH: usize = 1;
// EXAMPLE 2
// const MIN_VALUE: Int = 10_000;
// const MAX_VALUE: Int = 99_999;
// const LENGTH: usize = 5;
// const MIN_LENGTH: usize = 2; | {
"domain": "codereview.stackexchange",
"id": 43778,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, programming-challenge, primes, rust",
"url": null
} |
performance, programming-challenge, primes, rust
// FINAL
const MIN_VALUE: Int = 100_000;
const MAX_VALUE: Int = 999_999;
const LENGTH: usize = 6;
const MIN_LENGTH: usize = 2;
const MAX_LENGTH: usize = LENGTH - 1;
const DIGITS: [u8; 10] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
fn main() {
let all_primes = Primes::get_between(MIN_VALUE, MAX_VALUE);
let mut best_of_all_combinations = vec![];
for pattern in PositionCombinations::new(MIN_LENGTH, MAX_LENGTH, LENGTH) {
let mut best_this_combination = vec![];
let mut primes_to_check = all_primes.clone();
while let Some(first) = primes_to_check.pop() {
let mut primes_matching_pattern = vec![];
let digits = first.to_digits();
for digit in DIGITS {
let could_be_prime = apply_transformation(&digits, digit, &pattern);
if primes_to_check.contains(&could_be_prime) || could_be_prime == first {
primes_matching_pattern.push(could_be_prime);
}
}
if primes_matching_pattern.len() > 2 {
best_this_combination.push(primes_matching_pattern);
}
}
if !best_this_combination.is_empty() {
best_of_all_combinations.push(get_longest(best_this_combination));
}
}
println!("{:#?}", get_longest(best_of_all_combinations));
}
fn apply_transformation(prime_as_digits: &[u8], new_digit: u8, pattern: &[bool]) -> Int {
debug_assert_eq!(prime_as_digits.len(), pattern.len());
let mut multiplier = 1;
let result = prime_as_digits
// apply the pattern to prime_as_digits
.iter()
.zip(pattern)
.map(|(old_digit, replace)| if *replace { new_digit } else { *old_digit })
.map(Int::from)
// calculate Int
.rev()
.reduce(|accum, item| {
multiplier *= 10;
accum + multiplier * item
})
.unwrap();
debug_assert_eq!(multiplier, 100_000);
result
} | {
"domain": "codereview.stackexchange",
"id": 43778,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, programming-challenge, primes, rust",
"url": null
} |
performance, programming-challenge, primes, rust
fn get_longest(mut vec: Vec<Vec<Int>>) -> Vec<Int> {
assert!(
!vec.is_empty(),
"cannot get the longest element of an empty vector"
);
vec.sort_by_key(Vec::len);
let length = vec.last().unwrap().len();
vec.into_iter().find(|v| v.len() == length).unwrap()
}
trait ToDigits {
fn to_digits(&self) -> Vec<u8>;
}
impl ToDigits for Int {
fn to_digits(&self) -> Vec<u8> {
self.to_string()
.chars()
.map(|x| x.to_digit(10).unwrap() as u8)
.collect()
}
}
#[cfg(test)]
mod test {
use crate::{apply_transformation, ToDigits};
#[test]
fn test_num_to_digits() {
let num = 83371;
assert_eq!(num.to_digits(), vec![8, 3, 3, 7, 1]);
}
#[test]
fn test_apply_transformation() {
let prime_as_digits = [5, 7, 3, 8, 2, 1];
let new_digit = 0;
let pattern = [false, true, true, true, false, false];
assert_eq!(
apply_transformation(&prime_as_digits, new_digit, &pattern),
500_021
);
}
}
combination.rs:
pub struct PositionCombinations {
min_length: usize,
max_length: usize,
state: Vec<bool>,
finished: bool,
}
impl Iterator for PositionCombinations {
type Item = Vec<bool>;
fn next(&mut self) -> Option<Self::Item> {
loop {
let result = self.state.clone();
self.increment();
if self.finished {
return None;
}
if (self.min_length..=self.max_length).contains(&result.iter().filter(|x| **x).count())
{
return Some(result);
}
}
}
}
impl PositionCombinations {
pub fn new(min_length: usize, max_length: usize, length: usize) -> Self {
let state = vec![false; length];
let finished = false;
Self {
min_length,
max_length,
state,
finished,
}
} | {
"domain": "codereview.stackexchange",
"id": 43778,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, programming-challenge, primes, rust",
"url": null
} |
performance, programming-challenge, primes, rust
fn increment(&mut self) {
let mut overflow = self.state[0];
self.state[0] ^= true;
for position in self.state[1..].iter_mut() {
let new_overflow = *position & overflow;
*position ^= overflow;
overflow = new_overflow;
}
if overflow {
self.finished = true;
}
}
}
pub trait ToString {
fn to_string(&self) -> String;
}
impl ToString for Vec<bool> {
fn to_string(&self) -> String {
self.iter().map(|b| if *b { 'x' } else { '.' }).collect()
}
}
#[cfg(test)]
mod test {
use crate::combination::PositionCombinations;
use std::collections::HashSet;
#[test]
fn test_combination_2_3_4() {
let combinator = PositionCombinations::new(2, 3, 4);
let result: Vec<_> = combinator.into_iter().collect();
let mut number_solutions = result.len();
let mut solution = HashSet::new();
solution.insert(vec![false, false, true, true]);
solution.insert(vec![false, true, false, true]);
solution.insert(vec![false, true, true, false]);
solution.insert(vec![false, true, true, true]);
solution.insert(vec![true, true, false, false]);
solution.insert(vec![true, false, true, false]);
solution.insert(vec![true, false, false, true]);
solution.insert(vec![true, false, true, true]);
solution.insert(vec![true, true, false, true]);
solution.insert(vec![true, true, true, false]);
for item in solution {
assert!(result.contains(&item));
number_solutions -= 1;
}
assert_eq!(number_solutions, 0);
} | {
"domain": "codereview.stackexchange",
"id": 43778,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, programming-challenge, primes, rust",
"url": null
} |
performance, programming-challenge, primes, rust
#[test]
fn test_combination_2_2_3() {
let combinator = PositionCombinations::new(2, 2, 3);
let result: Vec<_> = combinator.into_iter().collect();
let mut number_solutions = result.len();
let mut solution = HashSet::new();
solution.insert(vec![false, true, true]);
solution.insert(vec![true, false, true]);
solution.insert(vec![true, true, false]);
for item in solution {
assert!(result.contains(&item));
number_solutions -= 1;
}
assert_eq!(number_solutions, 0);
}
}
primes.rs
extern crate num;
use num::FromPrimitive;
use num::Num;
use num::ToPrimitive;
use std::collections::HashSet;
use std::hash::Hash;
#[derive(Clone)]
pub struct Primes<T> {
vector: Vec<T>,
set: HashSet<T>,
}
impl<T> Primes<T>
where
T: Num + ToPrimitive + FromPrimitive + Hash + Eq + PartialEq + Copy,
{
pub fn get_between(min_value: T, max_value: T) -> Self {
let max_value = max_value.to_usize().unwrap();
let min_value = min_value.to_usize().unwrap();
assert!(min_value > 1);
assert!(max_value > min_value);
Self::from_array(
&Self::get_prime_numbers_array(min_value, max_value),
min_value,
max_value,
)
}
fn from_array(array: &[bool], min_value: usize, max_value: usize) -> Self {
let mut vector = Vec::new();
let mut set = HashSet::new();
for number in min_value..max_value {
if array[(number - min_value) as usize] {
let prime = FromPrimitive::from_usize(number).unwrap();
vector.push(prime);
set.insert(prime);
}
}
vector.reverse(); // so that self.pop removes the smallest prime
Primes { vector, set }
} | {
"domain": "codereview.stackexchange",
"id": 43778,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, programming-challenge, primes, rust",
"url": null
} |
performance, programming-challenge, primes, rust
fn get_prime_numbers_array(min_value: usize, max_value: usize) -> Vec<bool> {
// Sieve of Eratosthenes
let length = max_value - min_value;
let mut result = vec![true; length];
for number_to_check in 2..(max_value / 2) {
let mut last_number = number_to_check;
loop {
let current_number = last_number + number_to_check;
if current_number < min_value {
last_number = current_number;
continue;
}
if current_number >= max_value {
break;
}
result[current_number - min_value] = false;
last_number = current_number;
}
}
result
}
pub fn pop(&mut self) -> Option<T> {
let result = self.vector.pop();
if let Some(value) = result {
self.set.remove(&value);
}
result
}
pub fn contains(&self, val: &T) -> bool {
self.set.contains(val)
}
}
#[cfg(test)]
mod test {
use crate::primes::Primes;
#[test]
fn test_example_prime() {
let primes = Primes::get_between(2, 99_999);
assert!(primes.set.contains(&56003));
assert!(primes.set.contains(&56993));
assert!(!primes.set.contains(&56002));
}
#[test]
fn test_pop() {
let mut primes = Primes::get_between(10, 20);
assert!(primes.contains(&11));
primes.pop();
assert!(!primes.contains(&11));
}
}
Thank you for your time!
Answer: Using the comments and the other answer, I have attempted to rework this code myself. | {
"domain": "codereview.stackexchange",
"id": 43778,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, programming-challenge, primes, rust",
"url": null
} |
performance, programming-challenge, primes, rust
Answer: Using the comments and the other answer, I have attempted to rework this code myself.
Runtime is down from 1000 ms to 100 ms.
My implementation of the sieve of Eratosthenes was indeed weird and needlessly complicated, although correct. I have rewritten that and thrown some optimizations on it (benchmarked, of course).
apply_transformation was a bad name that I should have replaced before asking for a review. It is now called replace_digits_with_new_digit_according_to_pattern
I had best_this_combination and bets_of_all_combinations where I held the longest prime family fulfilling the conditions that I have found so far, instead of just checking whether I found the family of the correct size and exiting the program.
My old variant of ToDigits was indeed suboptimal performance-wise (Int to String to char to u8). It now converts the number directly to Vec<u8> using some basic multiplication and subtraction.
I had the correct idea that I do not need to check numbers again that I had already checked, but I did it in an inefficient manner. I cloned the original all_primes struct for every outer iteration, and popped one prime out of it for every inner iteration. The comments were helpful insofar that I realized I can have a case string to check if I had checked that combination of digits before. (get_case_string).
Furthermore, I found that I could get out of the inner loop earlier when there are not enough digits left so that I can find a family of the required size. (enough_digits_left)
The case strings and processed cases are written to a pre-allocated buffer, which prevents a lot of allocations and drops in the main loop.
This is how the code looks like now.
Repository is updated. https://github.com/steven-omaha/euler51
main.rs
mod combination;
mod primes;
use std::{collections::HashSet, process::exit};
use combination::PositionCombinations;
use primes::Primes;
type Int = u64; | {
"domain": "codereview.stackexchange",
"id": 43778,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, programming-challenge, primes, rust",
"url": null
} |
performance, programming-challenge, primes, rust
use combination::PositionCombinations;
use primes::Primes;
type Int = u64;
// EXAMPLE 1
// const SEARCH_MIN: Int = 10;
// const SEARCH_MAX: Int = 99;
// const AMOUNT_OF_DIGITS_IN_NUMBER: usize = 2;
// const MIN_PATTERN_LENGTH: usize = 1;
// const FAMILY_SIZE: usize = 6;
// EXAMPLE 2
// const SEARCH_MIN: Int = 10_000;
// const SEARCH_MAX: Int = 99_999;
// const AMOUNT_OF_DIGITS_IN_NUMBER: usize = 5;
// const MIN_PATTERN_LENGTH: usize = 1;
// const FAMILY_SIZE: usize = 7;
// FINAL
const SEARCH_MIN: Int = 100_000;
const SEARCH_MAX: Int = 999_999;
const AMOUNT_OF_DIGITS_IN_NUMBER: usize = 6;
const MIN_PATTERN_LENGTH: usize = 2;
const FAMILY_SIZE: usize = 8;
const MAX_PATTERN_LENGTH: usize = AMOUNT_OF_DIGITS_IN_NUMBER - 1;
const NUMBER_OF_DIGITS: usize = 10;
const DIGITS: [u8; NUMBER_OF_DIGITS] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
fn main() {
let all_primes = Primes::get_between(SEARCH_MIN, SEARCH_MAX);
let mut processed_cases = HashSet::with_capacity(SEARCH_MIN as usize);
let mut primes_matching_pattern = Vec::with_capacity(FAMILY_SIZE);
let mut case_buf = String::with_capacity(AMOUNT_OF_DIGITS_IN_NUMBER);
for pattern in PositionCombinations::new(
MIN_PATTERN_LENGTH,
MAX_PATTERN_LENGTH,
AMOUNT_OF_DIGITS_IN_NUMBER,
) {
for prime in &all_primes.vector {
primes_matching_pattern.clear();
let digits = prime.to_digits();
get_case_string(&digits, &pattern, &mut case_buf);
if processed_cases.contains(&case_buf) {
continue;
} else {
processed_cases.insert(case_buf.clone());
} | {
"domain": "codereview.stackexchange",
"id": 43778,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, programming-challenge, primes, rust",
"url": null
} |
performance, programming-challenge, primes, rust
for (i, digit) in DIGITS.iter().enumerate() {
if !enough_digits_left(i, primes_matching_pattern.len()) {
break;
}
let could_be_prime =
replace_digits_with_new_digit_according_to_pattern(&digits, *digit, &pattern);
if all_primes.contains(&could_be_prime) {
primes_matching_pattern.push(could_be_prime);
}
}
if primes_matching_pattern.len() == FAMILY_SIZE {
println!("{primes_matching_pattern:#?}");
exit(0);
}
}
}
}
fn enough_digits_left(i: usize, primes_len: usize) -> bool {
// are there enough digits left in the loop to achieve the required FAMILY_SIZE?
i - primes_len + FAMILY_SIZE <= NUMBER_OF_DIGITS
}
fn get_case_string(digits: &[u8], pattern: &[bool], buf: &mut String) {
buf.clear();
digits
.iter()
.zip(pattern)
.map(|(d, b)| if *b { '*' } else { *d as char })
.for_each(|c| buf.push(c));
}
fn replace_digits_with_new_digit_according_to_pattern(
prime_as_digits: &[u8],
new_digit: u8,
pattern: &[bool],
) -> Int {
debug_assert_eq!(prime_as_digits.len(), pattern.len());
let mut multiplier = 1;
let result = prime_as_digits
// apply the pattern to prime_as_digits
.iter()
.zip(pattern)
.map(|(old_digit, replace)| if *replace { new_digit } else { *old_digit })
.map(|d| d as Int)
// calculate Int
.rev()
.reduce(|accum, item| {
multiplier *= 10;
accum + multiplier * item
})
.unwrap();
debug_assert_eq!(multiplier, 100_000);
result
}
trait ToDigits {
fn to_digits(&self) -> Vec<u8>;
} | {
"domain": "codereview.stackexchange",
"id": 43778,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, programming-challenge, primes, rust",
"url": null
} |
performance, programming-challenge, primes, rust
trait ToDigits {
fn to_digits(&self) -> Vec<u8>;
}
impl ToDigits for Int {
fn to_digits(&self) -> Vec<u8> {
let oom = get_order_of_magnitude(*self);
let length = oom as usize;
let mut var = *self;
let mut result = vec![0; length];
result.iter_mut().enumerate().for_each(|(i, d)| {
let power = 10_u64.pow(oom - i as u32 - 1);
let digit = var / power;
var -= digit * power;
*d = digit as u8;
});
debug_assert_eq!(var, 0);
result
}
}
fn get_order_of_magnitude(x: Int) -> u32 {
let mut tmp = 1;
let mut oom = 1;
while tmp - 1 < x {
oom += 1;
tmp *= 10;
}
oom - 1
}
#[cfg(test)]
mod test {
use crate::{
get_order_of_magnitude, replace_digits_with_new_digit_according_to_pattern, ToDigits,
};
#[test]
fn test_num_to_digits() {
let num = 83371;
assert_eq!(num.to_digits(), vec![8, 3, 3, 7, 1]);
}
#[test]
fn test_apply_transformation() {
let prime_as_digits = [5, 7, 3, 8, 2, 1];
let new_digit = 0;
let pattern = [false, true, true, true, false, false];
assert_eq!(
replace_digits_with_new_digit_according_to_pattern(
&prime_as_digits,
new_digit,
&pattern
),
500_021
);
}
#[test]
fn test_to_digits() {
let num = 37871_u64;
assert_eq!(vec![3, 7, 8, 7, 1], num.to_digits());
}
#[test]
fn test_oom() {
assert_eq!(get_order_of_magnitude(3), 1);
assert_eq!(get_order_of_magnitude(9), 1);
assert_eq!(get_order_of_magnitude(10), 2);
assert_eq!(get_order_of_magnitude(32), 2);
assert_eq!(get_order_of_magnitude(10_000), 5);
assert_eq!(get_order_of_magnitude(10_001), 5);
assert_eq!(get_order_of_magnitude(37_871), 5);
}
} | {
"domain": "codereview.stackexchange",
"id": 43778,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, programming-challenge, primes, rust",
"url": null
} |
performance, programming-challenge, primes, rust
combination.rs
pub struct PositionCombinations {
min_length: usize,
max_length: usize,
state: Vec<bool>,
finished: bool,
}
impl Iterator for PositionCombinations {
type Item = Vec<bool>;
fn next(&mut self) -> Option<Self::Item> {
loop {
let result = self.state.clone();
self.increment();
if self.finished {
return None;
}
if (self.min_length..=self.max_length).contains(&result.iter().filter(|x| **x).count())
{
return Some(result);
}
}
}
}
impl PositionCombinations {
pub fn new(min_length: usize, max_length: usize, length: usize) -> Self {
let state = vec![false; length];
let finished = false;
Self {
min_length,
max_length,
state,
finished,
}
}
fn increment(&mut self) {
let mut overflow = self.state[0];
self.state[0] ^= true;
for position in self.state[1..].iter_mut() {
let new_overflow = *position & overflow;
*position ^= overflow;
overflow = new_overflow;
}
if overflow {
self.finished = true;
}
}
}
pub trait ToString {
fn to_string(&self) -> String;
}
impl ToString for Vec<bool> {
fn to_string(&self) -> String {
self.iter().map(|b| if *b { 'x' } else { '.' }).collect()
}
}
#[cfg(test)]
mod test {
use crate::combination::PositionCombinations;
use std::collections::HashSet; | {
"domain": "codereview.stackexchange",
"id": 43778,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, programming-challenge, primes, rust",
"url": null
} |
performance, programming-challenge, primes, rust
#[test]
fn test_combination_2_3_4() {
let combinator = PositionCombinations::new(2, 3, 4);
let result: Vec<_> = combinator.into_iter().collect();
let mut number_solutions = result.len();
let mut solution = HashSet::new();
solution.insert(vec![false, false, true, true]);
solution.insert(vec![false, true, false, true]);
solution.insert(vec![false, true, true, false]);
solution.insert(vec![false, true, true, true]);
solution.insert(vec![true, true, false, false]);
solution.insert(vec![true, false, true, false]);
solution.insert(vec![true, false, false, true]);
solution.insert(vec![true, false, true, true]);
solution.insert(vec![true, true, false, true]);
solution.insert(vec![true, true, true, false]);
for item in solution {
assert!(result.contains(&item));
number_solutions -= 1;
}
assert_eq!(number_solutions, 0);
}
#[test]
fn test_combination_2_2_3() {
let combinator = PositionCombinations::new(2, 2, 3);
let result: Vec<_> = combinator.into_iter().collect();
let mut number_solutions = result.len();
let mut solution = HashSet::new();
solution.insert(vec![false, true, true]);
solution.insert(vec![true, false, true]);
solution.insert(vec![true, true, false]);
for item in solution {
assert!(result.contains(&item));
number_solutions -= 1;
}
assert_eq!(number_solutions, 0);
}
}
primes.rs
extern crate num;
use std::collections::HashSet;
use std::fmt::Display;
use std::hash::Hash;
use num::FromPrimitive;
use num::Num;
use num::ToPrimitive;
#[derive(Clone)]
pub struct Primes<T> {
pub vector: Vec<T>,
set: HashSet<T>,
} | {
"domain": "codereview.stackexchange",
"id": 43778,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, programming-challenge, primes, rust",
"url": null
} |
performance, programming-challenge, primes, rust
#[derive(Clone)]
pub struct Primes<T> {
pub vector: Vec<T>,
set: HashSet<T>,
}
impl<T> Primes<T>
where
T: Num + ToPrimitive + FromPrimitive + Hash + Eq + PartialEq + Copy + Display,
{
pub fn get_between(min_value: T, max_value: T) -> Self {
let max_value = max_value.to_usize().unwrap();
let min_value = min_value.to_usize().unwrap();
assert!(min_value > 1);
assert!(max_value > min_value);
Self::from_array(
&Self::get_prime_numbers_array(min_value, max_value),
min_value,
max_value,
)
}
fn from_array(array: &[bool], min_value: usize, max_value: usize) -> Self {
let number_of_primes = array.iter().filter(|b| **b).count();
let mut vector = Vec::with_capacity(number_of_primes);
let mut set = HashSet::with_capacity(number_of_primes);
for number in min_value..max_value {
let idx = number - min_value;
// SAFETY: see considerations in get_prime_numbers_array
if unsafe { *array.get_unchecked(idx) } {
let prime = FromPrimitive::from_usize(number).unwrap();
vector.push(prime);
set.insert(prime);
}
}
debug_assert_eq!(number_of_primes, vector.len());
Primes { vector, set }
}
fn get_prime_numbers_array(min_value: usize, max_value: usize) -> Vec<bool> {
// Sieve of Eratosthenes
let length = max_value - min_value;
let mut result = vec![true; length];
let upper_limit = Self::calc_upper_limit(max_value);
for i in 2..upper_limit {
let skip = Self::find_number_to_skip_until_min_value(min_value, i); | {
"domain": "codereview.stackexchange",
"id": 43778,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, programming-challenge, primes, rust",
"url": null
} |
performance, programming-challenge, primes, rust
for multiple in (i * i..max_value).step_by(i).skip(skip) {
let idx = multiple - min_value;
// SAFETY: `multiple` will always be between min_value and max_value
// (which define the length of the array), therfore idx is always smaller than the
// length of result, therefore this access is always in bounds.
// This is slightly faster than the bounds-checked write.
unsafe { *result.get_unchecked_mut(idx) = false };
}
}
result
}
fn calc_upper_limit(max_value: usize) -> usize {
f64::sqrt(max_value as f64).ceil() as usize
}
fn find_number_to_skip_until_min_value(min_value: usize, i: usize) -> usize {
((min_value.saturating_sub(i * i)) as f64 / i as f64).ceil() as usize
}
pub fn contains(&self, val: &T) -> bool {
self.set.contains(val)
}
}
#[cfg(test)]
mod test {
use super::Primes;
#[test]
fn test_example_prime() {
let primes = Primes::get_between(2, 99_999);
assert!(primes.set.contains(&56003));
assert!(primes.set.contains(&56993));
assert!(!primes.set.contains(&56002));
}
} | {
"domain": "codereview.stackexchange",
"id": 43778,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, programming-challenge, primes, rust",
"url": null
} |
c++, performance, beginner, palindrome, c++20
Title: Find long palindrome multiplications in modern C++
Question: I'm a former C# programmer, updating my rusty C++98 (perhaps I should try Rust instead) to modern C++20. My main goal is to get used to C++ standard library types and algorithms.
I chose to solve a palindrome quiz, finding the largest palindrome when multiplying two N-digit numbers. Basically it's a harder version of this puzzle.
Solving this task was no problem for N <=4, but I needed to tweak performance to run in acceptable time for 5 <= N <= 7. For that I needed to
start at the upper limit to find large numbers quickly and count backwards
quit the innermost loop early (break;)
update the lower limit (lower_bound)
With this performance improvement, I can no longer imagine how to use a C++ algorithm instead of the plain for-loops.
Request A: can you help me use a C++ algorithm instead of the innermost "plain old" for-loops?
There's something else: when I implemented the mathematical approach for the palindrome check (is_palindrome_math()) I first had a bug. With that bug, execution time was ~120 ms only. After fixing the bug (uncomment the line which says bugfix), it takes ~1200 ms (factor 10).
Request B: can you help me apply the bugfix without getting a 10x performance loss?
Request C: just a code review ;-) I used east const, just to see how that feels. Please don't argue for west const. I know the discussion.
I'm using Visual Studio 2022, C++20. Do yourself a favor and run it in Release Build without attaching a debugger for higher N.
#include <algorithm> // std::sort()
#include <cassert> // assert()
#include <chrono> // time measurements
#include <iostream> // std::cout
#include <string> // std::to_string()
#include <vector> // std::vector<T>
#include <tuple> // std::tuple<T>
#include <ranges> // std::ranges::views
#include <map> // std::map<T> | {
"domain": "codereview.stackexchange",
"id": 43779,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, beginner, palindrome, c++20",
"url": null
} |
c++, performance, beginner, palindrome, c++20
/**
* \brief Checks for palindromes using string and reverse string.
* \param n Number to check being palindrome.
* \return True if the number is a palindrome.
*/
inline bool is_palindrome_str(unsigned long long n)
{
auto const num = std::to_string(n);
auto backward(num);
std::ranges::reverse(backward);
return num == backward;
}
/**
* \brief Checks for palindromes using a string and a forward and reverse iterator.
* \param n Number to check being palindrome.
* \return True if the number is a palindrome.
*/
inline bool is_palindrome_iterator(unsigned long long n)
{
auto const num = std::to_string(n);
auto left = num.begin();
auto right = num.rbegin();
while (std::distance(left, right.base() - 1) > 0)
{
if (*left != *right) return false;
++left;
++right;
}
return true;
}
/**
* \brief Checks for palindromes using a string and accessing individual characters.
* \param n Number to check being palindrome.
* \return True if the number is a palindrome.
*/
inline bool is_palindrome_char(unsigned long long n)
{
auto const num = std::to_string(n);
auto const size = num.size();
for (auto i = 0ULL; i < size / 2; i++)
{
if (num[i] != num[size - i - 1]) return false;
}
return true;
}
/**
* \brief Checks for palindromes using a string and std::all_of for individual characters.
* \param n Number to check being palindrome.
* \return True if the number is a palindrome.
*/
inline bool is_palindrome_allof(unsigned long long n)
{
auto const num = std::to_string(n);
auto const size = num.size();
auto const indexes = std::ranges::views::iota(0ULL, num.size() / 2);
return std::all_of(indexes.begin(), indexes.end(),
[&num, &size](auto index) { return num[index] == num[size - 1 - index]; }
);
} | {
"domain": "codereview.stackexchange",
"id": 43779,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, beginner, palindrome, c++20",
"url": null
} |
c++, performance, beginner, palindrome, c++20
/**
* \brief Checks for palindromes using math.
* \param n Number to check being palindrome.
* \return True if the number is a palindrome.
*/
inline bool is_palindrome_math(unsigned long long n)
{
// Bugfix:
//if (n % 10 == 0) return false;
auto m = 0ULL;
while (n > m)
{
auto const last_digit = n % 10;
n /= 10;
if (n == m) return true; // exit for odd number of digits
m *= 10;
m += last_digit;
if (n == m) return true; // exit for even number of digits
}
return false;
}
/**
* \brief Calculates the start number and end number of the decade with the number of digits given.
* \param digits Number of digits
* \return Start and end value, e.g. 1000 and 9999 for the 4 digits decade
*/
std::tuple<unsigned int, unsigned int> get_decade_range(unsigned int const digits)
{
unsigned int begin = 1;
for (unsigned int i = 1; i < digits; i++) begin *= 10;
unsigned int end = begin * 10 - 1;
return std::make_tuple(begin, end);
}
/**
* \brief Stopwatch for measuring wall clock time of a method.
* Starts measuring when created, stops measuring when it goes out of scope.
*/
class Timer
{
private:
std::chrono::time_point<std::chrono::steady_clock> const startTime = std::chrono::steady_clock::now();
public:
~Timer()
{
auto const endTime = std::chrono::steady_clock::now();
std::cout << "Calculation took " << std::chrono::duration_cast<std::chrono::milliseconds>(endTime - startTime).count() << " ms." << std::endl;
}
};
int main()
{
// Some poor man's unit tests
assert(is_palindrome_char(9234567654329));
assert(is_palindrome_str(9234567654329));
assert(is_palindrome_iterator(9234567654329));
assert(is_palindrome_allof(9234567654329));
assert(is_palindrome_math(9234567654329)); | {
"domain": "codereview.stackexchange",
"id": 43779,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, beginner, palindrome, c++20",
"url": null
} |
c++, performance, beginner, palindrome, c++20
// Different approaches for performance comparison
std::map<std::string, bool (*)(unsigned long long)> palindrome_functions;
palindrome_functions.emplace("math", is_palindrome_math);
palindrome_functions.emplace("char", is_palindrome_char);
palindrome_functions.emplace("str", is_palindrome_str);
palindrome_functions.emplace("iterator", is_palindrome_iterator);
palindrome_functions.emplace("allof", is_palindrome_allof);
auto [begin, end] = get_decade_range(7); // Note to self: this is C++17 structured binding == Python tuple unpacking
std::cout << "Looking for palindromes from " << begin << " to " << end << "\n";
for (auto const& is_palindrome_f : palindrome_functions) // Note to self: we call this a range-based for-loop
{
std::cout << "\nRunning algorithm " << is_palindrome_f.first << "\n";
const Timer _performance;
unsigned long long lower_bound = begin;
std::vector<std::tuple<unsigned long long, unsigned long long, unsigned long long>> palindromes;
// Question: can I use an algorithm here?
for (unsigned long long factor1 = end; factor1 >= lower_bound; factor1--)
{
// Question: or here?
for (unsigned long long factor2 = factor1; factor2 >= lower_bound; factor2--)
{
auto const product = factor1 * factor2;
if (is_palindrome_f.second(product))
{
lower_bound = std::max(factor2, lower_bound);
palindromes.emplace_back(product, factor1, factor2);
break;
}
}
}
auto const highest = *std::ranges::max_element(palindromes);
std::cout << std::get<0>(highest) << "=" << std::get<1>(highest) << "*" << std::get<2>(highest) << "\n";
}
} | {
"domain": "codereview.stackexchange",
"id": 43779,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, beginner, palindrome, c++20",
"url": null
} |
c++, performance, beginner, palindrome, c++20
Output on my AMD Ryzen 7 2700X, 32 GB RAM (for comparison), /O2 optimization (MSVC does not have /O3 as it seems).
Looking for palindromes from 1000000 to 9999999
Running algorithm allof
99956644665999=9998017*9997647
Calculation took 5310 ms.
Running algorithm char
99956644665999=9998017*9997647
Calculation took 5332 ms.
Running algorithm iterator
99956644665999=9998017*9997647
Calculation took 5195 ms.
Running algorithm math
99956644665999=9998017*9997647
Calculation took 121 ms. <-- bug version
Running algorithm str
99956644665999=9998017*9997647
Calculation took 8113 ms.
Answer: Sometimes, comments can be useful when #includeing headers. However, these are patently redundant:
#include <cassert> // assert()
#include <vector> // std::vector<T>
#include <tuple> // std::tuple<T>
#include <map> // std::map<T>
This kind of comment quickly becomes outdated as the code is changed, so I recommend them only when the dependency is distinctly non-obvious.
When the list of includes gets long, I find it helpful to sort them (or sort each group) alphabetically, so it's easy to avoid adding a duplicate. Sorting is possibly because all standard libraries are defined to be used independently.
is_palindrome_allof() fails to compile here, because the two iterators are of different types (the view start type and its sentinel type). That's easily fixed, by using std::ranges::all_of() in place of std::all_of() in its implementation:
auto const indexes = std::ranges::views::iota(0u, num.size() / 2);
auto compare =
[&num, &size](auto index) { return num[index] == num[size - 1 - index]; };
return std::ranges::all_of(indexes, compare); | {
"domain": "codereview.stackexchange",
"id": 43779,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, beginner, palindrome, c++20",
"url": null
} |
c++, performance, beginner, palindrome, c++20
It's a good idea to use a typedef for the type of integer we're using - if we later decide we want to work with a std::uint_max_t, we would then only need to change it in one place. We could alternatively make the predicate functions into templates (e.g. template<std::unsigned_integer Integer>, using the constraint from <concepts>).
If we're only interested in the highest product, we don't need to maintain a vector of results - just replace the value each time we find a better one.
Of course, we need to deal with the possibility of getting no results - but that's already true of the posted code: *std::ranges::max_element(palindromes) is undefined if palindromes is empty, so we should check that first.
For the questions in the comments ("can I use an algorithm here?"), I think the answer is "no" for the first one, because we have an end-point we're continually adjusting. It's possibly "yes" for the second (std::find_if() exits the loop after the first match), but I expect that would actually harm the clarity of the code.
I think that lower_bound should be made exclusive, reducing its initial value by 1 and changing the comparisons to <, because we don't want to actually reach it. E.g. having found 9999*9901, we don't want to try 9998*9901. That gave me a significant speed-up when I tried it.
We can improve the termination condition for the inner loop: since we compute the product anyway, we can break out of it once we reach a value that cannot be the highest, rather than going all the way down to lower_bound. That removes a few more calls to the palindrome predicate function. And it's worth using std::sqrt() to get a better limit for factor1.
Improved code
#include <cmath>
using Integer = unsigned long long;
Integer lower_bound = begin;
Integer max_prod = 0;
std::pair<Integer, Integer> max_factors; | {
"domain": "codereview.stackexchange",
"id": 43779,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, beginner, palindrome, c++20",
"url": null
} |
c++, performance, beginner, palindrome, c++20
for (Integer factor1 = end; lower_bound < factor1; --factor1)
{
for (Integer factor2 = factor1 ;; --factor2)
{
auto const product = factor1 * factor2;
if (product <= max_prod) { break; }
if (is_palindrome_f.second(product))
{
max_prod = product;
max_factors = { factor2, factor1 };
lower_bound = static_cast<Integer>(std::sqrt(product));
break;
}
}
}
if (max_prod) {
std::cout << max_prod << '='
<< max_factors.first << '*' << max_factors.second
<< '\n';
}
In the individual predicate functions, we can make some improvements, too:
In is_palindrome_str(), I expected that constructing backward from a pair of reverse iterators would be faster than copying followed by in-place reverse(), but I was wrong there - it's already as fast as I could make it.
is_palindrome_iterator() can be simplified using a standard algorithm:
inline bool is_palindrome_iterator(Integer n)
{
auto const num = std::to_string(n);
auto half = num.size() / 2; // rounding down is okay
// as we can ignore mid char
auto left = num.begin();
auto right = num.rbegin();
return std::equal(left, left + half, right);
}
This change was performance-neutral on my system.
is_palindrome_char() really ought to use std::size_t i to fully match the type of size/2. On the other hand, we can use what we know about the number of digits in our integer types to use a smaller (and faster) type there: auto const size = static_cast<unsigned>(num.size()); for (unsigned i = 0; i < size / 2; ++i). | {
"domain": "codereview.stackexchange",
"id": 43779,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, beginner, palindrome, c++20",
"url": null
} |
java, file, console, statistics
Title: Command-line correlation calculator in Java
Question: I have this Java program that asks for a name of the file containing data rows in the format $$
x_1\ y_1 \\
x_2\ y_2 \\
\vdots \\
x_n\ y_n
$$, and outputs on the command line the Pearson correlation coefficient of the input data:
com.github.coderodde.stat.pearson.PearsonCorrelation.java:
package com.github.coderodde.stat.pearson;
import java.awt.geom.Point2D;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
public class PearsonCorrelation {
public static void main(String[] args) throws IOException {
if (args.length != 1) {
return;
}
String dataFileName = args[0];
List<Point2D.Double> dataPoints = readDataPointsFromFile(dataFileName);
double correlationCoefficient =
computeCorrelationCoefficient(dataPoints);
System.out.println("r = " + correlationCoefficient);
}
private static List<Point2D.Double>
readDataPointsFromFile(String dataFileName) throws IOException {
List<String> dataFileLines =
Files.readAllLines(new File(dataFileName).toPath());
List<Point2D.Double> dataPoints = new ArrayList<>();
for (String dataFileLine : dataFileLines) {
String[] parts = dataFileLine.split("\\s+");
double xCoordinate = Double.parseDouble(parts[0]);
double yCoordinate = Double.parseDouble(parts[1]);
dataPoints.add(new Point2D.Double(xCoordinate, yCoordinate));
}
return dataPoints;
}
private static double computeCorrelationCoefficient(
List<Point2D.Double> dataPoints) {
double averageX = computeMeanX(dataPoints);
double averageY = computeMeanY(dataPoints); | {
"domain": "codereview.stackexchange",
"id": 43780,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, file, console, statistics",
"url": null
} |
java, file, console, statistics
double numerator = computeNumerator(dataPoints, averageX, averageY);
double denominator = computeDenominator(dataPoints, averageX, averageY);
return numerator / denominator;
}
private static double
computeNumerator(List<Point2D.Double> dataPoints,
double averageX,
double averageY) {
double sum = 0.0;
for (Point2D.Double dataPoint : dataPoints) {
sum += (dataPoint.x - averageX) * (dataPoint.y - averageY);
}
return sum;
}
private static double
computeDenominator(List<Point2D.Double> dataPoints,
double averageX,
double averageY) {
double factor1Sum = 0.0;
double factor2Sum = 0.0;
for (Point2D.Double dataPoint : dataPoints) {
double dx = dataPoint.x - averageX;
double dy = dataPoint.y - averageY;
factor1Sum += dx * dx;
factor2Sum += dy * dy;
}
return Math.sqrt(factor1Sum * factor2Sum);
}
private static double computeMeanX(List<Point2D.Double> dataPoints) {
double sum = 0.0;
for (Point2D.Double dataPoint : dataPoints) {
sum += dataPoint.x;
}
return sum / dataPoints.size();
}
private static double computeMeanY(List<Point2D.Double> dataPoints) {
double sum = 0.0;
for (Point2D.Double dataPoint : dataPoints) {
sum += dataPoint.y;
}
return sum / dataPoints.size();
}
}
Critique request
Seems to work, but I would like to hear comments on how to make it more mature. | {
"domain": "codereview.stackexchange",
"id": 43780,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, file, console, statistics",
"url": null
} |
java, file, console, statistics
Critique request
Seems to work, but I would like to hear comments on how to make it more mature.
Answer: Don't repeat yourself
The methods that compute the means of x and y have the same structure, just operate on a different field of the input list.
It would be good to extract the common logic to a helper method that takes a function to extract a double value from the input list.
Actually, the other methods also have the same shape, looping over the same list, completing a value for each item and summing, so all of them can be implemented in terms of the suggested helper method, though at the expense of one additional pass in the computation of the denominator.
It's not a big problem though, as written is easy to understand.
The CLI could be more friendly
When the number of arguments is unexpected, it could print a usage message rather than quietly ignore.
When the path parameter is not a file, it could print an error message rather than crash with a stack trace.
Avoid strange dependencies
I get that Point2D.Double has what you need, but it's defined under awt, a library for graphical UI, so it looks like a strange dependency for a command line tool.
It's not a big issue, but I think it would be cleaner to just define a custom static inner class for this. | {
"domain": "codereview.stackexchange",
"id": 43780,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, file, console, statistics",
"url": null
} |
strings, assembly, number-systems, amd64
Title: Increment a binary number represented as a string
Question: I'm an amateur at assembly, but am trying to get better at it. For fun, I decided to write code that takes in a char array and increments the number represented in binary.
Here are a few input-output examples:
inc("10001010") = "10001011"
inc("0") = "1"
inc("1") = "10"
inc("100") = "101"
Code:
section .bss
result: resb 1024
section .text
_strlen:
; rdi -> string
; rax -> output
; i -> rax
xor rax, rax ; i = 0
; first of all, the string being
; empty turns out to be an edge
; case. we handle it here
cmp byte[rdi], 0x0
je _strlen_ret
_strlen_loop:
inc rax
cmp byte[rdi + rax], 0x0
jnz _strlen_loop
_strlen_ret:
ret
global _asm_inc
_asm_inc:
; carryFlag -> bl
; i = r11
mov bl, 1 ; carryFlag = true
call _strlen ; call _strlen on the input
mov r11, rax ; move the length into r11
mov r12, r11 ; make a copy of the length
_asm_inc_for_1:
dec r11 ; i--
cmp bl, 1
jnz _no_carry_flag
; if carryFlag
cmp byte[rdi + r11], 48
jne _current_char_1
; if s[i] == '0'
mov byte[rdi + r11], 49
xor bl, bl
jmp _after_current_char_1
_current_char_1:
; else
mov byte[rdi + r11], 48
_after_current_char_1:
_no_carry_flag:
cmp r11, 0
jg _asm_inc_for_1
mov rax, rdi ; return value = input string
; well, after these modifications
cmp bl, 1
jnz _asm_inc_ret
; if carryFlag
mov byte[result], 49
_asm_inc_exceptional_case_loop:
mov bl, byte[rdi + r11]
mov byte[result + r11 + 1], bl
inc r11
cmp r11, r12
jnz _asm_inc_exceptional_case_loop
mov byte[result + r11 + 1], 0x0
mov rax, result
_asm_inc_ret:
ret | {
"domain": "codereview.stackexchange",
"id": 43781,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "strings, assembly, number-systems, amd64",
"url": null
} |
strings, assembly, number-systems, amd64
_asm_inc_ret:
ret
This code works perfectly, but I'm sure it could be improved. Have you got any suggestions?
Answer: The string being empty is indeed an edge case, but one that you can deal with in a simpler fashion. Instead of initializing your RAX index at 0, prime it with -1 and let the very first increment that happens in the loop already raise it to 0. That way, you'll have shaved off two instructions:
mov rax, -1
_strlen_loop:
inc rax
cmp byte [rdi + rax], 0
jne _strlen_loop
ret
Your string will never be that long that it would require a 64-bit length. Therefore we can safely use the shorter inc eax instruction as well as the shorter mov eax, -1 that automatically zero extends into the full RAX register.
mov eax, -1
_strlen_loop:
inc eax
cmp byte [rdi + rax], 0
jne _strlen_loop
ret
If the length should turn out to be 0, then you should not run the incrementation loop that follows at all!
cmp bl, 1
jnz _no_carry_flag
Your BL 'carry flag' is limited to the values 0 and 1. Instead of the 3-byte cmp bl, 1 instruction, you could use the 2-byte test bl, bl instruction and branch on the 'zero' condition:
test bl, bl
jz _no_carry_flag
cmp r11, 0
jg _asm_inc_for_1
The R11 register contains a length and that is to be considered an unsigned quantity, so better use the unsigned conditional jump instructions. Also, testing for zero is better done via the test <reg>, <reg> instruction and because the length is surely very much smaller than 32-bit, we can use R11D:
test r11d, r11d
jnz _asm_inc_for_1
The code that actually adds 1 to the binary number jumps around too much, and jumping is expensive speed-wise!
Consider what happens when you have to add 1 to a binary character.
For "0" (00110000b), BL becomes 0 and the digit becomes "1"
For "1" (00110001b), BL stays 1 and the digit becomes "0" | {
"domain": "codereview.stackexchange",
"id": 43781,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "strings, assembly, number-systems, amd64",
"url": null
} |
strings, assembly, number-systems, amd64
The new BL is identical to the lowest bit of the ASCII code for the digit that is to be modified (i) , and the binary character just has to toggle which you can do with a single xor byte [rdi + r11], 1 instruction (ii).
_asm_inc_for_1:
dec r11d
test bl, bl
jz _no_carry_flag
mov al, [rdi + r11]
mov bl, al
and bl, 1
xor al, 1
mov [rdi + r11], al
_no_carry_flag:
test r11d, r11d
jnz _asm_inc_for_1
And then for the killer loop optimization. As soon as BL becomes 0, you can stop the loop because no more changes will be made to the digits on the left that remain in the number.
When the incrementation loop did not produce a final carry, you leave the result where is was stored originally, but when a final carry does exist, you copy the result to another buffer (because you need the extra space). An easier approach would be to always keep one extra byte free at the start of the string. Then adding the new "1" becomes real easy...
Next snippet implements most of the above. I also prefer to use the ECX register instead of the R11D register because that shaves off an additional REX prefix from the encoding.
call _strlen ; -> RAX
mov ecx, eax
dec ecx
js _DONE ; (iii) if taken then empty string
mov bl, 1 ; carry flag = true
_LOOP1:
mov al, [rdi + rcx]
mov bl, al ; future carry flag
xor al, 1 ; new digit
mov [rdi + rcx], al
and bl, 1 ; new carry flag [0,1]
jz _DONE ; (iii) if taken then carry clear
dec ecx
jns _LOOP1 ; (iii) if taken then more digits
dec rdi
mov byte [rdi], "1" ; filling the kept-free-byte
_DONE:
mov rax, rdi ; return value = new string
ret | {
"domain": "codereview.stackexchange",
"id": 43781,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "strings, assembly, number-systems, amd64",
"url": null
} |
strings, assembly, number-systems, amd64
_DONE:
mov rax, rdi ; return value = new string
ret
The new BL is identical to the lowest bit of the ASCII code for the digit that is to be modified (i),
The code copies the current character in AL to the BL register and then performs a bitwise and with the mask value 1. This will zero every bit except the lowest bit:
AL 00110000 ASCII code for "0" 00110001 ASCII code for "1"
BL 00110000 ASCII code for "0" 00110001 ASCII code for "1"
00000001 The AND mask 00000001 The AND mask
-------- --------
BL 00000000 New 'carry flag' 00000001 New 'carry flag'
and the binary character just has to toggle which you can do with a single xor byte [rdi + r11], 1 instruction (ii).
The code has the current character in the AL register and then performs a bitwise xor with the mask value 1. This will keep every bit unmodified except the lowest bit that toggles state:
AL 00110000 ASCII code for "0" 00110001 ASCII code for "1"
00000001 The XOR mask 00000001 The XOR mask
-------- --------
AL 00110001 ASCII code for "1" 00110000 ASCII code for "0" | {
"domain": "codereview.stackexchange",
"id": 43781,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "strings, assembly, number-systems, amd64",
"url": null
} |
strings, assembly, number-systems, amd64
Very often we don't need to cmp before deciding about a conditional branch (iii)
Many instructions define flags according to the result of their operation.
In dec ecx js _DONE, the dec instruction defines the OF, SF, ZF, AF, and PF. (It doesn't touch the CF). The js that immediately follows is based on the SF that got defined alright.
Here the loop gets completely bypassed if ECX became -1 (same as SF=1), because that would have meant that the binary string had a length of 0.
In and bl, 1 jz _DONE, the and instruction defines the SF, ZF, and PF. (It also resets the OF and CF. The effect on AF is undefined). The jz that immediately follows is based on the ZF that got defined alright.
Here we leave the loop early as soon as BL=0 (same as ZF=1).
In dec ecx jns _LOOP1, the dec instruction defines the OF, SF, ZF, AF, and PF. (It doesn't touch the CF). The jns that immediately follows is based on the SF that got defined alright.
Here the loop stops iterating as soon as ECX becomes -1 (same as SF=1), because that signals that we have just finished processing the leftmost digit of the binary string.
The dec rdi can't go 'out of bounds' since the premise was that you kept an extra byte at the ready at the far left of the number.
There's no risk of writing the special "1" every single time. It only gets added in case the loop has to iterate over all of the digits of the binary string. When the early out from finding BL=0 is taken, that part of the code gets bypassed (the label _DONE: sits below it in the source).
ps. I write this in the answer because on the computer that I'm using right now, I can't post comments. | {
"domain": "codereview.stackexchange",
"id": 43781,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "strings, assembly, number-systems, amd64",
"url": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.