instruction stringlengths 71 95.1k |
|---|
While submitting this question i found that someone already made up this question in python, here is my java implementation of the Perfect-Rectangle-Challange
challenge:
Given an array rectangles where rectangles[i] = [xi, yi, ai, bi] represents an axis-aligned rectangle. The bottom-left point of the rectangle is (xi,... |
I solved a Daily Coding Challenge, but i suspect my code could be optimised. The challenge is the following:
You are given an N by M matrix of 0s and 1s. Starting from the top left corner, how many ways are there to reach the
bottom right corner?
You can only move right and down. 0 represents an empty space while 1 rep... |
I am working on this code from 3 days from a website called Codechef, the code compiles, executes and even give correct results but my code is taking 1.01 sec, but the time limit for question is 1sec, I have tried various ways but neither of them is giving a result that can work within 1 sec.
The question is about fi... |
Goal
I'd like to understand if this current method, of loading data and inserting data into a database I currently use is to be avoided?
Code
I drafted a simple application that loads data and inserts data, simple as that.
Model
public class Person
{
public int PersonId { get; set; }
public string Firstname { g... |
I have a dictionary in Python (uglyDict) that has some really un-cool key names. I would like to rename them based on values from another dictionary (keyMapping). Here's an example of the dictionaries:
uglyDict = {
"ORDER_NUMBER": "6492",
"Ship To - Name": "J.B Brawls",
"Ship To - Address 1": "42 BAN ROAD",... |
I've written a program that gets the web API endpoint for some functions on a website. I'm just wondering if you guys see anything I could do to improve the code at all.
import sys
import requests
import dateutil
class KenoBase:
'''
Methods that are to be inherited to 'KenoAPI' class.
Do not use this class... |
This is a follow-up question for A recursive_transform template function for the binary operation cases in C++, A recursive_transform Template Function with Unwrap Level for Various Type Arbitrary Nested Iterable Implementation in C++, A recursive_transform Template Function Implementation with std::invocable Concept a... |
I am not an advanced user of Excel and am VERY new to VBA. My only programming experience is 2 C# classes in college. That being said, go easy on me ;)
I am working on a team that audits military bases for energy conservation projects. I am trying to revise a workbook that is currently used to document HVAC equipment i... |
use std::{cmp::max_by_key, collections::HashMap};
fn longest_common_subsequence(s1: Vec<u8>, s2: Vec<u8>) -> Vec<u8> {
struct Helper {
s1: Vec<u8>,
s2: Vec<u8>,
cache: HashMap<(usize, usize), Vec<u8>>,
}
impl Helper {
fn helper(&mut self, i: usize, j: usize) -> Vec<u8> {
... |
I am looking for suggestion to make my for loop iterate faster. With about 2000 rows of data. Below code is taking lot of time to run. So far I have followed various Stack Overflow answers. For example reducing db queries and using Bulk insert to improve EF performance. It just improved marginally.
List<VehicleApplicat... |
I have the following code to round a number down to the nearest non zero digit in a string, or if the digit is larger than 1 it would round to the second decimal place.
I have yet to find a way to do this without converting the number to a string and then using regex.
The end result of the number can be either a string... |
I am trying to solve Google Foobar challenge prepare-the-bunnies-escape using my own approach, instead of BFS. I attempt to solve two ends of the maze and try to connect them together. It works, but it exceeds Google's time limits. How can I optimize the program/algorithm to meet google standards?
Readme.txt
You have ... |
How would you go about designing a database for service appointment?
Here is what i came up with so far. Let me know if there is a better way.
Basically the admin should be able to build services list, work schedule. Based on this data Client should be able to make service appointment on specific days, hours.
CREATE TA... |
Following idea: There are three married couples and they have to be introduced another.
I have implemented this solution:
val couples = arrayOf(
arrayOf("Michael", "Sandy"),
arrayOf("Frank", "Claudia"),
arrayOf("Andrew", "Michelle")
)
for (i in 0 until couples.size) {
for (j in 0 until couples[0].size)... |
I attempted to implement a simple Gomoku game (connect 5) in pygame and wanted to get some help. So far, the basic features are working fine with 2 players going against each other.
Entire Code
import numpy as np
import pygame
import sys
import math
# initialize the pygame program
pygame.init()
# static variables
ROW... |
I'm reading on how to write proper testing suites here. So I'm trying to follow the selenium example in the docs which is in Java; I'm trying to translate it to Python since my app is written in Python.
So I translated the example like so:
class LoginPage(unittest.TestCase):
FE_URL = os.getenv('FE_URL')
SERVER_... |
Below is the Rabin Karp implementation. I am not so sure about it, and there is no where that I can check whether this code really works or not. It will most helpful for extra set of eyes if whether this gives correct output or not.
The code finds the substring (in code it is, pattern) from the string given (in code it... |
UPDATES:
I'm looking for an answer that can answer the questions listed in the post. Moreover, this answer will not only continue my way of thinking, but also give feedback based on it. It's just like a conversation.
For example: As to question 1.1. It's better to create andy_cfg to handle everything about andy.ini onl... |
I'm building a simple webpage that allow users to find the intersection of different category lists on a wiki (imslp.org) since the site itself does not offer this functionality. I have a simple HTML form that asks users to paste in two URLs and a PHP script that retrieves information from the two wiki pages and produc... |
This is a follow-up question for A recursive_transform template function for the binary operation cases in C++. Thanks for G. Sliepen's answer. Based on the mentioned suggestion, I am attempting to improve the extendibility of recursive_transform template function for the multiple parameters cases.
recursive_invoke_re... |
I want to create a database which gives an admin user ability to create schedule for other users to book from. This is second edition of this database schema.
I would like to know if there are any structure / logic issues with this schema. What would you change and why or if you see any potential problems regarding its... |
Playing around with the google API.
I have written demo applications to use the google gmail API. But what I am actually looking for is a review of the C++ wrappers for Authentication (OAuth2) and an initial GMail wrapper. Want input before I start going any further.
Please take your time to point out all even the slig... |
I am an experienced developer, but new to the react and the javascript world. I am trying to create a resizeable sidebar in react(Please see the full code and demo here) for a personal project. Although it seems to be working I am not sure if this is correct. Here is the main part of the code.
I would like some feedbac... |
I have been trying to optimize this:
const NUMBERS = [2, 2, 2, 2, 2, 4, 5, 5, 5, 5, 5, 5, 5, 5, 9];
const getMode = (arr) => arr
.sort(
(a, b) =>
arr.reduce((acu, cur) => (cur === a ? (acu += 1) : cur)) -
arr.reduce((acu, cur) => (cur === b ? (acu += 1) : cur))
)
.pop();
console.lo... |
I have a simple SDK in Python for internal use.
It's basically 150~200 lines of code of simple API calls wrapped around nicely that is comfortable for us to use.
It holds a few clients with methods (and each method wraps some API calls).
So a proper usage would be:
from datatube.datatube import Datatube
client = Datat... |
I have an application that subscribes to a topic in GCP and when there is some messages over there it downloads them and sends them to a queue on ActiveMQ.
In order to make this process fast I am using exeutorService and launching multiple threads for sending messages to active mq. since that the subscription is suppos... |
I am working on a basic Array rotate code for a Hacker Rank challenge. The code is complete and passes all test cases, except for 2 which it times out on. I was wondering if there is a way to make this code more efficient. Thank you in advance.
class Result {
/*
* Complete the 'rotLeft' function below.
*... |
I am processing a file as the following and closing it. Later, I do some more processing and get some ID that I want to append to all rows in the previous CSV generated. So all rows will have the same value.
My initial code of creating and appending data to csv:
private StringBuilder stringBuilder = new StringBuild... |
I was rejected after a tech screening for the following code.
I mainly struggled to make the code 'production ready'.
I was running out of time so I did not create a class for testing.
How could I have improved this code?
/*
Problem
Imagine you are building a friend locator app.
Given your current position identified o... |
I'm looking at improving my PHP knowledge and wondering if anybody has any tips on improving and optimising my function below?
<?php
function urlCheck($string = '')
{
$searches = array('one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirtee... |
Here is a minimal example of my task...
I have four 2-column files. profile1.data
zone luminosity
1 1 1359.019
2 2 1359.030
3 3 1359.009
4 4 1358.988
5 5 1358.969
6 6 1358.951
7 7 1358.934
8 8 1358.917
9 9 1358.899
10 10 1358.881
profile2.data
zone luminos... |
I have this piece of code which I'd like to improve:
std::optional<IntersectionInfo> Scene::intersects(const Ray& ray) const
{
float closest = std::numeric_limits<float>::max();
int index = -1;
int i = 0;
for(auto& sphere : _spheres)
{
auto [b, d] = Intersections::intersects(ray, sphere._sh... |
I have a code in vba that works well but it is slow so I am looking for a better solution to this code.
If there is any one who could help me I would be grateful!
Sub Formula()
Sheets("Result").Range("D2:D" & Cells(Rows.Count, 2).End(xlUp).Row).FormulaR1C1 = "=VLOOKUP(RC[-2],DATA!C[2]:C[86],3,FALSE)"
Sheets("Result... |
To put it in context, I had the assignment to do for a job interview in Node.JS, which basically making CRUD with products (and it have certain conditions).
The assignment was well-understandable, and I have succeeded to make this task.
After the company reviewed my code, I've got rejected because one of the main reaso... |
I have been learning Java for approximately 3 weeks now and made 2 posts on code review. Learned quite a lot from people and learned a lot of Java at the same time as well. I made this Age Calculator program to mainly practice with splitting up code into methods and classes as well as using method parameters and return... |
I am working on an API call in pure Javascript and I hit a section of code that i want to refractor The code is something like this
function getStart(city, lat, long, response) {
const latDir = lat[lat.length - 1];
const latVal = lat.slice(0, -1);
const latMinVal = latVal - 15 < 0 ? 0 : latVal - 15;
const latM... |
This is my implementation of itoa() (Integer to Alpha), which converts an integer to a string. Memory management and optimization is important. The caller is not responsible for allocation of the string.
The caller is responsible for freeing the string, as my implementation does not allow to call free(). The function h... |
So I'm currently trying to learn more about events using C# and the example that I just write seems a bit.. It seems a bit too much? I feel like you could accomplish the same thing with way less code. I just have a hard time seeing why an event in this case would be useful? Maybe I just did it wrong.
Is this a good way... |
# digit containing 9 has to be greater or equal in length
mul9 = { str(i): str(9-i) for i in range(10)}
print(f"{mul9}\n")
number1 = int(input("Enter 9s': "))
len1 = len(str(number1))
number2 = int(input(f"Enter (0 - {str(9)*len1}): "))
if len(str(number1)) < len(str(number2)):
print("This trick won't work")
... |
add9 = []
add9.append(int(input("Enter 1st 4-digit no.: ")))
print(f"The answer will be 2 and {str(add9[0])[0 :-1]} and {str(add9[0]-2)[-1]} = 2{add9[0]-2}")
add9.append(int(input("Enter 2nd 4-digit no.: ")))
add9.append(9999-add9[1])
print(f"The 3rd 4-digit is 9999 - {add9[1]}= {add9[2]}")
add9.append(int(input... |
I asked this on StackOverflow and was directed here...
Instead of including a debounce plugin library for a very small form section of my site, I've implemented some of David Walsh's JavaScript Debounce Function in my code to allow a small wait for slower user input, however I am binding it to the input field using jQu... |
Im currently working doing a webscrape which in my case if sydsvenskan but will be a template over time for other sites.
I have currently done:
from typing import Optional
import attr
import requests
from bs4 import BeautifulSoup
from loguru import logger
from requests import RequestException
from requests.exceptions ... |
I'm working on a programming exercise (university, nothing related to industry) which basically asks to implement a Buffer to be used by two threads (a producer and a consumer). The first one enqueues data calling next(T t), while the other gets the oldest value (in a FIFO mechanism) calling consume() or waits if the b... |
I am learning Python and managed to accomplish the above. But my script doesn't seem optimal. Could someone help to take a review and suggest for betterment?
import boto3
from datetime import datetime,timedelta
REGION = "ap-southeast-1"
retention_days = 45
account_id = boto3.client('sts').get_caller_identity().get('Ac... |
I am implementing a callback method to replace the use of generics.
For maximum performance, it is not allowed to use Box and I also don’t want to use dyn FnMut(T) -> Ret as that introduces vtable.
So I decided to write a non-owning ErasedFnPointer that stores the function pointer and the pointer to the struct if the f... |
I have service class which loads data from external service. This service needs API key which loads from db and unique for every user.
public class GoogleCloudService
{
private readonly ILogger<GoogleCloudService> logger;
public GoogleCloudService(string key)
{
Key = key;
logger = Startup.S... |
I have a 3-D array in numpy, of dimensions 3000 x 2000 x 8
I need to modify the cells of the array so that each cell will contain the sum of all cells above and left of it, inclusive the current cell.
I am doing it using loops like below, but it is taking around 5 minutes to complete the program run. Is there a faster ... |
In my database, I have table wp_postmeta, example:
| meta_key | meta_value | post_id |
---------------------------------
points | 12 | 23
points | 2 | 18
lorem | ipsum | 92
points | 8 | 15
I want to order points by meta_value and get the row number of a specific p... |
print("This trick only works for range 10 to 199 included")
num1 = int(input("Enter 1st no.:"))
num2 = int(input("Enter 2nd no.:"))
max1 = max(num1, num2)
min1 = min(num1, num2 )
cond = (min1 > 9) and (max1 < 200)
def print2(res1, res2):
res3 = num1+num2-100
res4 = (num1-100) * (num2 -100)
print(f"""
... |
I have many stacks with the same navigation options. How do I abstract the navigationOptions part to have it repeat in all my stacks?
export const MakePaymentStack = createStackNavigator(
{
PaymentsBpayNewScreen,
PaymentsBpayNewAmountScreen,
},
{
...defaultNavStyle,
initialRouteName: APP_SCREENS.... |
Problem Statement
I need to access a deeply nested object. I could've used a 3rd party util such as Lodash but insisted myself on writing a Vanilla JS solution with a recursive strategy.
Code
Can this solution be improved with a better and more efficient approach? Is there any edge case which has been missed and could ... |
I created this short method:
private Item createItemType(final Integer type) {
if(type == null) {
return null;
}else if (type == 0) {
return Item.PLACE;
} else if (type == 7) {
return Item.ADDRESS;
}
return null;
}
Logically it is correct, but I want to know if there is a be... |
This is a hangman game. The only word is 'word' and I am not planning on changing this since I am not going to publish this game or anything.
If there is any unnecessary/bad code I need to get rid of, please tell me.
Here is my code:
using System;
using System.Threading;
namespace Hangman
{
class Program
{
... |
I'm trying to do a non equi self join with basic python libraries on a table that has 1.7 millions rows and 4 variables. the data look like this:
product position_min position_max count_pos
A.16 167804 167870 20
A.18 167804 167838 15
A.15 ... |
I have been attempting to implement a function calculating values of the sine function.
I know that there are several similar threads regarding this topic but my goal was to try
to implement such function in my own way as an excercise. I suppose that the argument will be in range \$\left<-2\pi\, +2\pi\right>\$.
In the ... |
I started learning MVVM and API data fetching, so I made this code:
Function loadDirector in which directorName value is modified with fetched data:
func loadDirector(id: Int, completed: @escaping () -> ()) {
homeRepository.getDirector(id: id){ (creditReponse) -> (Void) in
self.directorName = ""
cre... |
I'm making images. My steps are:
create PGM files using a C program
convert/resize PGM to PNG using Image Magic
remove (big) PGM files
To do it I use Make and a Bash script.
The Makefile is very simple:
all:
chmod +x d.sh
./d.sh
Most things are done by the script:
#!/bin/bash
# script file for BASH
# wh... |
Problem
I would like to make an efficient, extensible, and potentially asynchronous parallelizable event system using modern features in C++20.
My solution
I've constructed a templated event struct by category and group:
#include <algorithm>
#include <execution>
#include <functional>
#include <vector>
namespace Syste... |
I was trying to make a simple noise visualizer using the noise, pygame and pygame_gui libraries. I wanted it to have UI features like buttons, drop down menus, sliders, etc. And the pygame_gui library is perfect for this.
The code is clearly not very clean, so any suggestions are well appreciated.
noise_visualizer.py
f... |
This is something I made as an input display resembling NohBoard because I need to make a video for a video game, but it's on Linux which doesn't have any good input display programs. One thing I'm worried about is the way I'm making the scroll wheel flash last for exactly three frames in a 60 FPS recording. I checked ... |
Imagine we have a function that returns a Promise, ie call a GET endpoint of an api and return the response data.
function testFn() {
return fetch('http://localhost/ep')
}
The response will remain valid for some unknown period of time but may need to be refetched later. Basically anytime somebody needs it, it needs... |
I used uniform crossover to solve eight queens problem. It is taking more than an hour to get the result. Is there any way to reduce the running time or improve the crossover to solve eight queens problem? Following is the code:
import random
import numpy as np
from math import gamma as G
def random_chromosome(size): ... |
I'm trying to scrape arrival data from Flight Radar 24
My script takes extremely long time to scrape the data. Is there any way I can speed up the scraping process?
Here's my script:
import time
from selenium import webdriver
from bs4 import BeautifulSoup
from urllib.parse import urljoin
from selenium.webdriver.chrome.... |
This code is from my blog project. This project is almost done. This is working well.
I can create new posts and update and display all saved posts.
const express = require("express");
const router = express.Router();
const Article = require("../models/BlogPost.model");
router.get("/", (req, res) => {
res.redirect... |
I am currently writing a chess engine to improve my C++. I was able to improve my first results in terms of performance. (It is still really weak, but it does not lose a queen in one move)
I ended up having massive problems regarding namespaces in move generation.
It is really not great.
Here is some code:
#pragma once... |
basically i am new to python lookin for any bad practices done down there in my script, any ways to shrink the code and increase efficiency
import json, os, win32crypt, shutil, sqlite3
from Crypto.Cipher import AES
tmp = os.getenv('TEMP')
usa = os.environ['USERPROFILE']
triple = False
both = False
edb = usa + os.sep ... |
I am experimenting with asio web sockets and tried to write a simple serializer / deserializer.
I am also thinking about an approach on how to serialize some type information alongside the actual data. This way a dont have to worry about that i might choose the wrong type when deserializing.
// serialize.hpp
template<... |
I'm currently learning Python for a masters and am trying to improve the best I can, as I'll need to know how to code in my future career.
I currently have a function that builds a table from a dictionary, no matter how long the characters of either the keys or values are.
However, I'm trying to get better and I'm sure... |
I am a junior web developer currently doing my first internship and I had a lot of freedom to solve small problems the way I thought was best. (There aren't really any developers here so I am completely on my own).
My solution worked and is no longer needed, but I really want to improve and become a better programmer, ... |
My goal is to look for nearest neighbours in a Boolean-assigned mapping (a Python dictionary). For this purpose I'm looping through the candidates, starting from those with the closest distance. The code will exit the loop once it finds a neighbour that meets additional criteria. My question here is for best practices ... |
I'm doing some research on Nearest Neighbor Search of quantization, where running speed is very important. As I've just started using Python, I wonder if the following code for multi-processes can be further optimized to obtain faster running speed.
import numpy as np
from joblib import Parallel, delayed
def search_ne... |
I recently started programming and ran into a problem in the battle algorithm. This piece of code checks if there is someone in the position of the main character. If there is, then the battle begins (action() function). If several enemies are in the same position, then the battle will go on until all the enemies in th... |
I made a Tkinter MP3 Player with Pygame and am looking for tips to improve. Explanation offered in comments in code, but it generally works by getting all the files in a folder. (Have censored filepaths for privacy.)
import os
import glob
import shutil
import pygame
import tkinter as tk
from pytube import YouTube
impor... |
This function is about the fact that a std::wstring was used in another cpp file in order to be able to read strings with German umlauts from the console. Since it is difficult to get wstrings into a text file when a std::ofstream is already accessing the text file, this wstring was converted into a normal std::string ... |
I'm trying to learn how to write code well in Python. I've been tinkering with a function that will return a list of all prime numbers between the two parameters. This is the best I could come up with considering my limited experience.
Do you have any ideas of how this code can be improved to become more Pythonic? (Whi... |
I'm attempting to import an external script into an HTML file. The name of the js file that I want to import is hosted in a SQL database. Therefore, I am using a XMLHttpRequest to access the SQL database so that I can fetch the appropriate name of the script. I then create a script element where I set src equal to 'thi... |
I have invented the fastest string search algorithm. Can someone prove that it is not fastest?
I am not considering worst case scenarios.
The algorithm can be found here: https://sourceforge.net/projects/fastest-string-search-algo/files/
/*
* Choudhary algorithm
*/
public static int choudharyStringSe... |
How can I improve efficiency/readability of the following code?
It can be seen that the number, 125874, and its double, 251748, contain exactly the same digits, but in a different order.
Find the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and 6x, contain the same digits.
https://projecteuler.net/problem=... |
Here is some php code which i think is optimized but still want to optimize it more but not sure how to do it.
<?php
$result = curl_exec($ch); // here i get a json response from a curl.
$result = json_decode($result, TRUE);
$result = arrangeData($result, $app, $currentSite);
$app->exit($result);
function arrangeData... |
Below is my attempt at the challenge found here. The challenge is "Find a build order given a list of projects and dependencies." Already given are the classes Node and Graph (which I can add if anyone needs them to help review my code), and also
class Dependency(object):
def __init__(self, node_key_before, node_k... |
A simple implementation of the Observer pattern in rust. The Observable constructor (::new) is called with a subscription function which will be called every time an observer subscribes.
The subscription function must return a cleanup function which is defined by the using code.
An observer subscribed to the Observable... |
So I decided to implement a basic event system in JavaScript.
My goal was to support the following functions:
on - allows the user to register a handler on the event system that fires until it's removed.
once - same as above, but only fires the first time, then removes itself.
emit - creates an event and fires all rele... |
I have a comparison function for comparing two points in 2 (or more) dimensions based on the angle of each point in standard polar coordinates. In other words, a point a should compare less than a point b if the angle through the origin from the +x axis to a is less than the corresponding angle for b. For the origin,... |
So, I wrote this function to sort three numbers in Julia. Any feedback on readability, performance, and Julian-ness would be appreciated.
function sort_asc(a, b, c)
# defined in function so as not to overwrite Base.minmax
minmax(x, y) = ifelse(x < y, (x, y), (y, x))
l1, h1 = minmax(a, b)
lo, h2 = minma... |
This is a follow-up question for Tests for the operators of image template class in C++ and A recursive_transform template function for the multiple parameters cases in C++. I appreciated G. Sliepen's answer. I am attempting to extend the mentioned element-wise operations in TinyDIP::Image image class. In other words, ... |
I have a macro I have been using to generate daily fantasy (dfs) lineups for soccer matches. I would like to know where I can speed up my code so I can run more simulations.
Briefly, I have a worksheet in which I try to 'simulate' individual scores for each player in a match (e.g. "ITAvENG" in the code below). This use... |
Before start, I'd like to give some context.
A couple of years ago I implemented an autocompletion function for one particular case: querying all hosts from database.
It has a couple of flows. One of the most - rewriting and losing original completion.
That's why after some evenings I've implemented the new approach. N... |
ArchiveInputStream is from apache-commons compress. it is an InputStream. nextEntry is the only method for traversing the stream i've found the while loop is IDE converted from apache docs.
fun ArchiveInputStream.forEachEntry(doThis: (ArchiveEntry) -> Unit) {
var e: ArchiveEntry?
while (this.nextEntry.also { e... |
Very simple question. Imagine are designing library API, where you want to provide way to switch boolean flag. Typically to disable or enable a functionality. For argument's sake, let's say it's enabling/disabling sounds and I will be using kotlin in my code samples, but language doesn't really matter. I see 2 ways to ... |
I have the python script that creates a sqlite database and fills it with data (originally coming from a json file). At the time I execute the code below, my word table has about 400 000 entries.
con = sqlite3.connect("words.db")
cur = con.cursor()
form_of_words_to_add: "list[tuple(int, str)]" = []
# other code fills t... |
To divide 9 persons into 3 groups, when the ordering of groups is not important can be done in
(9C3 * 6C3 * 3C3) / (3!) = 280 ways
Here, we divide by (3!) because the ordering of 3 groups is not important
What I did?
Gather all the permutations from the given array.
While grouping the combinations, discard the hands t... |
I'm going to start out by saying this is the 1st python program I have ever written and have no real background in the language so my code is probably pretty rough. Take it easy on me!
When I wrote this it works fine for a small number of tickers but when I have a file with 6k+ it is very slow. Now I know there are oth... |
I'm coding this program that allows you to encrypt files using vernam cipher in C language. I would be glad if you could inspect my code and tell me if I can make some improvements to it or if there are any error.
The request they gave me is:
The goal is to develop a simple application that allows you to encrypt files... |
I try to solve some old Codeforces questions. The problem is;
Petya once wrote a sad love song and shared it to Vasya. The song is a
string consisting of lowercase English letters. Vasya made up q
questions about this song. Each question is about a subsegment of the
song starting from the l-th letter to the r-th lette... |
I've been grinding some Leetcode for an interview coming up and just completed Square Spiral in Javascript.
Looking for feedback on performance. This ranked faster than 58% of submissions, would there be anyway to increase the speed using a similar implementation to what I have here?
let matrix = [
[1, 2, 3, 4, 5],... |
I'm working on a simple Leaky Bucket algorithm.
I have found a lot of samples on the internet, but something always bothers me.
Most of them use Collections and DateTime to track current actions and calculate the time of a Delay.
So, I try a controversial (according to my co-workers) implementation, using 2 semaphores ... |
I am computing pairwise Euclidean distances for 3-D vectors representing particle positions in a periodic system. The minimum image convention is applied for each periodic boundary such that a particle only considers the nearest image of another particle when computing the distance.
This code is part of a larger post-p... |
<!DOCTYPE html> <!--Declare the doctype as the html standard of HTML 5-->
<html lang="en-us"> <!--Lang Attribute to declare the language of a webpage-->
<head> <!--Every html doc needs a head which contains important information for viewing the code on different devices.-->
<meta charset="UTF-8"> <!--The... |
Here is the improved code
#include <iostream>
#include <sstream>
#include <string>
#include <random>
#include <vector>
#include <iomanip>
enum class ending
{
win ,
lose ,
tie
};
enum class States
{
Human ,
robot ,
blank
};
enum class command
{
deletE ,
move
};
class BOARD {
publi... |
I solved problem 58 in Project Euler and I am happy with my solution. However, are there any areas where I can improve my code here as I am learning how to write good python code.
Prompt:
Starting with 1 and spiralling anticlockwise in the following way, a
square spiral with side length 7 is formed.
37 36 35 34 33 32 ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.