instruction
stringlengths
71
95.1k
This is a personal (very amateur) project to teach myself how to use if statements, lists/tuples, loops, etc. It takes an input of one letter and using a pygame-based module drawly written by one of my university professors, it draws that letter using numbered boxes (essentially pixels) that "turn on and off" based on ...
I am performing a sports prediction multi-class classification problem, and wanted to compare the differences in model performance between normalised and non-normalised data. You can see the 2 different datasets are X_train and X_train_normalised. I wanted to know if my implementation below to compare them would be cor...
I am creating an API for a version control system. This is my first time creating an API (and a web project in general) and I wanted to get some feedback. I plan to connect this API to a frontend to create website. I choose to share this part of the code because the rest of the code follows this structure. For referenc...
I've implemented a basic Trie that is supposed to work only with lowercase English letters. class TrieNode { public: array<shared_ptr<TrieNode>, 26> children; bool isWord; TrieNode(bool _isWord = false) : isWord{_isWord} { } }; class Trie { public: Trie() : root{make_shared<TrieNode>(TrieNode())} ...
I wrote a bare-bones, no fluff, base 64 library in C. My goal was to make it as small as possible. I'm wondering if there are any further size optimizations I can make (without sacrificing too much readability). #include <arpa/inet.h> #include <stdint.h> #include <stdio.h> #include <string.h> #include <sys/types.h> ...
/* let's compile using: gcc main.c -Wall -Wextra --pedantic --std=c2x -D_GNU_SOURCE -Ofast -march=corei7 -mtune=corei7 */ /* Linux headers begin */ #include <dirent.h> #include <sys/stat.h> #include <unistd.h> /* Linux headers end */ #include <stdlib.h> #include <errno.h> #include <stdio.h> #include <string.h> #inclu...
I have been working on making a transpiler from Brainfuck to C in C(11), here is the code: #include <stdlib.h> #include <stdio.h> int main(int argc, char **argv) { size_t indentlevel = 1; size_t repetition = 1; FILE *fin, *fout; int c; if (argc != 3) { if (argc > 0 && argv[0][0] != '\0') /...
I have 2 tables StockDetails, StockMail First insert Stock name and Expiration Date into StockDetails Table(inserting bulk data using XML) Then Generate Reminder date(7 Days before expiration date) and insert Stockid(auto generated id) into StockMail Table Then Update Generated id(auto generated id in the StockMail ta...
(This post is followed up by this one.) I have rolled this simple unit test library for C: com_github_coderodde_my_assert.h: #ifndef COM_GITHUB_CODERODDE_MY_ASSERT_H #define COM_GITHUB_CODERODDE_MY_ASSERT_H #include <stdbool.h> #include <stdio.h> extern size_t passes; extern size_t failed; void print_test_statistics...
(This post has a version II.) Since strtok is not thread-safe, I decided to practice and write a thread-safe replacement. This code and the demo runner may be found at GitHub. Code com_github_coderodde_thread_safe_strtok.h: #ifndef COM_GITHUB_CODERODDE_THREAD_SAFE_STRTOK_H #define COM_GITHUB_CODERODDE_THREAD_SAFE_STRTO...
Let's consider a simple graph represented by the following edges, where true indicates a visible node and false indicates a non-visible node: A (true) -> B (false) B (false) -> C (true) C (true) -> D (true) The expected output of the CompressPaths method for this graph would be a list of EdgeColumn objects representin...
I have 5 versions of some endpoint. Only V4 and V5 are used currently on the frontend side. What should I do with the V1, V2 and V3 versions? Should I remove them when are not used anywhere? @PutMapping(consumes = "application/json", path = "/v1/announcement/{id:\\d+}") @PutMapping(consumes = "application/json", path =...
I've been learning to program in C# for a couple months and wanted some feedback regarding a project I completed. Criticism and constructive feedback is what I'm after, so bring it on! I know there are improvements to be made, but I'm not sure how to implement them without crazy repetition. Where could I improve? Is ...
This is the second iteration of the Multithreaded natural language text parser code review. Special thanks goes to G. Sliepen who conducted the first review. Before reading this post, please read the first iteration, since without it most of the text below doesn’t make sense. Functional specification Implement a multit...
I have improved my code here and it looks like this: Code assertlib.h: #ifndef COM_GITHUB_CODERODDE_ASSERTLIB_H #define COM_GITHUB_CODERODDE_ASSERTLIB_H void print_test_statistics(); int get_exit_status(); #define ASSERT_IMPL(COND, FILE, LINE) assert_impl(COND, #COND, FILE, LINE); #define ASSERT(COND) ASSERT_IMPL(CON...
Objective: Given a string s containing '(', ')', '{', '}', '[', ']' (and other characters), determine if the input string is valid. An input string is valid if: Open brackets are closed by the same type of brackets. Open brackets are closed in the correct order. Code: #!/usr/bin/env python3 from pathlib import Pat...
After improving Thread-safe strtok in C according to vnp's and Harith's nice comments, I ended up with this: Code strtok_arr.h: #ifndef COM_GITHUB_CODERODDE_THREAD_SAFE_STRTOK_H #define COM_GITHUB_CODERODDE_THREAD_SAFE_STRTOK_H #include <stddef.h> char** strtok_arr(const char* const text, const char...
I've been working on a refactoring my old WordPress pricing page template and would appreciate feedback on the code structure, organization, and any potential improvements. The template is used to display a pricing list with categories and items. I've found some time so here we are, I've splitted my long code into reus...
I am building an API with Express and NodeJS. I have made this middleware to check before executing my controller, that the user is logged in. It has taken me quite a while and I would like if another pair of eyes would take a look and tell me if I have missed something important. I am not really looking for advice on ...
I'm new to React and need to display a horizontal list of items at several places in my app in differing sizes and styles. This is a utility component I came up with: function HorizontalItemList<T>({ items, itemToTile, style = defaultStyle, }: HorizontalItemListProps<T>) { return ( <Box display={'flex...
How should I refactor the following Python 3.8 snippet? import enum import typing class Number(enum.Enum): one = 1 two = 2 three = 3 four = 4 five = 5 six = 6 class Color(enum.Enum): white = 1 black = 2 class Animal(enum.Enum): cat = 1 dog = 2 class Toy(enum.Enum): ball =...
Code #include <stdlib.h> #include <stdio.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <string.h> #include <signal.h> void error(char *msg) { perror(msg); exit(1); } char *get_file(char *request) { int end, start, i; end = 4; start = 4; i = 4; while (...
I'm quite new to React hooks/Typescript/Redux. I'm building a mock e-Commerce website for my portfolio. I've got a component (Category) working and rendering data with no issues, it follows the below steps gets data from Redux RTK API slice filters the data depending on the URL renders After initial load, other filte...
How would I go about converting these function-based views into class-based views? from django.core.exceptions import ObjectDoesNotExist from rest_framework import status from rest_framework.authentication import authenticate from rest_framework.authtoken.models import Token from rest_framework.response import Response...
I was reading this website. It mentioned how to use matrix exponents to find the n-th Fibonacci number in O(log n) time. I tried implementing it Python along with a fast exponent algorithm. I'm not sure if this algorithm I have really is O(log n) time, and would also appreciate feedback on code style / practices. Here'...
So this is my first time taking a coding class. It's my second project for my IT140 class and I am making a text based game. This is my code so far. I do have a warning on Pycharm for Shadows name current_room from outer scope on [lines 23, 76, 84] but I haven't seen it create any issue so far when running the game. ...
I'm working on a tool that performs some computations using elevations from a DTM file retrieved from a WCS service. These computations will be done on predefined regions of Europe. I'm trying to encapsulate some things in classes, but it is my first time really using them, so I would love to get some feedback. Basical...
What is the most efficient way to use a look-up table in C# that works like a range? For a given number, I want to increment it by another number. I have a look-up table like so 1 1 5 6 10 60 So if the number is 1-4, increment them by 1, if the number is 5-9, increment them by 6, if the number is 10 or more, increment...
In Polish postfix notation, the operators follow their operands. For example, to add 3 and 4 together, the expression is 3 4 + rather than 3 + 4. The conventional notation expression 3 − 4 + 5 becomes 3 4 − 5 + in Polish postfix notation: 4 is first subtracted from 3, then 5 is added to it. Polish prefix notation, on t...
As the title lists, I am trying to write an effective unittest suite to ensure that the function that converts a date to UTC from local or vice-versa is doing as planned. But it seems hard because time zones/changes vary a lot so what level of coverage suffices? Here is my code thus far: import numpy as np import panda...
Following the notice that block events will be removed in a future update, I have been implementing custom block mechanics (such as crop growth and groundcover spreading) using server-side scripts instead. This particular script accompanies a custom block called 'rhizome' which randomly spreads to adjacent blocks, and ...
This is a follow-up question for A recursive_find_if Template Function with Unwrap Level Implementation in C++ and recursive_invocable and recursive_project_invocable Concept Implementation in C++. I am trying to implement recursive_find and recursive_find_if_not template functions in this post. The experimental implem...
Context- CRM system, front-end form. Requirement- Within a form users have to give a rating to a section based on user inputs, each rating has different weighting. The rating is stored in an option set field. I have used JavaScript to calculate the average score of these rating fields. Also the weighting is stored in a...
You can see it live here: https://flatassembler.github.io/nQueensPuzzle.html /* * My solution to the n-queens puzzle, one of the classical problems of the * structural programming. It asks in how many ways you can arrange n chess * queens on an n-times-n chessboard without breaking the rules that no two * chess que...
This is the third iteration of the Multithreaded natural language text parser code review. Special thanks goes to G. Sliepen who conducted the first two reviews. Before reading this post, please read the previous iteration, since without it most of the text below doesn’t make sense. Functional specification Implement a...
N Queens Puzzle is a puzzle which asks you to place N chess queens on an NxN chess board so that no two queens are attacking each other. Two queens are attacking each other if they are on the same row, diagonal or column. I solved it using recursion in the dialect of AEC that's targeting WebAssembly. However, the diale...
Background On a whim, I wrote a function called summarize_pow(). It performs dplyr::summarize() on .data for every subset (ie. the power set) of its group_vars(), to yield a list of tibbles. It optionally consolidates these into a single tibble via bind_rows(), with (optional) identifying columns. I initially wrote m...
I asked a question on Stack Overflow and there's a discussion between @Serg, who posted an answer and @Jimi, whose comments suggest that the answer might be wrong. So I implemented the following code for demonstration purposes. It is a WinForms application written in C#. I'm running old fashioned .NET Framework 4.7.2, ...
I am a beginner learning Java, and I coded a command line version of the game 2048 for practice. Any feedback, especially regarding best practices, object-oriented principles, and tidying up the code logic, is appreciated. import java.util.Scanner; class Cell { int value = 0; boolean hasMerged = false; } clas...
I'm seeking a way to streamline the updating buffer process. The code provided addresses a coupled differential equation with a delay. However, it's worth noting that it doesn't employ a circular buffer as intended, instead opting for a rolling buffer approach which is quite time-consuming. Therefore, the primary objec...
I am working out some PySpark exercises and trying to write efficient and best practice code to be ready to work in a production environment. I could use some feedback with respect to: Is the code structured well? Is the code efficient? Any other best practices I missed but should make habits of. import findspark fro...
I am working out some Pyspark exercises and trying to write efficient and best practice code to be ready to work in a production environment. Could use some feedback w.r.t.: Is the code structured well? Is the code efficient? Are there any other best practices I missed but should make habits of? import findspark from...
I am here to ask for criticism, as for my first week of Python I feel like I have improved a lot. I recreated the first program I made within my first hour with a tutorial, the one I made now is based on the knowledge I have gained within the week. It is my first language so I am sorry if the syntax is confusing I real...
The algorithm involves using two stacks. One stack (call it token_stack) holds the operators (like +, - etc) and operands (like 3,4 etc) and the other stack (call it count_stack) holds the number of operands left to be seen (say 2 for binary operators). Anytime an operator is seen, it is pushed onto the token_stack an...
The structure of a class file consists of a single structure (presented here using pseudostructures written in a C-like structure notation): ClassFile { u4 magic; u2 minor_version; u2 major_version; u2 constant_pool_count; cp_info constant_pool[...
What it does The code creates a logger class which instantiates a circular buffer at construction and uses producer-consumer style approach using condition_variable to log and print the messages to stdout. Code logger.h #pragma once #include <chrono> #include <condition_variable> #include <cstdio> #include <iomanip> #...
I've made an associative array data structure (more details in the code comments below). What I'm interested in getting a critique on is the usage of double pointers. Are they necessary here? Am I allocating and freeing the memory correctly? assoc_array.h #ifndef __ASSOC_ARRAY_H__ #define __ASSOC_ARRAY_H__ /* * A d...
Can someone please review my rwlock implementation to see if there are any issues with correctness (hopefully not), give any feedback on how to write good C code etc, design patterns which could be useful. struct rwlock{ pthread_cond_t read_var; pthread_cond_t write_var; pthread_mutex_t mutex; ...
I finished this code a few minutes ago. It started off as an explanation of a basic calculator in C to a friend. Then we decided to take it further and I made this. Please tell me where I can make changes, no matter how small, you think needs to be changed/made better. Also I'm new to the C language, I've self studied ...
Here i tried to find the longest possible non repeating sub string in a string in java..plz check my code for errors and give some suggestions for improvement... package logicBuilding; import java.util.ArrayList; import java.util.Iterator; import java.util.Scanner; public class practiceAgain { public static voi...
Introduction A first order HMM (hidden Markov model) is a tuple \$(H, \Sigma, T, E, \mathbb{P})\$, where \$H = \{1, \ldots, \vert H \vert\}\$ is the set of hidden states, \$\Sigma\$ is the set of symbols, \$T \subseteq H \times H\$ is the set of transitions, \$E \subseteq H \times \Sigma\$ is the set of emissions, and ...
I recently developed this calculator for some FEA homework i had. I'm still trying to familiarize myself with fundamental rust concepts like the ownership and borrowing. Pls let me know if there is something that could use some work/changes so that I follow rust practices better. FEA = Finite Element Analysis, the purp...
I'm looking for some feedback on this converter I made. It works just fine for the instructions I had, but I'm wondering what else could be done to improve it or if there's a better aproach to doing this. I wasn't expecting to nail this since I'm just starting to learn JS. I'm aware I could've implemented things like M...
Problem: You have been tasked with writing a method named is_all_possibilities (or IsAllPossibilities, as per your preference) that accepts an integer array and returns True if the array contains all possibilities (i.e., all integers from 0 to the length of the array - 1), otherwise returns False. My Solution: def is...
Since the standard fgets() does not suffice for my use cases, as it doesn't automatically enlarge the target buffer if needed, and getline()/fgetln() are not part of the C standard, I rolled out my own. Code: The code below is listed as one file for code review. #define TEST_MAIN // Or pass this with make/gcc. #includ...
I want to dump a dataclass instance into a dict by omitting some of the attrs. I used the metadata parameter of the field method. Also I want any bytes object to be turned into a hex string. What do you think? def asdict(obj): """ use with dataclass only """ dict_ = {} for k, v in obj.__dataclass_fields__.i...
Problem: Whenever new data are inserted, extract BigQuery tables as csv files and store them in Cloud Storage. My plan: Set up an Eventarc trigger based on Event method google.cloud.bigquery.v2.JobService.InsertJob for Cloud Function to identify when new data are inserted into BigQuery. from google.cloud import bigqu...
A friend posed to me a question to see if I could solve it. He says I solved it appropriately. I was hoping someone here could give me a review of the program I wrote to answer it. I figured it would be a good exercise in trying to do things as well as possible and try to follow conventions. The problem Aaron and Alexa...
In my case I am saving a URL into my database via Eloquent Model: namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Str; class PageLink extends Model { use HasFactory; protected $table='links'; public function setU...
Despite the intention is to use it in a C++ project I put the c tag also because there is nothing C++-only (except references :)) in the code (I did not compile it by a C compiler though). Preliminaries I'm working on an automation system the main function of which is to control positional table. The table has 5 degree...
This is a "minimal thread pool" I came up with to compare with a colleague's approach using Rust's Rayon's par_bridge() to automatically parallelize looping over an indexed container (a vector in his case). This is basically a std::for_each with std::execution::unsequenced_policy (in this case), but you have access to ...
Here's a simple authentication server. It's pretty basic but has the core functionality of sign-up and log-in handling. Your best bet is to simply run the docker-compose file Main package com.example.tokenservice; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBo...
Performs interpolation binary search over an array sorted in ascending order. If value found returns found and index else returns not found, the insertion index is returned. Assumptions : data is sorted in ascending order and all the values in data are unique left >=0 and right <= data.size - 1 and left < right durin...
I have created a Grid out of using the new concept of List in Kotlin. I'm open to any feed back to how this code could be improved. It functions as expected and I'm happy with the results. import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.co...
The library (inspired by stb libraries) attempts to provide some commonly used functions (reading a file into memory, determining the size of a file) that are missing from the C standard library portably (for my own use cases). Code: #ifndef IO_H #define IO_H #include <stdio.h> #include <stdbool.h> #include <stdint.h>...
I have the following org-table datum werk start pauze start pauze stop werk stop 12/02/2024 09:48 12:45 13:14 17:22 13/02/2024 08:01 12:06 12:31 16:38 14/02/2024 07:38 12:12 12:38 16:48 15/02/2024 08:11 13:11 13:28 17:08 Now I want to calculate how many hours I did per day and see if I did too much or t...
we are trying to justify a long text into a image and we need to justify it. We have solved the problem with this function, but it's too heavy and takes a long time to process the text justification. Any faster solution in order to justify a text? $image = ImageCreateFromJPEG( "sample.jpg" ); $color = imagecoloralloca...
I'm learning Rust. Could you share some tips for improving this code so it's more idiomatic and functional? I would prefer to stick to the standary library, and avoid unnecessary sorting or memory allocations. fn first_file_in_dir(dir_path: &Path, extension: &str) -> Result<PathBuf, io::Error> { let mut matching_pa...
Here is the code I am using it works fine; however, it obviously takes forever when there are a lot of files to check. exact shell is cmd.exe. I am really just looking to make it more efficient. Here is my run.bat file: setlocal enableDelayedExpansion setlocal enableextensions :: date variable set theDate=%date%-%tim...
I am working on a PHP application that transforms data from the input CSV (JSON, TXT, or XML) into an output CSV (JSON or database, for example). The output format differs from the input: some columns can be skipped, and some values can be converted (e.g. blue => 1, or 1.85 => 185). Also, the headers can have different...
(Please note: the post about the compose implementation announced below is now available.) This is about decorating callables by making their argument and return value to be a std::optional. Therefore I created the template function make_skippable that takes a callable and returns a wrapping lambda having an optional a...
I am building users API with CRUD operation in fastapi and i'd love to hear feedback about it. I have been exploring fastapi in the past weeks and im trying to create API with best practice (scalable - no pagination yet, robust, effective and efficient) route.py from fastapi import APIRouter, Depends from users.seriali...
I wanted to make a VBA that creates self-renewing combinations and I actually did it, but Excel was crashing when the combinations increased, unfortunately Excel does not work in multi-item lists. That's why I worked out the codes that create the combinations with C#. I am adding all my work, I think someone who unders...
Are the two function templates below well-formed for serializing/deserializing POD types? Will they work for all the different types that satisfy the constraint pod? Here (live): #include <type_traits> #include <ostream> #include <istream> #include <fstream> #include <print> #include <stdfloat> template <class T> con...
I was trying out leetcode's first missing positive. As per the challenge's description: Given an unsorted integer array nums, return the smallest missing positive integer. You must implement an algorithm that runs in O(n) time and uses O(1) auxiliary space. My solution passes all tests, except last five i.e. where t...
I have created two pages (one straight HTML, the other PHP) to show an HTML file in the context of my server. The reason for this is simply to get access to / the styles in the CSS spreadsheets - not allowed when the page is opened straight from the file system. These styles are saved in a meta field in the header and ...
Now I have this result. Code com.github.coderodde.util.SkipListMap.java: package com.github.coderodde.util; import java.util.Collection; import java.util.Comparator; import java.util.Map; import java.util.Objects; import java.util.Random; import java.util.Set; import java.util.SortedMap; import java.util.function.BiCo...
I want to reduce time complexity of my code: I have an array of integers arr say [1, 2, 3, 6, 67] I have an equation : a*x+b*y=z, I can use the array values in this equation to replace x and y, by some array positions say arr[i], arr[j] i and j can be different or same. so it looks like this: a*arr[i] + b*arr[j] = z; ...
I'd like to ask you for a code review of this class. I'm quite new to Java and I'm afraid I have way overengineered this class. It's goal is only to fetch a specified data from given API, whose link is stored in config.properties. I would be grateful for both implementation details critique and design ones too. package...
Good morning everyone, I am trying to figure out how deep learning works. My approach is mainly theoretical but I have decided to code a few deep learning projects to get a better feel of the kind of work involved. Most courses and textbooks out there recommend that your first project as an aspiring AI engineer should ...
I'm six months into a Java training program and have developed a Spring Boot application, adhering to Java's separation of concerns principle. I've organized my application with distinct sections for data logic, input data, and business logic. Now, I'm seeking guidance specifically on the choice between Field Injection...
The provided code (a header-only library inspired by stb libraries] defines functions for creating a stack, pushing elements onto the stack, popping elements from the stack, peeking at the top element without removing it, checking if the stack is full or empty, getting the size of the stack, and destroying the stack. N...
I am working in a Web Api project that has the following project structure: Root Controllers Orchestrators Managers Services etc The Controllers depend on Orchestrators. The Orchestrators depend on Managers. The Managers depend on Services. The Services are making calls to external dependencies e.g...
My database structure is: assets - id (int) - name (text) - stock (int) booking: - id (int) - asset_id (int) Refers to the assets table - quantity (int) How many assets are planned in this timeframe - start_date (datetime) - end_date (datetime) I need to find the amount of ...
I'm coding a chat application from scratch in modern C++. I'm currently building an interface for interacting with sockets. I want it to be cross platform. Am I approaching platform independence correctly? Also is my error handling acceptable? Please tell me what is wrong and what should I improve or change. Socket.h ...
Background and use-case I need to create a stored procedure where the input parameters will be: @sourceTable, @targetTable, @compositeKey. I'm using available fields for the composite key, since I need to create myself what makes the row unique. Also, I want to use this procedure on other tables in other scenarios with...
I have been asked to implement this and completed that. There was also a request to apply the SOLID principles and use a CLEAN CODE approach. Write a program that prints the numbers from 1 to 100. But for multiples of three print "Fizz" instead of the number and for the multiples of five print "Buzz". For numbers whic...
I'm building a sliding bottom panel as a React component, adapting Phuoc Nguyen's excellent draggable element tutorial. It currently looks like this: The expected behavior is: User taps on button to open panel Panel slides from the bottom up to fill about 90% of the viewport User can then drag the panel down to close...
I am writing a C# Database connection class and I am trying to adhere to best practices and produce clean code. In the CreateAndOpenDatabaseConnection function below I am instantiating the connection object and opening the connection. Is this a violation of the Single Responsibility Principle (SRP), because of me insta...
I am writing a C# Database connection class and I am trying to adhere to best practices and produce clean code. In the CreateAndOpenDatabaseConnection function below I am instantiating the connection object and opening the connection and in the CreateSqlCommand function I am instantiating the command. Should the SqlCon...
I wrote a tokenizer but it's not very readable. How can I make it more readable? import std/os import std/streams import std/deques var strm = newFileStream(paramStr(1), fmRead) var stack = initDeque[string]() var arr = newSeq[string]() proc startEnclosure(token: string) {.discardable.} = echo token stack.addFirs...
I want to check if the current time is "close" to 9pm UTC. I have the following code to a.) get "now" and convert it to UTC time and b.) get 9pm utc time. Based off when I run it, it looks like it's running. However, I usually use scripting languages, and this looks absolutely crazy to me. I don't necessarily want to ...
C23 has introduced attribute specifier sequences. Consequently, the header below attempts to conditionally define macros for these sequences (for my own use cases). In cases where a compiler does not yet support them but does support GNU C's attributes, the macros will expand to utilize GNU C's attributes, provided equ...
This is a follow-up question for A recursive_transform_reduce Function for Various Type Arbitrary Nested Iterable Implementation in C++ and recursive_invocable and recursive_project_invocable Concept Implementation in C++. I am trying to implement another version recursive_transform_reduce function which takes unwrap_l...
I am going to do a math competition which allows writing programs to solve problems. The code attempts to solve problem 25 from the Purple Comet Spring 2004 Mathematics Meet: In the addition problem W H I T E + W A T E R ----------- P I C N I C each distinct letter represents a different digit. Find the number ...
The problem is: Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] where i, j and k are distinct and nums[i] + nums[j] + nums[k] == 0. The solution set must not contain duplicate triplets and the order of the output and the order of the triplets does not matter. This is my code: def thre...
I'm working with an API, where the url can be constructed with setting_ids. To more clearly indicate the functionality of the setting ids I am mapping them to a WriterClass' methods, with relevant names. In the code below these are method_a to method_c, in the true application this is a list of ~250 settings. The funct...
let currentWeekNumber = 1; // Initial week number function getWeeklyDates(year, month, weekNumber) { const dates = []; // Set the first day of the month const firstDay = new Date(year, month - 1, 1); // Calculate the offset to the first day of the week (assuming Sunday is the first day) const fi...
The goal is to take an array of numbers, have a max weight (saying 40%), and if any number above the max_num = sum * weight is present, remove the excess and distribute it over the sum of numbers that are below max_num based on their own weights. The code is designed to be able to take a sum of any number, although in ...
This is a follow-up question for A recursive_transform_reduce Template Function with Unwrap Level Implementation in C++. To fix the issue mentioned in G. Sliepen's answer, I updated the test cases and recursive_transform_reduce itself. Please check them again. If there is anything I missed, please let me know. Test Cas...