instruction stringlengths 71 95.1k |
|---|
The following algorithm attempts to randomly generate a set of size M from an array of size N. It is not based on Knuth Fisher Yates shuffle, but could someone verify its correctness?
import random
def random_m(arr, m):
if len(arr) <= m:
return arr
for i in range(m):
rand = random.randint(i, l... |
I've been grappling with Unity's architecture for the last few days, trying to work around the fact that you can't use constructors for your MonoBehaviours (and by extension, you can't easily configure components before Awake if you create them programmatically). I've got a pattern now that I'm fairly happy with, but b... |
I'm currently working on some SQL code within Oracle Fusion BIP but it's not very optimised as it's using multiple LEFT,RIGHT and FULL OUTER joins to link tables together.
Unfortunately this is making the query timeout as there's roughly 80k lines and this will be the norm over a rolling 12 month period give or take a ... |
I made up a quick and dirty implementation of the G-Set in C#. I was hoping for some feedback on my approach. I'm not totally happy with having the payload public but I can't see that I'm gaining much by making it private either.
public class GrowOnlySet<T>
{
public HashSet<T> payload {get; private set;}
pu... |
I have a list of utterances(strings)/corpus as the follows,
List<string> allUtterances = new List<string>
{
"c2's are above the hierarchy than c1's",
"c2's are better than c1's",
"get me a group of 10 c1's",
"he is a c2",
"he was a c two",
"hey i am a c1",
"jdsaxkjhasx",
"khndsmcsdfcs",
... |
My goal was to create a single-line function that produces a deep copy of a javascript object.
Requirements:
Executable on a single line without the use of semicolons (exception: last character of the line)
Nested objects should not be references to the originals
Function:
let copiedObjct = (copy = (obj) => (Object.k... |
I accomplished the following task to practice allocating on the heap.
reading words from stdin
sorting them in lexicographical order
printing the sorted words to stdout
To accomplish this is allocate the size of each word and the count of words.
I would like to hear any suggestions for improvements. Is there maybe an... |
I am relatively new to machine learning and I believe one of the best ways for me to get the intuition behind most algorithms is to write them from scratch before using tons of external libraries.
This classifier I wrote seems to be yielding reasonable results based on the dataset I provided. This dataset is based on t... |
As some of you may know, part of creating, or leveling up a character in almost any game is ability score increases. In this example, the character has six abilities with preassigned scores: strength, dexterity, intelligence, wisdom, charisma, and constitution. Users of the code have the option of choosing to level up ... |
I am creating a C++ header-only library for FlagSet.
A FlagSet is a container for booleans with meaning. Usually, it is done with constants (macro, enums, whatever), for example :
//from SDL2
#define SDL_INIT_AUDIO 0x00000010u
#define SDL_INIT_VIDEO 0x00000020u
#define SDL_INIT_EVENTS 0X00000... |
So I have implemented an application that acts as a chatbot for telegram in C#. I use a library that allows to set a filter of updates that the application whishes to receive. I assume the filter makes it more performant. This filter is passed in the StartReceiving method. My bot consists of multiple modules and each o... |
Needed to get a local serial port list. System.IO.Ports.SerialPort.GetPortNames() returns names but not the descriptions like you can see in Device Manager: COM6 vs. USB Serial Port (COM6)…
There is also no way to subscribe to plug-and-play port list changes.
Here comes the solution. Repository at GitHub.
To consume th... |
I have this at the moment, wondering if there's a cleaner way to do it or if this is already as compact as it gets.
h = "%s" % str(h) if h >= 10 else "0%s" % str(h)
m = "%s" % str(m) if m >= 10 else "0%s" % str(m)
s = "%s" % str(s) if s >= 10 else "0%s" % str(s)
print("{}:{}:{}".format(h, m, s))
|
I've made a program that works, but i want to make it reusable. This code reads in a dictionary object created in another class (that i made), as well as read in a text file to put in said dictionary object. The code then loads in another text file, compares it with the dictionary, updates its frequency values and outp... |
After seeing a lot of Sudoku solvers on Code Review I decided to implement my own.
My implementation aims to be very fast and flexible, supporting some Sudoku variations (irregular boxes, extra unique areas...)
I structured the code in three main classes, that are:
Cell
SudokuBoard
SudokuSolver
There is also a struct... |
I am building a simple calendar with recurring events.
CalendarEvent.php
id
start_date
CalendarRecurringPattern.php
parent_id
pattern_type // daily, weekly, monthly, yearly ...
Using pattern_type i build each following occurrence starting from start_date, using a recursive function and Carbon::class. What bugs me is ... |
I was following this tutorial from official python documentation site, but found its examples quite simplistic, so I've built my own wrapper.
It does what I intend it to do, but I wonder if this code is good or how it can be improved.
app.h
#pragma once
#include <iostream>
#include <string>
#include <Python.h>
clas... |
I have a solution but it feels bloated and unclean. How can I clean it up? The second for loop especially does not feel right.
I'm trying to calculate the opening hours but where we only use the highest opening time and the lowest closing time in a time-block. I will show you an example to clarify it.
If we have two ti... |
I'm trying to come up with a more elegant solution for a loop in months that I wrote long time ago in C# 1.1
I use a helper class Month but I'd prefer to get rid of it and make the code shorter and more readable.
I receive a start period in format yyyy-mm and end period yyyy-mm and I need to execute something for e... |
I have a type that returns a result based on some logic. The result contains a message. Should a good unit test check that the message is correct?
A negligible amount has changed as I'm not allowed to post IP:
class MyFilter
{
private readonly int _state;
public Result FilterResult { get; private set; }
p... |
In this android app, the user can enter (a subset of) roll20 notation to roll that many dice. Inputs will look like "4d6" at the simplest, but the user can also add or subtract numbers, and drop or keep the highest or lowest dice. I have implemented a class to do this parsing, with public methods for the resultant nu... |
Task: I'm importing a .CSV files as a pandas dataframes. I'm writing one column of that dataframe to a .txt file. Importantly, each row of the column must only be written as one row in the text file, never more (hence stripping /n)!
I have a very large dataframe (2 million rows), and this loop is naturally very slow gi... |
I want to use SOLID more and more but still learning, I'm improving a PPT generator and would like your help applying SOLID principles in it.
That generator should print two photos per slide, first one to the left, second to the right;
If the last photo is a left photo, it should be placed in center;
Each photo has ... |
I have a project that uses Caliburn.Micro to implement the MVVM pattern. For IoC, I am using MEF. All the ViewModels are marked with attribute [Export(typeof(IScreen))]. IScreen is defined in Caliburn.Micro.
In my BootStrapper file I have set up MEF like so:
private CompositionContainer container;
protected override v... |
I have an input text file which contains distance between 2 cities shown below
Luebeck Hamburg 63
Hamburg Bremen 116
Hamburg Hannover 153
Hamburg Berlin 291
Bremen Hannover 132
Bremen Dortmund 234
Hannover Magdeburg 148
Hannover Kassel 165
Magdeburg Berlin 166
Berlin Dresden 204
Dresden Leipzig 119
Leipzig Magdeburg 12... |
I'm new to node and web scraping in general but with some research I've written this working code.
My goal is to get all questions from X Stack Overflow's pages sorted by most rated and save that data locally to use on another project to plot charts and other analytical stuff.
How can I improve it in both readability... |
I did write it to have a solution for my problem. But I don't know if my code is ok. Can you please check it?
Problem:
I want to include all my Java files from all my projects (created with Netbeans), the projects are stored in one folder, into a LaTeX document. I solved it with this code:
package dir;
import java.io.... |
I know that this is an impossible task against someone determined, but I'd like to keep mid-average users from being able to open more than one copy of my program at a time.
Here's the quick code I've made:
const tmp = require('tmp'),
fs = require('fs'),
path = require('path');
// Randomly generated, constant ... |
I made 3 versions of a counting-up timer in JavaScript:
Version #1
All units of time (seconds, minutes, hours, and days) are updated every second, whether they change or not.
Pro: Shorter code.
Con: Worse performance than version #2.
const timeIntervals = [
["day", 86400],
["hour", 3600],
["minute", 60],
... |
I am attempting to add a property to access the query string elements on the window and am looking for feedback on this implementation.
if (!window.location.hasOwnProperty("query"))
Object.defineProperty(window.location, "query", {
get(){
var query = document.location.search.substr(1);
if (qu... |
I completed two intro computer science courses on the basics of Java programming and data structures in university, and have continued to study programming on my own over the past few months.
This is my first attempt at programming a playable game. It was written in Java 8 using the MVC design pattern, and contains dif... |
I have a script for parsing BAM files. The script's input thus is lines like
E00489:44:HNNVYCCXX:3:1101:24890:5616 99 22 16052014 150M
E00489:44:HNNVYCCXX:1:1110:21704:27345 99 22 16052044 150M
E00489:44:HNNVYCCXX:1:1217:2372:69519 163 22 16052044 150M
E00489:44:HN... |
I come from a C background and have now just begun C++.
This also means that I am not focussing on the algorithm, but more on C++ idioms.
Description:
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3... |
I have a method to get the time parameter, is this code neat, can the return parameter use other data structures?
private Map<String, Object> getTimeCondition(long smallDaysToSubtract, long bigDaysToSubtract) {
DateTimeFormatter format = DateTimeFormatter.ofPattern(DateUtil.yyyy_MM_dd);
ZoneId zoneId = ZoneId.... |
I have an asynchronous controller.
It is supposed to make a couple async calls then return combined data from then as one DTO.
[HttpGet("[action]/{name}")]
public async Task<CombinedDTO> GetSummonerData(string name)
{
SummonerEndPoint endPoint = new SummonerEndPoint();
SummonerDTO summonerData= await endPoint... |
Nowadays I am learning Domain Driven Design intensively. I am reading the book called Domain Driven Design by Eric Evans, and at the same time I try to apply the knowledge on a real life project I work on recently.
My domain is the following: The web-app I am developing is responsible for tracking containers. These con... |
I am creating a Java Swing Application which deals with Geographic and Stellar data and I need a solid framework on which I can build (now) and extend (in future) any functionality I wish to. I am aware of the MVC (traditional), MVP or MVVM design patterns typically used by people. However, I ended up creating someth... |
Here's my method used for parsing a ByteArray into multiple frames of CAN interface. It works now correctly but it's somewhat ugly in my opinion.
It's written in Kotlin with use of RxJava2
private fun parseCanFrameBytes(frame: ByteArray): Observable<CanFrame> {
return Observable.create { emitter ->
var inde... |
I use this code to change the identity coming from Azure AD in an identity usable by my application, then i generate a token for this identity and return it in the response headers.
Is this secure? and is it the good way? In particular, call the SignIn method of the AuthenticationManager and handle this in a middlewar... |
I am a beginner in Python, I want to know if this code can be improved. Is it possible to make it work without the if/else?
number1=int(input('Enter first number: '))
number2=int(input('Enter Second number: '))
operation=input("Enter operation\n[+,-,*,/]")
if operation == '+':
sum=number1+number2
elif operation == ... |
I have been reading up on file uploads in Laravel, reading through the documentation and looking at best practices. In my application, I have two instances: an upload area for single files, and an area for uploading multiple files.
The singular one allows users to enter their own file name whereas the multi file upload... |
I am needing to generate unique id's for users. The 'unique' part is the problem for me.
The 13 character id's which have a format of the following:
0 + random int with range of 1-9 + random letter + random 3 digit number + string 98XX001 For example: 04X90398XX001 --> (0) (4) (X) (903) (98XX001)
This is the code I cu... |
I had to do a lot of IO stuff on my server running Node JS where I did not really care about the result of the operations. The list of incoming tasks could be huge, so I had to limit the number of tasks that could run at the same time. I try to avoid third party libraries wherever I can, so I made my own method.
It see... |
I have the following code to create a table for overall percentages and the past 30 day percentages. I would like to add this to a Shiny app I'm making, but I feel there is a simpler or shorter way to create this code/table than what I have, which would work better in Shiny. I'm not asking for the Shiny code, just a ... |
This is an abbreviated version of a serial receiver that can be started and stopped like a resource. The idea is that a thread will listen to an InputStream and dispatch received data to registered listeners. Effectively this converts a pull-style InputStream to push-style CommunicationListener (own interface). While i... |
Given an unsorted array. The task is to find all the star and super
star elements in the array. Star are those elements which are strictly
greater than all the elements on its right side. Super star are those
elements which are strictly greater than all the elements on its left
and right side.
Note: Assume fir... |
I have a few of hobbies, one is reading science fiction and fantasy and another is coding solutions. I thought I might have a chance to combine both hobbies on this project.
I have well over 1500 Science Fiction and Fantasy books that I have accumulated over the years. Some of them are signed by the authors. Most of t... |
I have a single controller that has two methods. One generates a PDF preview [GeneratePDFPreview] and then ultimately an actual PDF document [GeneratePDF]. It uses the Rotativa library to generate the PDF via partial views. I feel like I'm repeating myself majorly with the case statements on both methods.
The reason f... |
I made a function to generate a list of prime numbers using list comprehensions. Here it is:
let primes n = [x, x <- [2..n], length [y, y <- [2..x-1], mod x y == 0] == 0]
Is this a good approach? I am sure that there are much better ways of approaching this.
|
I implemented the following excercise:
Implement a lookup table with operations such as find(struct table*, const char*), insert(struct table*, const char*,int), and remove(struct table*, const char*). The representation of the table could be an array of a struct pair or a pair of arrays (const char*[] and int*); you ... |
Here is code to parse an IPv6 address.
An IPv6 address is 128 bits long.
When represented in its printable form, its hextets (1 hextet == 16 bits) are represented as hexadecimal numbers, and are separated by columns.
For example
fe80:0000:0000:0000:8657:e6fe:08d5:5325
Note that for each hextet, the left-most 0s can b... |
In the Calculator worksheet of my spreadsheet, for any appliance type present in a building being studied, users enter a quantity. There are 18 different appliance types, and users can enter different quantities of any or all appliance types.
On the Calculator sheet they can see a breakdown of energy use per individual... |
I have some code that is loading passwords from AWS SSM and then using them through the script. I am really concerned that some funky password character is going to be used that is going to get interpreted/escaped/munged by bash. The code in question is below. Are there any obvious problems here? Can I improve this so ... |
Description:
Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
Note: A leaf is a node with no children.
Leetcode
Code:
class Solution {
public int minDepth(TreeNode root) {
if (root == null) return ... |
This code was reworked and repostet in Console based Vocabulary Trainer Version 2
I wrote a console based Vocabulary Trainer to practice C++.
Its possible to add and remove vocabulary and practice it with it.
I save and read the vocabulary from a file to be able to read it.
Also certain settings like target and source... |
Consider the following typical probability scenario:
I defined this function to handle that scenario, I'm curious if Python has a more efficient method to handle this, or if this is the best way:
from scipy.special import binom
def grade_of_service(n, p, c):
prob = 0
k = c + 1
while k <= n:
prob +... |
I need a collection view to page through cells and center it like the App Store, where a portion of the previous and next cells look like this:
The native isPagingEnabled flag would be great if it had an option to center on the cell. However, making the cell span the full width of the collection view doesn't show prev... |
This code is part of a simulation and inputs will be positive values less than one and inputs are constrained elsewhere. The goal of the algorithm is to scale the inputs up to much larger numbers, although the total sum is bounded. These represent the number of entities in the simulation.
Conceptually it is best to rem... |
I've been teaching myself python and I decided to make a Simon copy. Please let me know if there's anything notable that I should improve on. I understand my use of globals in some functions is considered poor, but I couldn't think of any other way to write them. Thank you for reading
import pygame
from random import r... |
I have created a Synchronizer, the purpose of which is to read data from an XML source file and store the result in a DB.
I have different source types, for example Student.XML, School.XML, etc. These files are copied in my source directory, C:\Source.
My Synchronizer watches the Source folder, and every time there is ... |
I have an IEnumerable of a view model that I need to convert to CSV and send back as a file response. I have written it out quite manually and I'm just seeking code review and suggestions on a more elegant solution, or alternatively if this looks acceptable, confirmation of that:
public ActionResult ExportBasicRead... |
I have three arrays, each of which contains only numbers. Given a target number, I need to return the number of ways I can make that sum, using exactly one number from each of the arrays.
For example: If I have 2 arrays [[1,2,3], [1,2,3]] and the target sum is 4, I must return the number of combinations that will sum t... |
I'm using Google Drive API for uploading large disk image files ( >100 GB). My Code uses this wrapper to upload these large files in chunks of 40mb. The files are stored on NAS drive.
The code works fine, however I'm losing a lot of performance due to the fact that each chunk has to be downloaded from the drive, before... |
I built this 4 classes where the Main is the one responsible for setting and getting the variables. I am using PHP7.1. Please let me know on how to make this more amazing or maybe using trait. How does my classes look? Is it professionally made? what do you guys think? thank you very much!
<?php
class Main
{
// Pa... |
I receive messages from a MessageWebSocket connection frequently, which are compressed with zlib. The following code decompresses them to a stream which can be read with JSON.Net's JsonReader.
I'm pretty sure there are some improvements to be done, but can't quite put my finger on what:
private MemoryStream _compressed... |
I have a UIViewController holding one UITableView with 3 sections. Also this UIViewController implements UISearchResultsUpdating for searching in that UITableView. The UIViewController looks like this:
class MyViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UISearchResultsUpdating {
... |
I'm refreshing some of my datastructures. I saw this as the perfect opportunity to get some feedback on my code.
I'm interested in:
Algorithm wise:
Is my implementation correct? (The tests say so)
Can it be sped up?
Comparing my code to the one in the heapq module, it seems that they do not provide a heapq class, but ... |
Suppose you just want to set border radius for different controls:
Button
TextBox
ComboBox
The most frequent approach I usually find is totally override default template like in answers
https://stackoverflow.com/a/4779905/1548895
https://stackoverflow.com/a/6746271/1548895
https://stackoverflow.com/a/17681374/154889... |
I'm new at this and need assistance with shortening/streamlining the 2 pieces of code that is repeated three times each (this is a shortened version as these pieces of code is repeated many more times).
Sub CreateWordDocTest()
Dim wApp As Word.Application
Dim wDoc As Word.Document
Dim myStoryRange As Word.Range
Dim In... |
I am looking to simplify this code as it is to bulky for what it is doing. I do not need to stick to jQuery.
Simple checkbox in html relates to adding underline to some text:
$("#houseOrCar").on("change", function () {
if ($(this).is(":checked") ) {
$("#houseChosen").css("text-decoration", "none");
... |
I'm working on a large VBA project for work (around 1000+ lines of vba code) This module is called within another module where I disable everything possible like screen updating, events and setting calculation to manual to improve speed, yet this still seems to run slowly when I'm working with sheets with over 60,000 r... |
Each day I receive a CSV that contains data concerning a patient record and a related appointment record, each on the same row of the CSV. My code is designed to:
Parse the entered CSV for two separate but related records per row
Validate some data (email)
Generate some data (duration)
Insert the patient record - this... |
I've managed to create a function that checks whether arrays 'a' and 'b' can 'swap' corresponding values to 'increase' - e.g.:
var a = [1,2,3,4,5] // is increasing
var a = [1,4,6,7,36] // is increasing
var a = [1,6,3,6,5] // not increasing
Some successful tests:
increaser([5,3,7,7],[1,6,6,9]) - should return 2; a = [1... |
I think this is a good solution to finding the largest numeric palindrome that can be formed from the product of two 3-digit numbers... But it seems like there are some improvements that we could make which I haven't thought of...
Given int inputs[899] which is initialized by: iota(begin(inputs), end(inputs), 100), Do ... |
I will write code for all scheduling algorithm in future that is why scheduling.h will contain common data members and member functions. Please help me to improve and optimise this code.
scheduling.h
#ifndef SCHEDULING_H_
#define SCHEDULING_H_
#include <vector>
typedef unsigned int uint;
class Scheduling
{
uint ... |
This is my first time posting so hopefully I manage to get my question across in a clear and concise manner. I'm not sure this is the right place but someone on StackOverflow suggested I ask here.
I am running a cross-validation experiment which involves training a model on a subset of a data set and then validating it... |
Introduction
I implemented a restricted version of the sorting algorithm, the one that works only with unsigned integers. I wanted to try using std::stable_partition with bitmask, as I chose base 2. The reason partition works here is because there are only two "bins", thus it is somewhat like partitioning. I mandated c... |
I'm dealing with design layers of an application. Basically what I've so far are:
Business
Architecture: Client-Server
Techonologies: PHP+MySQL, HTML5, JS, 3rd parties APIs
My app
Data Sources: MySql databases, 3rd party APIs
Data Layer: Interface with CRUD operations, PDO for accessing DBs, Classes implementing CR... |
I just made this link please check this out Online Results
I need to select data between 2 values from a table by using MAX because each SID has different VID.
My code:
$sql = mysqli_query($con, "SELECT * FROM `tests` WHERE `VID` BETWEEN (SELECT MAX(`VID`) FROM `tests`)-6 AND (SELECT MAX(`VID`) FROM `tests`)-3 ORDER BY... |
As before, I am moving into C++ and would like to learn about its idioms. I have moved from Project Euler to CodeKata as the former is based on algorithms, rather than language constructs (as suggested by bruglesco in the comments).
Description (slightly modified):
Write a binary search method that takes an integer se... |
Is there any way to make this program run in better time ? While running, it is taking 1 second for the sample test case to pass and 5-10 seconds for the rest of the test cases.
Problem statement
A smart-set is a set of distinct numbers in which all the elements have the same number of 1s in their binary form. The se... |
I have coded the following quick sort implementation.
There are few things that still makes this code ugly and redundant.
1. Handling Arrays of Primitives
I have to write a separate implementation of QuickSort to handle each of the 7 primitive types. Is there a way, this could be done in a much better way?
2. Usage of ... |
Whilst learning Rust I am solving different algorithm problems. Below is a solution to largest rectangle in histogram.
Algorithm is well described here:
Although code below does the job it is very verbose (much more than my C++ solution).
pub fn largest_rectangle(v: &mut Vec<i32>) -> i32 {
let mut stack: Vec<usize... |
I am currently writing mergesort in Python and have implemented it to work. I have noticed, though, that it is very slow compared to the standard sorted() method. I understand it will always be faster but I am open to suggestions in terms of optimization.
def merge(left,right):
sortedArray=[]
l_idx,r_idx=0,0 #s... |
I have to solve an exercise from ANSI C book:
Add the commands to print the top elements of the stack without
popping, to duplicate it, and to swap the top two elements. Add a
command to clear the stack.
Here is my implementation in RPN Calculator:
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#defin... |
I'm new to coding C++ and I want to get some insight on my progress. Can you guys take a look at my program and give me some feedback on it?
#include <iostream>
using namespace std;
int main(){
int day{};
int monthNum{};
cout << "Calculate how many days are left in the month. \nPlease enter the month number and the ... |
Task:
The task requires creating a class (say, ConfigDict) which inherits from the dict class.
It is supposed to save its keys and values in a file.
If a file does not exist, the instance of ConfigDict should be able to create it.
Examples:
For instance, the following code:
fh=open("config.txt","w")
fh.write("key1 = 5... |
I'm trying to validate if an integer represents a valid IPv6 mask, which boils down to checking if all the left-most bits of an u128 are 1s, and all the right-most bits are 0s. For instance:
0 is valid
0xffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff is valid
0xffff_ffff_ffff_ffff_0000_0000_0000_0000 is valid
0xffff_ffff_fff... |
In a grid of hexagons, we often want to find the neighbors of a cell with distance n. In the image below we have a rhombus-shaped grid of hexagons with an axial coordinate system showing the cell (row, col) = (3,3) (dark gray), its 1-distance neighbors (medium gray) and its 2-distance neighbors (light gray).
In the co... |
I wanted to reproduce the type of navigation system found in the console of Firefox and Chrome: you can explore an object's properties by unfolding boxes:
So I'm searching to:
display all of the object's properties (even if they're nested)
being able to fold/unfold the properties if themselves are objects
Element h... |
This is one of my first C++ training project where I created the console application which displays the calendar of any given month.
I observed how offset of days (empty places on the calendar) change year by year and build the empirical formula on it. For the starting point (the fixed year) I have chosen 2008 only bec... |
This class encapsulates a 2D Array and a Scripting Dictionary. Values are add or returned from to the Array using a Key and a ColumnIndex, e.g. IndexedArray(Key, ColumnIndex) = Value . The Key is used to get the RowIndex of the Array. The Value is then added to the Array, e.g. Array(ColumnIndex, RowIndex).
Although,... |
currentUserPosts will have a post object with an id that either matches a tempId, an Id, or nothing.
If there's a tempId match there won't be an id match and vice versa.
This code works but there's something about it I don't like. How can it be refactored?
let postIndex;
postIndex = currentUserPosts.findIndex(post => p... |
I would really appreciate some feedback on this code. It 100% works (as far as I have tested it). Really just looking to improve where I can. This script is currently hosted on my local PC and is accessible to those I specify via ngrok. This is supposed to be a very rough and simple banking api. Wherein a user has a st... |
I'm currently in the process of building my own Chess game engine and could really use some suggestions on how to make this segment of code for calculating diagonal moves more efficient. (This is obviously only for diagonals going Up-Right.)
As of now I'm using "Try-Except" to iterate by 1, and then my return statement... |
Description:
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
Note: A leaf is a node with no children.
Leetcode
Code:
class Solution {
private List<List<Integer>> paths = new ArrayList<>();
public List<List<Integer>> pathSum(TreeNode root, int sum) {
... |
Problem Statement:
You are given a read-only array of n integers from 1 to n. Each
integer appears exactly once except A which appears twice and B which
is missing.
Return A and B.
Example
Input:[3 1 2 5 3]
Output:[3, 4]
A = 3, B = 4
I wrote the following code:
def repeated_number(number_array):
pair_A_B =... |
I've made some code that reads in text files (which hold quite large vectors of word frequencies), which in turn stores each index of a vector within an ArrayList for their specified team (i.e. Arsenal vector to the Arsenal ArrayList, Chelsea vector the Chelsea ArrayList, etc.). It then uses a cosine similarity functio... |
I recently published an iOS control/component called BJDraggable which basically, with a call of a method, enables us to drag a view within its superview boundary. The whole setup works using the UIKitDynamics API. (Scroll to last to see the output achieved.)
These are the methods I expose to consumers. You could follo... |
I am very new programming and am trying to develop a small tycoon game as a hobby project in Unity. This algorithm executes beautifully but if 100+ agents are getting new paths simultaneously there is a significant drop in frame rate. Where should I start with optimizing?
I use 4 classes for my pathfinding. The PathFin... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.