instruction
stringlengths
71
95.1k
I use the function trace() to calculate the trace of a matrix. This is not important. But for this specific matrix this value is -1. My variable "trace" is set to this from the function. However when I compare this value as a boolean it shows they are not equal. Why is this happening? Code: double trace = R.trace(); do...
I wrote a simple Cumulative grade-point-average calculator in C++, and would like to ask for advices to improve the code in terms of best practices (efficiency, reliability) in the language. Here's my code: #include <stdio.h> #include <iostream> #include <string> #include <vector> class Subject { public: s...
I've tried to make a small template for the creation of distinct (incompatible) numerical types. For example both row and column indices are usually represented as the same underlying type. However it is rare that you would want to mix the two. Code template< typename Base, std::size_t Id> struct Alias { explicit( ...
I am developing a code to compute Value at Risk (VaR) using various models (see below). Currently, I am looking to implement a rolling window approach over a dataset spanning 4,000 days, with each window covering 500 days. My goal is to generate 3500 VaR forecasts using different VaR models within this rolling window f...
I wrote a simple brainfuck interpreter in C99. Coming from a background of C++ made the task easier, but still there is some stuff I had to get used too. The program accepts a path to a brainfuck file as a command line argument, and also an optional tape size. Tape size is defaulted to 30000 bytes. It also features som...
Recently, I got into programming with Python as a fun little side hobby. After watching a bunch of YouTube tutorials (to learn about IDE's, variables, etc.), I finally got to the point where I was able to make this really simple game where the player tries to guess the number that the computer generated. So, today I wa...
I'm a sophomore in computer science who's working on a linked list class for his DSA class. I believe this code can be improved, but I'm not sure how because everything got really messy really fast. Thanks. List.hpp: // This is a blueprint for all list-like data structures. // It won't specify how the operations are ca...
so I got started with competitive programming about a day ago and I got stuck on the first random question I tried on codeforces. It's called Dasha and Nightmares. Problem Description: The problem involves finding the number of unique nightmares formed by concatenating pairs of given words. A nightmare is defined as a ...
I've been working on a project related to a fruit and vegetable scale program for about a month, and I'm relatively new to programming. In this project, I'm trying to adhere to object-oriented principles and make my code as object-oriented as possible. I started from a single class structure in my previous assignment a...
I tried to write a decent answer to Most efficient way to get the largest 3 elements of an array using no comparisons but a procedure for ordering 5 elements descendantly. I could not come up with something concise, let alone compelling. I assumed duplicate values were allowed; unique values allowing "multidimensional ...
I built an image upload API with Python Django. There are a fixed number of 6 slots, which can either be null or filled with something. There are two entities, Profile, which contains the six photos, and an overridden save method. The other entity involved is Upload, which contains the timestamp when it was uploaded at...
I'm trying to find the fastest way to multiply every element in an array by a given number, in this case 2. So far I have written a SIMD instruction that performs at 33 ns multiplying every number in an array of size 1000 by 2. The techniques used so far are: SIMD instructions, MemoryMarshal method for the loop, Spans,...
I have three arrays in which first index is same, so I want to merge all three array into one array based on first index element Input: [[1, 'A'], [2, 'B'], [3, 'C']]; [[1, 'D'], [2, 'E'], [3, 'F']]; [[1, 'G'], [2, 'H'], [3, 'I']]; Expected output [ [ 1, 'A', 'D', 'G' ], [ 2, 'B', 'E', 'H' ], [ 3, 'C', 'F', '...
I'm working on a codesignal practice problem You are given an array of integers a and an integer k. Your task is to calculate the number of ways to pick two different indices i < j, such that a[i] + a[j] is divisible by k. Guaranteed constraints: 1 ≤ a.length ≤ 10^5, 1 ≤ a[i] ≤ 10^9. Now, the problem is sup...
I'm writing a brainfuck compiler in rust, that takes brainfuck instructions and converts them to a very basic assembly form, and then compiles that into binary, if you are not familiar with brainfuck I have included some resources, but the basic premise is this, the language operates with a memory tape, and there are 8...
I created a simple password system using HTML, CSS, and JS to quiz myself on my variable, localstorage, and if and else statement knowledge. I don't know how to make the create/login password input fields required though. Any other improvement suggestions/feedback would be appreciated! <!DOCTYPE html> <html> <head> ...
Can someone see if have not made some stupid mistakes in the binary semaphore implementation? I know that some more checks have to be added but I have eventually lost the initial idea in the details. /** * @brief Print an error message with additional information about the source code location. * * This function for...
I'm taking the 100 Days of Code (Python) taught by Angela Yu on Udemy. There have been a few other questions revolving around this lesson but I can't find one who came up with my specific question so I do apologize if it's out there somewhere. The course is asking us to check whether or not a year is a leap year using...
The purpose of this code is add proxy on nested object for log changes on property. This is a debug utility! // check if value is object or array function isObject(value) { return value !== null && typeof value === "object" && ["Array", "Object"].includes(value.constructor.name); } // add nested proxy ...
Util class to find into a collection the indexes of a given element with multiple occurrences from the first index or relative to a given index. import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; public class NextIndex { public static <T> Lookup<T> of(T e...
I have commented out two attributes (in random_number_guesser.py) which I believe are unnecessary. Am I correct in assuming that, because the code runs correctly without their implementation, they should not be included in my program? player.py class Player: def __init__(self) -> None: """Initializes the p...
This algorithm encodes a 64 bit integer. As input I have a 64 bit integer a, for example: (a is a single 64 bit number,which I split in 8 bytes for readability) a=11110110,10101110,00010000,01100110,11101011,11000001,11001011,01100011 To calculate b=f(a), I begin with the rightmost digit (the less significant digit) a...
The three characters that occurs most in a given string should be printed by using streams/lambdas (functional programming). The order of characters that occur equally often should be preserved. My thoughts were to use a LinkedHashMap for counting (accumulation), and then to use a ArrayList for sorting the results. I w...
I've developed a Python script that simulates die rolls and analyses the results. I'm now looking to extend and modify this code for more complex data science tasks and simulations. Is this code simple and readable? Are there more insightful statistics or visualisations that can be generated from the die roll data? Ho...
I wanted to calculate topological sort given a few predicates asserting that one element should be before another in a sequence. order(a, b) means that a should go before b. I ended up implementing Kahn's algorithm: pop_dict(Key, DictIn, Value, DictOut) :- Value = DictIn.Key, del_dict(Key, DictIn, _, DictOut). ...
Today, I tried to write a simple function that would display the characters of my string one by one by iterating over a string containing the letters of the alphabet and showing the steps on the screen. Just out of personal curiosity and fun: how would you write it? Is there something you would optimize, both in terms ...
I'm brand new to using rust, so please bear with me. I'm trying to write a rust program which takes two arguments: A URL, and a wordlist. This wordlist has the following contents, and is several hundred thousand lines long: ... example1.php example2.php example3.php ... I want to read all of these from the wordlist fi...
Embodying the helpful tips from the “Sequentially find the indexes of an element into a collection” previous code review resulted in extending the implementation to bidirectional index lookup, that is starting from first element or starting from the last element. Util class to find into a collection the indexes of a g...
This is an attempt to create a usable alternative to the "normal" method of implementing concurrency with tkinter. The "normal" method seems to be by pro-actively polling a result queue and using mainloop.after(), such as in this example. My (attempted and perhaps naive) implementation uses a listener interface so that...
I've written some code that performs movement similar to the Tomb Of The Musk game. The idea is that the objet should move in a certain direction until it encounters an obstacle. After that, the player can choose which way the object should move. The code I wrote seems to me to be rather unoptimized. I think it could h...
This is a follow-up of this quesiton: Filter: BMP Image Filtering Tool Changes: Added comments where necessary. Added checks for integer overflow. Added support for input and output redirection. Added support for more than one filter in a single invocation. Eliminated casts, magic numbers, and Windows typedefs for sta...
I am a beginner. I have really struggled with fgets() when using the function twice. I am on Windows with VS Code and C++ extension. My test program is working, but it is IMHO lengthy and complicated for such a simple task. Furthermore, the use of goto is bad practice, I have read. Is there a simpler solution? #include...
I'm wondering if this is the best way to write the Java code I have written. It works, but looks overly verbose, is it possible to rewrite any of the code to make it more concise? Please ignore the constructors for now as I'm going to add DI in the coming days. I did google beforehand but wasn't getting much luck with ...
I have a database with the following hierarchy. A dataset can have multiple scans (foreign key scan.id_dataset -> dataset.id) A scan can have multiple labels (foreign key label.id_scan -> scan.id) A label has a labeltype (foreign key label.id_labeltype-> labeltype.id) The dataset, scan and labeltype tables all have a ...
I have a .json file with name (string) and RGB (r, g, b: numbers) with 30.000 key-value pairs. I am looping the json multiple times per second to find the closest name to a given RGB color. Any idea how I can optimize the code or the json data to make it faster? Currently it works fine for the few calls per seconds, bu...
I would be grateful if you could review my code for a multi producer/consumer lock-free queue in C++. I am mainly after performance improvements, but all input is welcome. #pragma once #include <array> #include <string> #include <chrono> #include <atomic> #include <thread> #include <optional> #include <cmath> templat...
The code below groups a list by either number or letter, as seen below: 1A, 1B, 2A, 2B, 3A, 3B, 4A, 4B, 5A, 5B or 1A, 2A, 3A, 4A, 5A, 1B, 2B, 3B, 4B, 5B The option is configurable by the user via the loopOrder variable. The code essentially sets the first loop (i loop) or third loop (k loop) to 1 to negate it and t...
#!/usr/bin/bash # debug #export PS4='$LINENO + ' #set -x # description : #TODO # # # PERSONAL FUNCTION HERE ######################## ## # #TODO # ## ######################## # help information myhelp() { #TODO echo "usage : mksh [options] {files} " echo '' echo " -h,--help check for help" e...
Description I've written a heap allocator in C++ using an explicit free list for organization. I've also written a series of unit tests and a microbenchmark using Catch2. At time of writing I've tested it with gcc and clang on Linux and MSVC and clang on Windows. The intended use case for this code is personal projects...
I was recently doing an assignment for a job interview, which asked to create a simple key value database with 4 command line operations: create key value: Adds a key value pair/updates an existing key get key: Prints the value corresponding to key, if it exists del key: Deletes a key value pair ts key: Returns the ti...
Can you tear my code apart with code review comments? Below is a simple method which reads an XLSX file and does some stuff with it. I use FileInputStream and XSSFWorkbook to do the processing. The code block which I am concerned about is the exception handling (I have been told that it's buggy/not ideal). Note: I am n...
I'm new to Razor pages. I would like to bind a <select> list to an object's property that is a list of another object (Report.EventyTypes). Consider the following code: Report.cs public class Report { [Key] [Column("ID")] public int Id { get; set; } public string PersonName { get; set; } public Li...
I wrote a trait library that allows the de-/serialization of data structures from/to little endian bytes 1. For it I now wrote my first procedural macro 2 to be able to derive the traits FromLeBytes and ToLeBytes for structs: use proc_macro2::TokenStream; use quote::quote; use syn::{parse_macro_input, parse_quote, Data...
I have some logic that helps me calculate the data for a summary of an event, which should be rendered as something like this: People in the event right now: 10; People by company in the event right now: Green Group (10), Hoppe Group (5); People not checked-in: 200; However, I have received a complaint that it is unne...
This is a follow-up question for A recursive_fold_left_all Template Function Implementation in C++. Besides recursive_fold_left_all function, I am trying to implement recursive_fold_right_all template function in this post. The experimental implementation recursive_reverse_foreach_all template function implementation ...
I am creating my own bitboard chess engine in C#. I am trying to optimize my make move, unmake move, and move generating functions to get a good fast base. My C# skills are average and got some tips from articles, forums and videos on how to increase performance. If you have any advice on how I can make it faster then ...
Project Euler Prime Pair Sets: The primes 3, 7, 109, and 673 are quite remarkable. By taking any two primes and concatenating them in any order the result will always be prime. For example, taking 7 and 109, both 7109 and 1097 are prime. The sum of these four primes, 792, represents the lowest sum for a set of four pr...
I developed this application for the company I work for. It became increasingly challenging to locate drawings within the myriad of folders, especially when searching for the most up-to-date versions. I have another app that generates an index of files, boasting over 90 thousand entries. The index includes the name, fo...
Here is a code for a simple model of three phase two level inverter with constant DC voltage source and three phase RL load. import numpy as np from datetime import datetime from scipy.integrate import solve_ivp from scipy import signal ##Parameters #time axis starting_time = 0 #[s] step_time = .2e-6 #[s] ending_time ...
For a research project, I want to assign a unique identifier to a stream of bits. I can assume that all the streams will always have the same size. Because of this nice property, my idea has been to use a binary tree structure to assign to each stream a leaf storing its unique identifier. In the following, I call these...
Lately, I was studying the concept of unit testing in python, so I have decided to write a imperative strong password validator ( checker ) and also attach a unit test to it. I would like to know if there is any recommendation for improving this code, Thanks! main.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- "...
I'm writing an application to sync files between two directories. In order to prevent simultaneous access to the shared directory from several computers, I implemented blocking of the shared directory. The class below implements this lock. The application is built and at first glance works without errors. But I'm new t...
I have a code that calculates Euclidean distance on a grid with border crossing or without that. def distance(x1: int, y1: int, x2: int, y2: int, grid_size: int, border_cross: bool): if border_cross: min_x = min(abs(x1 - x2), grid_size - abs(x1) - abs(x2)) min_y = min(abs(y1 - y2), grid_size - abs(y...
Need to clear my brain. BF interpretor in C++. bf.h #include <vector> class BF { std::vector<char> memory; std::size_t dp; template<typename I> I findMatchingClose(I start); public: BF(std::size_t defaultMemorySize = 4096); void reset() {dp = ...
I'm somewhat new to python and I'm creating a script that requests to a certain API and then uses the response to populate a local DB, so far I have the following: Project Structure ├─── logs │ ├─── app-logs.log │ └─── err-logs.log │ ├─── secrets │ └─── config.ini │ ├─── src │ ├─── api │ │ └─── send_request...
A large cube-shaped box has the dimensions 5x5x5. This box is to be completely filled with smaller boxes. Possible candidates are: 1x1x1, 5-fold 1x2x4, 6-fold 2x2x3, 6-fold An additional "magic" box with the dimensions 1x1x1 should always be placed in the middle/center of the large box. This should be solved with bac...
I am trying to code a state machine for the given state diagram: I module mealy(input x_in,rst_n,clk, output reg y_out); parameter s0 = 2'b00, s1 = 2'b01 , s2 = 2'b10,s3 = 2'b11; reg [1:0] p_state,n_state; always@(posedge clk,negedge rst_n) begin if(!rst_n) p_state = s0; else if(clk) p_state <= n_stat...
I'm a newbie python developer, and fortunately I have been introduced to the principle of abstract base classes and they seemed pretty interesting to tackle while going forward in my Python journey. I've had multifarious tries in order to implement an abstract base class correctly so the child class also won't be left ...
I am trying to filter steps such that it only contains numbers from 1 to step_size that aren't divisible by factors of step_size. However, the only way I can get it to work is using a flag like this, which seems to be suboptimal. (This is part of a larger prime factorizer, which works quite well with this prime_count, ...
This is the program I have written to return the list of keys if the current hour is present within the range provided. # time_mapping has data in key:value pair # where value consists of time range in 24 Hr format. # For key 'abc', the time range is 6AM (i.e. 6) to 3PM (i.e. 15) # For key 'def', the time range is 2P...
Here's my FieldInspector. It compares objects by field values and performs deep null checking. What do you think? It works, but I'm not happy with how it looks. I don't believe it's an example of clean code. How can I improve it? That "memorizing" was my solution to cyclic dependencies. Otherwise, you get StackOverflow...
I'm learning Rust, and as-is tradition, I'm starting out with a Mandelbrot Set explorer as my first project (although, it just produces images so far). When run, it just creates and writes an image to the CWD. The coordinates and coloring function that are hardcoded produce my avatar. Eventually, there will be a GUI us...
In answering How to do file I/O with bool in C?, I made a helper function that used fgetc() calls to substitute the missing fscanf() bool * specifier. Also included is a test harness. Review goals: Primary: Review fscanf_bool() for how well it achieved the above goal as well as any other concerns. Secondary: Review t...
This is an updated version of my Tic Tac Toe game with AI players, it is related to GUI Tic-Tac-Toe game with six AI players - part 1: the UI. But that question is more than two weeks old and no one has posted an answer. I have spent well over two months on this project and I don't know if I did it right, I just patche...
I've tried to implement merge sort in c with varying degrees of success, one was correctly sorting the array but leaking memory, one was neither sorting the array and leaking memory. The following was an attempt at implementing the algorithm again with these points in mind: Memory must be freed in the scope it was all...
I have a class template that stores an std::optional<T>. A very reduced version of the class template looks like this: template <typename T> class param { public: param() = default; param(T const& t) : m_value(t) {} bool is_valid() const { return m_value.has_value(); } T const& value() const { ...
This question contains code of the updated version of my GUI Tic Tac Toe game, the code is about the styling and playing piece customization. It is related to: GUI Tic Tac Toe game with UNBEATABLE AI players and GUI Tic-Tac-Toe game with six AI players - part 2: the styling Much of the code is reused, I wrote the code...
This is my Python3 code which solved the 10th problem of Project Euler. I haven't passed the last 2 time limit test cases. def sieve_of_eratosthenes(n): result = [True] * (n + 1) result[0] = result[1] = False for i in range(2, int(n**0.5)+1): if result[i]: for j in range(i*i, n+1, i): ...
After spending a considerable amount of time poking at the internals of the Collection class, I have discovered 2 methods to iterate a private internal array within a VBA class using a For Each loop on the class instance. Both methods: work without the need for assembly code or external DLL references make use of the ...
I have created a rock paper scissors game in C++. #include <iostream> #include <map> #include <vector> #include <time.h> std::vector<std::string> gameOptions {"Rock", "Paper", "Scissors"}; // Map of Key as winner and Value as loser std::map<std::string, std::string> gameRules { {"Rock", "Scissors"}, {"Scissor...
I'm making a image processing application in c from scratch using P6 ppm images, I want some input on my code before I start adding more features to prevent it from falling apart if it's not well structured sample output improc.h #ifndef IMPROC_H #define IMPROC_H #include <stdint.h> typedef struct { int size; ...
I again share my Python code which didn't pass time limit test cases in the HackerRank contest of ProjectEuler. def get_divisors(number): divisors = [] for i in range(1, int(number**0.5) + 1): if number % i == 0: divisors.append(i) if i != number // i: divisors.ap...
I've got an application with a filter that offers the user over 30 different search cirteria that I need to translate into an SQLite query. A small DSL should simplify creating more efficient where clauses without the need of using dozens of parameters or hardcoding everyting in the SQL itself. Example I would use the ...
Here's a JavaScript function that check the equality of input and secret strings, trying to do that without leaking information about secret: function timeSafeEqual(input, secret) { let equal = input.length === secret.length for (let i = 0; i < input.length; ++i) { const ofInput = input[i] cons...
I'm writing a password manager application, mostly with the goal of learning about proper handling of encryption. Here is my code responsible for encrypting/decrypting passwords and loading to/from file. The PasswordDataBase class is pretty bare as is, but will incorporate more functionality going further (such as filt...
This post is regarding the revamp of this post/project I did about 8 months ago. I took a lot of the advice from the suggestions provided (thank you by the way), and fixed the project up, so I'm reposting it. @Ajinkya Kamat wanted to see the revisions I made, so here they are: (From https://replit.com/@Selisine/CBPR?v=...
Introduction I have a telegram bot based on aiogram framework. It does GPU intensive computations locally then user makes a request and outputs a text file after computations are done (which takes from 1 to 10 minutes). I figured out that I should use a second thread for computations and leave the main thread for bot h...
I have written a Wordle solver in JavaScript. The solver generates a decision tree. For each word, it generates all possible feedbacks patterns for that word, it then selects for each pattern the word that on average, given all possible feedbacks, reduces the size of remaning words the most. The algorithm is taken from...
Hey, i just finished work on a Element based FiFo Buffer in C. Layout of this question: Intro .h File .c File Usage Example Intended Use-cases Question .h File #ifndef Std_FiFo_LINEARBUFFER #define Std_FiFo_LINEARBUFFER #include <stdint.h> //Include for the UIntXX_t types #ifdef __cplusplus extern "C" { #endif ...
I'm looking for pointers on the best way to optimize my code below. The query is designed to pull for a vendor database in a separate SQL server table that I built a connection to in my wordpress site. I've created three different queries based on the value that gets passed in a search field. Either it's a vendor name,...
I create a game in the terminal the premise(for now) is walking around a field collecting points marked as $, and avoiding mines marked as !, the player is marked as @ and normal terrain marked as #. the playing field consists of a bunch of boards, all the boards are the same size and the field is those boards connecte...
Is the following Python code, which calculates hand angles based on current time, simple and readable? What alternative approaches can enhance simplicity and readability? Are there concise one-liner solutions worth considering? def calculate_angles(current_time: List[int]) -> List[float]: ''' Calculates hands angle...
This function outputs random values in a list. Although I was happy to craft this solution from a more complex version, and it looks really cool to me, I wonder if it is an example of clean code. How can it be improved, and what are other ways to write it? def random_time_values() -> List[int]: ''' Generates random...
Given an array a and a number d, I want to count the number of distinct triplets (i,j,k) such that i<j<k and the sum aᵢ + aⱼ + aₖ is divisible by d. Example: when a is [3, 3, 4, 7, 8] and d is 5 it should give count as 3: triplet with indices (1,2,3) 3+3+4=10 triplet with indices (1,3,5) 3+4+8=15 triplet with indice...
The given Python code snippet is for drawing clock markings. from waffle_oak_clock import markings_number, markings_radius, markings_hours_size, markings_hours_color, markings_minutes_size, markings_minutes_color, clock def draw_markings() -> None: ''' Draws the markings of the clock ''' for i in range(marking...
I've written a python function to split a netmask or an ip address. The code is about to become part of a custom router api. def split_ip_or_netmask(ip_address: str) -> list: """ Splits an IP-address or network mask into the parts between dots. Returns a list of parts. """ if not isinstance(ip_add...
I built a theme toggle switch function, and refactored it following an awesome suggestion in a previous answer. Before the refactoring the function looked like this: def toggle_theme(): if state["theme"]["light_mode"] is False: # If it is dark mode at the moment, make light state["theme"]["light_mod...
ERROR: type should be string, got "https://www.acmicpc.net/problem/23204\nI've solved a programming challenge where you need to count the occurrences of a specific digit at the end of the product of multiples of a given number within a certain range.\n\nDescription\nA large shipment of doodads has just arrived, and each doodad has a suggested retail price of b cents. You’ve noticed that consumers are much more likely to purchase goods when most of the trailing digits are the same. For example, items are more likely to be priced at 99 cents rather than 57 cents. So to make your goods more appealing, you’ve decided to sell your goods in bundles. To make a bundle, you choose a positive integer k, and sell k doodads for k × b cents. With an appropriate choice of k you can have a more pleasing price. For example, selling 57-cent doodads in bundles of size 7 means that each bundle sells for 399 cents, which has two trailing 9s, rather than no trailing 9s of 57. This idea of trailing 9s can be generalized to any other trailing digit: bundles of 692 57-cent doodads sell for 39 444 cents (three trailing 4s) and bundles of one million doodads sell for 57 000 000 cents (six trailing 0s).\nAfter a little thought, you realize that you do not want to make your bundles too large—not only can the price be excessive, but who really needs several million doodads? For any type of doodad, your marketing department has a maximum bundle price of a.\nGiven the price of a doodad, the desired trailing digit, and the maximum price of a bundle, write a program that optimizes the trailing digits.\nInput\nInput consists of a single line containing three integers b, d, and a,\nwhere b (1 ≤ b < \\$10^6\\$) is the price of a doodad in cents, d (0 ≤ d ≤ 9)\nis the desired trailing digit, and a (b ≤ a < \\$10^{10,000}\\$) is the maximum\nprice of a bundle.\nOutput\nOutput the maximum number of consecutive occurrences of d that can\nappear at the end of a bundle price, given that the price of the\nbundle cannot exceed a.\nsample input 1\n57 9 1000\n\nsample output 1\n2\n\nsample input 2\n57 4 40000\n\nsample output 2\n3\n\nsample input 3\n57 4 39000 \n\nsample output 3\n2\n\n\ncode\ndef main(B,d,a):\n\n count=0\n max=0\n price=0\n i=1\n while price<a:\n price=B*i\n #print(price)\n #print(str(price))\n count=0\n\n\n for x in range(len(str(price))):\n\n if(str(price)[len(str(price))-1-x]==str(d) ):\n #print(\"price\",str(price))\n count+=1\n #print(count)\n else:\n break\n\n if(max<count):\n #print(\"max\",count)\n max=count\n i+=1\n\n print(max)\n\nif __name__ == '__main__':\n main(57,9,1000)\n main(57,4,40000)\n main(57,4,39000 )\n\nI know the code fits but I always exceed the time for the validation page. I could translate to C or c++ language but I receive any suggestions for improve logic or performance\n\nI read it. I just suggest to think of another way to solve the problem. It is a mathematical question, not really a programming's one. (That kind of site is not good to teach programming).\n– Jarod42\n2023-11-17 16:07:13Z, License: CC BY-SA 4.0\n\nHow can I improve the performance?\ncode V.2\n def reverse_iteration(a, b, d):\n k = a // b # Start with the maximum possible value of k\n # print(k)\n max_repetition = 0\n\n\n while k > 0:\n total_cost = k * b\n bestresult = len(total_cost.__str__())\n\n if total_cost <= a:\n print(\"k:\", k, \"Total Cost:\", total_cost)\n # repetition = total_cost % b\n\n number_str = str(total_cost)\n count = 0\n last_digit = None\n\n for digit in reversed(number_str):\n if digit == str(d) and (digit == last_digit or last_digit is None):\n count += 1\n last_digit = digit\n else:\n break\n # print(count)\n if count > max_repetition:\n max_repetition = count\n\n if count == bestresult \\\n or (int(total_cost.__str__()[0])<d and max_repetition==bestresult-1):\n k=-1\n continue\n\n k -= 1\n\n print(max_repetition)\nif __name__ == '__main__':\n reverse_iteration(1000, 57, 9)\n reverse_iteration(1000, 57, 5)\n reverse_iteration(40000, 57, 4)\n reverse_iteration(39000, 57, 4)\n\ncode V.3 calculate relevant factor\ndef most_trailing_digits(a, b, d):\n\"\"\" Print the maximal amount of trailing digits \"trailing\"\n a bundle of doodads priced \"retail\" may have up to\n a bundle price of \"maximum\".\n\"\"\"\n k = a // b # Start with the maximum possible value of k\n print(\"max iterations\",k)\n\n max_repetition = 0\n result_with_max_repetition = None\n factors=[]\n reducer = []\n iterations=0\n #determine relevan factors\n for i in range(1, 11): # Iterar sobre los números del 1 al 10\n resultado = b * i\n if resultado % 10 == d: # Verificar si el último dígito es el buscado\n factors.append(i)\n print(\"factors\",factors)\n print(k * b)\n for i in factors:\n if i != k % 10:\n if k % 10 <i:\n reducer.append((k % 10) + 10 - i)\n else:\n reducer.append((k % 10) - i)\n else:\n reducer.append(0)\n\n #last conection\n if reducer[0]==0 and len(reducer)>1:\n reducer[0]=(factors[len(factors)-1] - factors[0])\n #single reducer\n if len(reducer)==1:\n k=k-reducer[0]\n reducer[0]=10\n\n print(\"reducer\",reducer)\n iteratorReducer=0\n while k > 0:\n iterations+=1\n # print(iterations)\n total_cost = k * b\n bestresult = len(total_cost.__str__())\n\n if total_cost <= a:\n print(\"k:\", k, \"Total Cost:\", total_cost)\n # repetition = total_cost % b\n\n number_str = str(total_cost)\n count = 0\n last_digit = None\n\n for digit in reversed(number_str):\n if digit == str(d) and (digit == last_digit or last_digit is None):\n count += 1\n last_digit = digit\n else:\n break\n # print(count)\n if count > max_repetition:\n max_repetition = count\n\n if count == bestresult \\\n or (int(total_cost.__str__()[0])<d and max_repetition==bestresult-1):\n k=-1\n continue\n\n iteratorReducer += 1\n currenreducer=0\n if len(reducer)==1:\n currenreducer=reducer[0]\n else:\n currenreducer=reducer[iteratorReducer % len(reducer)]\n\n k = k -currenreducer\n\n print(\"iterations\",iterations)\n print(max_repetition)\n\n## tests\nmost_trailing_digits(1000, 57, 9)\nmost_trailing_digits(1000, 57, 5)\nmost_trailing_digits(40000, 56, 4)\nmost_trailing_digits(39000, 57, 4)\n\n"
I'm looking for review and feedback on simple news website built using React, next.js, tailwind and nextui. I'd love to get your feedback on file naming conventions, project structure, ways I could improve the components. Any feedback would be greatly appreciated. https://github.com/sazr/next-js-news-site If you don't ...
I decided to create this project to put my JS skills to the test mostly, and it works well. It is a HTML and CSS editor that saves your code to localstorage and runs the code. On page load, it retrieves the localstorage saved code and runs it. The only minor issue is that the popup text that appears on hover of the sav...
I'm a newbye in React. I created some simple Components to practice. For now, I'm using class Component (I want learn either class COmponent or function COmponent). I would know if I projected properly my Components or if I could have a better setting: My little application allow to increment a number of 1 by default, ...
I am using a driver that retrieves data from HW (Driver) and a display (Viewer) that will output data to the user. The user calls a trigger function to initiate the getting of data from the Driver. The Driver's constructor accepts a "publish" callback function to be called when data is ready. The Viewer receives a "get...
Context I want to build a transposition table where the game states are binary square matrices which size MATRIX_SIZE is known at compile time. Rather than storing these matrices, I want to store their "hash". More precisely, I want to build a function that, upon being given such a matrix returns a unique identifier. M...
I'm working with a bunch of yaml files that are rather sloppy. This is outside of my control unfortunately, so I'm trying to clean up the data after the fact. My approach doesn't allow for nested structures yet, but I was wondering if this approach seems reasonable so far, if the code is readable, and if there are sugg...
This is a contrived example of a question that came up in code review the other day about memoizing context values in React. Let's say I have a hook which returns a memoized value of an expensive operation like so import { useMemo } from 'react' const ONE_MILLION = 1_000_000 const ZERO_TO_ONE_MILLION = Array(ONE_MILL...
I rewrote one of my Pandoc filters (initially written in Haskell, then Python) as a Lua Pandoc filter. I'd be happy to receive feedback on how this filter could be improved, especially in regards to best practices / clean code regarding Lua. I really dislike all the type calls in the Meta function. pathPrefixMetaName =...
.syntax unified .text .global __main .global function .thumb_func .equ RCC_BASE, 0x40021000 .equ RCC_APB2_ENR, 0x40021018 // STM32f103C8T6 - Adresse von RCC_APB2ENR - 0x18 .equ GPIOC_BASE, 0x40011000 // GPIOC-Basisadresse nach "memory-map", Datenblatt .equ GPIOC_CRH, 0x40011004 ...
Here are some utility bitwise functions for 64 bit integers. I have independently derived inv64 (inverse all bits) and pcnt64 (count bits set to 1) myself, though I am sure someone else has before, so this is nothing new. But ctz64 (count trailing zero bits) is a modified version of Count the consecutive zero bits (tra...
I just finished creating a Tic Tac Toe game in Javascript, but now am wondering if there are ways I could improve upon the code I've written for it. Mind the lack of CSS here. const cells = document.getElementsByClassName("cell"); const board = [ [0, 0, 0], [0, 0, 0], [0, 0, 0], ]; const players = ["X", "O"]; c...
I'm currently using the ReadDirectoryChangesW Function from the Windows API to build a Directory Watcher. The Watcher should monitor a folder for newly added files. For this i use the following code: class DirectoryWatcher { public: using Callback = std::function<void(const std::string&)>; DirectoryWatcher(const st...