instruction
stringlengths
71
71.9k
Inspired by this meta question I decided to take a look at Rosalind. Their first challenge seemed easy enough: An example of a length 21 DNA string (whose alphabet contains the symbols 'A', 'C', 'G', and 'T') is "ATGCTTCAGAAAGGTCTTACG." Given: A DNA string s of length at most 1000 nt. Return: Four integers (separated ...
I created a load balancing server at work and have to keep track of which server it adds the user to, so I wrote a little Ruby script that will do just that. I'm looking for any critique of my work, can I do anything better at all. Source(user information, directory information, and server information changed for secur...
I have a service that raises multiple events, some of them can be raised at the same time. I need to process those events and run a potentially long running method based on the event arguments. What I did is to create a BlockingCollection<T> that will store the events and a Task that will keep taking one event at a tim...
This is sort of a follow-up to Replacing elements from a list and its sublists but now there are arbitrary numbers of words that would be replaced stored in a list. Now write substitute2 that takes a list, a list of old words, and a list of new words; the last two lists should be the same length. It should return a c...
To keep it succinct, I created a simple way to input dates and times into an input box without worrying about formatting. As an alternative to date time pickers, dropdowns and all the other various datetime libraries. Repo Demo page /** * Loosetime.js * * Author: Bruce Taylor * URL: brucetaylor.xyz * Date: ...
I'm starting a project in which I'll generate random graphs and use algorithms to solve them. The first necessary step is obviously to build a graph. My graph has the following characteristics : It can be directional or not, implying that the Edge between NodeA and NodeB can be traversed from B to A if the Graph is ...
From SICP Exercise 2.5: Show that we can represent pairs of nonnegative integers using only numbers and arithmetic operations if we represent the pair a and b as the integer that is the product 2^x*3^y. Give the corresponding definitions of the procedures cons, car, and cdr. Please review my code. (define (cons x y)...
I've made more improvements from previous iterations and my own, including: Added the -n flag (print owner and group IDs instead of names) Eliminated some bools by allowing certain flags to turn on others Added a Date struct for keeping the current date in one place Added an Entry struct to ease sorting and informatio...
Problem 21: Let \$d(n)\$ be defined as the sum of proper divisors of \$n\$ (numbers less than \$n\$ which divide evenly into \$n\$). If \$d(a) = b\$ and \$d(b) = a\$, where \$a ≠ b\$, then \$a\$ and \$b\$ are an amicable pair and each of \$a\$ and \$b\$ are called amicable numbers. For example, the proper divisors o...
I am trying to program a skew logistic distribution function to return the PDF, the CDF, and (later) the inverse CDF. Although there are several forms of skew logistic, this is for perhaps the most widely known, a variation of the skew normal distribution introduced by Azzalini and covered by Saralees Nadarajah. Asid...
I attempted a problem from the Cracking the Coding Interview book. The following input: aabcccaaa should give the following output: a2b1c3a3. Any advice is much appreciated! #include <stdio.h> #include <stdlib.h> #include <string.h> char* compress(char*); int main(int argc, char** argv) { if(argc==2) { ...
In the app I'm creating, when a user upvotes a post, the post should be upvoted, as well as the user that wrote the post. But this updates two MongoDB documents. This presents a number of issues. I'll first provide an overview of the code and then list the issues. A user clicks on an upvote button, which calls the vm.u...
I was working on this game for while and I have made it for education purposes by using SFML. The game works fine but I would like to know how I can improve it. #include <SFML/Graphics.hpp> #include <vector> #include <utility> #include <array> #include <random> #include <iostream> #include <algorithm> #include <functi...
With the festive season mood and the new year coming, I thought I would make my first question this year, a tree implementation. Blame me because it doesn't have anything to do about Christmas. public interface ITreeITem { object Key { get; } object ParentKey { get; set; } } public class Tree<T> : IEnumerable...
If I have a oneliner in C such as size_t maxSizeOf(const char *s) { return strlen(s) > M_MAX_SIZE ? M_MAX_SIZE : strlen(s); } would it be better to have a macro defined such that #define MAX_SIZE_OF(s) (strlen(s) > M_MAX_SIZE ? M_MAX_SIZE : strlen(s)) or would it be better to have size_t maxSizeOf(const char ...
This program offers 8 notes C, D, ..., A, B, C on keyboard keys 1, 2, ..., 8. Also, by typing Left or Right, you can cycle over MIDI instruments. KeyboardPiano.java: package net.coderodde.music; import java.awt.Canvas; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import javax.sound.midi.Instrumen...
The objective is to create a lightweight object pool that should be as simple as possible, but not simpler. It should be able to create and pool any type of object, be configurable (i.e. pool size) and be able to be replenish exhausted pools or timeout waiting for returned objects. It should be thread safe and able to ...
One thing lead to another and eventually I wanted to know the "proper" way of writing the permutation generating function in C#. Below is my code for generating permutations. This will go into an internal library, so the calling context is really generic. Expected calling is in a single-threaded context /// <summary> /...
As a self taught developer I never did any of the Project Euler problems, so I decided to just start with Problem 1 which states 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 or 5 below 1000. The...
I recently implemented a subset of the ustar archiving utility as my first year programming one project. I would like to get it reviewed and if anyone has anything to point out. dir.c #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <dirent.h> #include <string.h> #include <stdio.h> #include <st...
I've just written code for generating all permutations of the numbers from 1 to n in Java. It seems to work, but I think it's a bit more complex than it needs to be. import java.util.*; public class ProblemFour { private static int n; private static void printResult(int[] result) { Set<Integer> set = ...
After I have tackled the first problem I come to Project Euler Problem 2 which states Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... By considering the terms in the Fibonacci sequence wh...
Inspired by this question I decided to write an alternative that uses polymorhphism and a Factory pattern. The code works for the subset of implemented types, namely BYTE, WORD and STRING but I have a few concerns: I'd like to get rid of the big ugly switch in the TLVFactory. Is there a way to make the TLVFactory::...
This is a data structure that supports the push(), pop() and isEmpty() operations and returns the least element on every pop(). In a sense, this works like a PriorityQueue, only in \$O(n)\$ runtime against the \$O(log n)\$ runtime of a PriorityQueue. My implementation: public class SortedStack<T extends Comparable<T>> ...
I've created a class that holds an EAN13 code. This class is an attribute of the Product class. In the Ean13 class, the string that represents the EAN code is passed as a parameter to the constructor and the validation is performed in the constructor. I created some utility methods in that class, like sumEven, sumOdd, ...
I've been told that using God objects at all is a Bad Thing™ In object oriented languages, God objects know all, they control too much. I'm trying to build a game (or for the scope of this question a generic app with a GUI) and I'm using a Main object that holds all the other objects needed to make it all work. At the ...
I want to create a predicate nearby(X,Y) which represents "X and Y are integers 1 apart from each other" and fully satisfies: %%! nearby(+X:Int, +Y:Int) is semidet. %%! nearby(+X:Int, -Y:Int) is multi. %%! nearby(-X,Int, +Y:int) is multi. In other words it must work for any combination of two bound inputs or one bound...
I have solved the day 6 adventcode problem: --- Day 6: Probably a Fire Hazard --- Because your neighbors keep defeating you in the holiday house decorating contest year after year, you've decided to deploy one million lights in a 1000x1000 grid. Furthermore, because you've been especially nice this year, Santa has...
I have to create a function that takes a positive integer number and returns the next bigger number formed by the same digits: 59853 -> 83559 Please let me know if there are any better solutions. I would like feedback how to improve this. def next_bigger(num): numlist = [int(i) for i in str(num)] index_of_repl...
I have come up with the following method to post a transaction to a database, in the context of an e-commerce Java web application. The transaction consists in submitting a new order alongside its details: public long insertOrder(Customer customer, Hashtable<String, CartItem> shoppingCart) { long returnValue = 0L; ...
I created a simple 15-line number guessing game in Python 2.7: # Guess the number game username = raw_input("What is your name? -> ") guess = input("%s, I'm thinking of a number between 1 and 10. -> " % username) answer = 7 # sets the answer answer = guess if guess < 7: print "That's too low." if guess > 7: ...
I left out the helper() function because it is gargantuan and is a problem for another day. Basically, this program asks for: Your name Your parents Number of siblings Marital status Number of spouses Number of children for each spouse It then dumps everything into a helper function which draws said family tree to a...
I am wondering if there's a better way to structure my code. I want to keep my controllers thin but at the same time want to keep the model methods flexible. As you can see below, it's almost as if I can write active record code directly on my controller itself (Which not be a good thing?) The line of code in the contr...
I've been trying to find a way to collapse all these methods into one. Current I have these methods default byte readByte(long address) { return read(address, 1).get(); } default int readShort(long address) { return read(address, 2).getShort(); } default int readInt(long address) { return read(address, 4...
I have this program that compares performance of two algorithm for multiple exact string matching: Given a set of patterns and the text, find in the text all occurrences of any pattern. For example: Text: habababa Patterns: aba, ha Above, aba occurs 3 times, and ha occurs one time (matches are allowed to overlap)....
I wrote a function to reverse an array. The first argument is an iterable object, the second argument is the size of the array element in bytes, and the third argument is the length of the array. void reverse(void *object, int size, int length) { int i; int j; int k; for(i=0, j=length-1; i < j; i++, j...
I was doing a basic problem on coding a factorial \$n!\$: function factorialize(num) { if (num < 0) { return undefined; } else if (num === 0) { return 1; } else { return num * factorialize(num - 1); } } The site I'm learning from accepted this solution, but they're only testing for nonnegative integ...
I've seen a tutorial where a dbcontext base class is created like so: public class BaseContext<TContext> : DbContext where TContext : DbContext { public BaseContext() : base("name=Context") { Database.SetInitializer<TContext>(null); } protected override void OnModelCreating(DbModelBuild...
I am trying to learn how to professionally work with unit testing, so I have refactored a medium sized project of mine (a sort of article aggregator that also does some NLP processing) and tried to apply some patterns to allow efficient testing (based on answers proposed here). Current structure of the application: Co...
Based on the previous question, I have implemented all suggestions. Also, I added new features to the game. Summary of improvements: Implemented smooth movements to snake instead of tile movements to give realistic impression Added fixed timestep Game relied on radian and degrees instead of enum of directions for com...
Title is pretty self explanatory, this program just takes in input (not from command line arguments), removes the extra spaces in the input, then prints that to output. /*replace string of blanks with single blank*/ #include "stdio.h" int main(int argc, char const *argv[]) { int nb,c = 0; while ((c=getchar(...
This question is an improvement I did based on recommendations from these other questions: Simple object-oriented calculator Simple object-oriented calculator - follow-up Simple object-oriented calculator - part 3 To those looking at this question for the first time, I'm trying to find a correct OOP model I can use in ...
I've written the following code to determine if an Internet connection is available in mind of this article at Microsoft's technet. In short, there are two methods of prove: Check if the response of http://www.msftncsi.com/ncsi.txt is Microsoft NCSI. If not, check if the IP of dns.msftncsi.com is 131.107.255.255. //...
I am learning clojure this week end and just starting to develop a simple checkers engine. I currently coded some basic functions to create the board and display it. I would love to get some feedback ! (ns sandbox.checkers) (def standard-size 10) (defn empty-board [size] (vec (replicate size (vec (rep...
I have been working on a project for several days. It is a command line program for viewing files in hexadecimal. It is usually very fast, but is there any way I could make it more efficient? #include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]){ if(argc == 2){ FILE *in = fopen(argv[1], "...
Below are two functions that work no problem in my current script. They are written to be ran in Python 2.7.x def tor_browser_initialise(): """ This function checks whether the Tor Browser is running. If it isn't, it will open the Tor Browser. """ processlist = [] for p in psutil...
I am making a Sudoku game and I have managed to add random numbers, add numbers, and to checklines (if there is 2 numbers on the same line). I am trying to check the 3x3 boxes if the number is twice or more in the same box. I have managed to do it one way, but is this the easiest way? In that case I need to do this 81 ...
I'm learning JavaScript and decided to build this mortgage calculator as a starting point. For the most part it was reasonably straightforward, but when I implemented the graphs using D3 I found myself with two similar functions that contained a lot of the same code. I could have used one of the many D3-based charting ...
I had to create this makefile to build and debug a C++ console app. I just need some hints and tips on how I can organize my makefile. CC=g++ CFLAGS=-c -Wall LDFLAGS= SOURCES=helloWorld.cpp OBJECTS=$(SOURCES:.cpp=.o) EXECUTABLE=helloWorld all: $(SOURCES) $(EXECUTABLE) debug: CXXFLAGS += -DDEBUG -g debug: CCFLAGS += -...
I am making an HTTP request with the Google Maps API and I have to pass in parameters (adresses/coordinates): $.ajax({ url : 'https://maps.googleapis.com/maps/api/distancematrix/json?origins=' + $("#origin").val() + '&destinations=' + $("#destinations").val() +'&mode=driving&key=AIzaSyASanevdiCI4t1h8LMf5FgWHMD...
Source: Rosalind("Consensus and Profile") Brief summary A T C C A G C T G G G C A A C T A T G G A T C T DNA Strings A A G C A A C C T T G G A A C T A T G C C A T T A T G G C A C T A 5 1 0 0 5 5 0 0 Profil...
Inspired by this question I thought I provide my implementation. I tried to go with the spirit of the *nix tool chain - read from stdin and write to stdout. This has the added benefit of making buffering very easy (current and previous characters and the count). All kinds of reviews welcome (best practices, error handl...
I have written an isRotation function that calls on isSubstring only once(I am allowed to call it only once). I have implemented my own version of isSubstring as well. Any advice is much welcome! //Checks if one string is a rotation of the other #include <stdio.h> #include <string.h> #include <stdbool.h> bool isRota...
I need to get the distinct sums of naturals of a natural What I came up with is: type Sum = Stream[Int] //should maintain the invariant that //* all Ints are positive //* is non-strictly decreasing //* is non-empty def makesums(i: Int): Stream[Sum] =...
How can I improve my code and make it more idiomatic? package pascal func NextRow(prevRow []int) []int { x := make([]int, len(prevRow)+1, len(prevRow)+1) x[0], x[len(prevRow)] = 1, 1 for i := 0; i < len(prevRow)-1; i++ { x[i+1] = prevRow[i] + prevRow[i+1] } return x } func Triangle(x int) ...
For my current project I need a basic UDP server. The first priority is to make it as fast, but as resource friendly as possible (it will be run on Raspberry Pi-like devices). I would like a review about the general code 'quality' and logic. I know that I am missing some error-handling at the moment. The Server class: ...
My primary concern is that this has been written as a global function. I think it would be better if this was a function of the SignalProducer class but I am not sure that is even possible. Is this thinking justified or is the use of global functions acceptable? (The following code uses ReactiveCocoa 4 and is written...
I completed writing a dice roll script in Python but I thought it looked too messy. Is there anything I should change here? import random, os class Dice: result = [] total = 0 def __roll_(sides=1): return random.randint(1, sides) def roll(sides=1, times=1): for time in range(0, times)...
I am brand new to coding in Python, and programming in general. I have picked up the Learning Python book and have been slowly making my way through it. I decided that I would try to implement what I have learned by writing a simple word-based game that I could run through the Mac OS Terminal. I would love to hear any ...
Background and Purpose For those unaccustomed to Ruby, Ruby supports range literals i.e. 1..4 meaning 1, 2, 3, 4 and 1...4 meaning 1, 2, 3. This makes a Ruby for loop pretty sweet: for i in 1..3 doSomething(i) end It works for non-numeric types and that's pretty cool but out of our scope. A similarly convenient t...
It seems odd that state must be passed around all the time. Can't State module hold itself, so I could do something like state = %State{size: size} case state.is_full? do ... Here state is always passed. I suppose this is how it is in FP? defmodule Chatter.Room do use GenServer defmodule State do defstr...
I'm not great with JavaScript. I've written a small jQuery function and I've now got it working, but I just wanted to check if the code looks good or if it can be improved. I wanted a function so that I can easily add the function to any textarea and input so that it counts characters remaining and so I can just change...
This working macro converts Hindi Devanagari proprietary font to Unicode font. It reads the conversion table from a tab delimited file, and converts one by one by finding all matches and then does some ligature shifting. I don't know how efficient it is and how much time and resources it uses. Feel free to tell me if s...
This is a section of code in a program I have created to store and review the results of a game based upon the "class_number" the user gives. This section is very bulky and I was wondering how I could make it more efficient. if class_number in ['1','2','3']: if class_number == 1: query = """ INSERT...
I am printing subsets from an array whose sum has been specified, while avoiding duplicates. I think there may be improvements, potentially on how using map is bad idea, or how can I avoid map to filter the duplicates. Additionally, in my code I want to reverse the sort order of an int array using streams which is aske...
I have two similar libraries for use in an embedded system (Teensy, sort of like Arduino). One is for debouncing a digital pin, the other is for reading a capacitive pin as if it is a debounced digital pin. They have similar APIs: constructor (with pin number as parameter) void update() hides reading the pin and inte...
The following code is my attempt to create an interactive bodeplot. I used JavaScript using d3.js, jQuery Mobile and math.js. The bode plot shows a lead lag filter in continuous time and several discrete time equivalents using a certain discretization technique. I would like to have some comments on: How I created the...
I came across this problem by accident and gave it a go. I think my solution works as it has passed all the unit tests I wrote. Given I just started learning F# a couple of weeks I would love to have some feedback on the code regarding both its accuracy and its quality. To be clear about the problem, given an integer ...
I wrote some code to implement a way to filter the arguments of a variadic template based on their type. My current solution requires many helper meta-functions and I'm sure that there must be a better way. How would you improve this? #include <type_traits> #include <tuple> //Type for storing a variadic template templ...
I was playing around with ES6 arrow functions, currying and partial application and I decided to try a functional implementation of the FizzBuzz problem: function* range(start, stop) { for (var i = start; i < stop; i++) yield i } var map = fn => res => x => fn(x) ? res : null var isDividedBy = dividend => diviso...
I have the following 'interface' to the C++ std::list and I was wondering how I could make it go faster. In particular, it needs to be able to evaluate up to two million operations in a matter of a couple seconds. Right now it's at around 8 seconds. #include <iostream> #include <list> int main() { int n, m; s...
I built a small app that gets data from a remote json file and displays it in a list of users. In each list item, an image of the user, their name, and their points tallies are shown. The list is displayed in two possible ways - 'all time' and 'recent' - depending on the user's choice. I would specifically like feedbac...
As an interesting sub-part of an interpreter -- just the Read part of the REPL -- I present my raw-mode line-oriented editor that I intend to use for my APL interpreter. (The Eval part has been posted for review in comp.lang.c.) It defines a large character-translation table to coordinate the input-form/internal-rep/ou...
I'm learning C and one of the questions I've been asked is converting a string to an integer. The code I've written supports converting from a string in any base up to 16/hex to an integer. There is no over/underflow checking and it does not support lowercase hex. int ASCIIToInteger(char *x, int base) { //Each el...
Heres the idea Write a program that takes two integers, N and M, and find the largest integer composed of N-digits that is evenly divisible by M. N will always be 1 or greater, with M being 2 or greater. Note that some combinations of N and M will not have a solution. Example: if you are given an N of 3 and M of 2, the...
I wrote a function that basically works like sprintf, but instead returns the formatted string (std::string). I haven't worked on this long, and I'm aware there are tons of improvements that could be made (alloc/realloc perhaps?). I was just looking for some advice before taking the next step. GLOBAL string format(cons...
As a follow up to my previous question I've improved the code + algorithm. The compression now works the following way: Each character is followed by a length byte. The top 3 bits of that byte denote the number of additional length bytes which encode the count. The count is stored in "little endian order" (least signif...
I recently solved this leetcode problem: Given n nodes labeled from 0 to n - 1 and a list of undirected edges (each edge is a pair of nodes), write a function to check whether these edges make up a valid tree. For example: Given n = 5 and edges = [[0, 1], [0, 2], [0, 3], [1, 4]], return true. Given n = 5 and edg...
Explanation For this Christmas, I got this puzzle as a present, with the aim being to try and fill 25 "Z" shaped pieces into a 5x5x5 box. Once I saw this gift, I thought I would challenge myself into trying to make a program to solve this for me. Picture of piece All pieces are exactly the same, which are 5 units in s...
I'm using a method to make initialize the attributes of my objects, and this method is called from both constructor. What it does is, if no correct currency has been passed, choose € by default. I'm just wondering if what I've done below is correct in terms of design. class Prix { double valeur; string monnaie;...
I'm learning Clojure and I'm interested in areas that could be more idiomatic. The main function is below. If you're interested in the whole lib, check out this. The function operates on a grid, which contains a finite number of cells. A cell is a single point in a grid. neighbours-of will get information about moving...
I've posted a question on stackoverflow: How can I consequently read messages from a queue in parallel? I would like my own answer to be reviewed. Situation We have one message queue. We would like to process messages in parallel and limit the number of simultaneously processed messages. Our solution Based on answers g...
I'm making a Battleship game using python 2.7. However, how to make it is not currently my issue. The main aspect that I'm asking about is the style and method of making the code. Am I following best (or even good) practice? Are the comments too much, too little, unclear? If someone could give me some pointers based...
I have a list T of objects (of class Element, this class stores attribute values (strings) of elements from an HTML page) in C# - Visual Studio. I am interested in finding the maxPageWidth. To do that, I want to check the whole list of objects for the Left value and the Width value. The highest of these values put tog...
Here is what I've written for a program to print upper half triangle of a matrix. Now I need a way to do it without using goto: #include <iostream> using namespace std; int main() { int a[10][10], r, c, i, j; cout << "Enter the number of rows and columns"; cin >> r >> c ; cout << "Enter the matrix...
Based on suggestions and some thoughts I made some refactorings of my classes to hold EAN13 codes, I created a contract interface which now is extended by BarCode classes, since there will be other types of BarCodes, like DUN-14, UPC-A... public interface BarCode {} I decide to move all the validations to factory clas...
import java.util.Scanner; public class ticTacToe { public static Scanner input; public static void main(String[] args) { input = new Scanner(System.in); char p1 = ' '; char p2 = ' '; boolean gameOver = false; char[][] board = new char[3][3]; int pos1 = 0, pos...
I have written this little function to convert UK weight drams (dr) to ounces (oz) and pounds (lbs). As far as my research goes, 1 lbs = 16 oz and 1 oz = 16 dr. I need the function to return an array of lbs, oz and dr. Am I doing it right? Or is there a better way to do it? Has my method got any flaws? function fromDra...
Here is my Haskell program designed to list all of my GitHub repos along with their descriptions and languages via the GitHub JSON APIs: {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} module Main where import Control.Monad import Data.Aeson import qualified Data.ByteString as BS import qualified Da...
Is there anyway to improve with how this code is structured into functions? Is the coding style compliant, and what can be improved beyond this? def add_lower_intuitive_relation(gurobi_model, Leg1, Leg2, lower_bound, eval_func, name=""): for first_departure in xrange(Leg1.latest_departure_time - Leg1.earliest_depar...
I built this as part of completing the Codecademy JavaScript lesson. I wanted to perfect it, make it readable and functional, and as efficient as possible. As far as I can tell it can't be any more efficient than this. But maybe I can't tell. What do you think? I know there are little things, maybe the victory variable...
What I'm trying to do here is first set the first eight variables to the proper default values. That's the first area I'm thinking there might be a way to optimize. Is there anyway to set both variables at once for example I know in PHP I could do $title=$d_title="value"; Is there any way to consolidate that section? (...
I created the following code to better understand CIDR notation. Also to learn some of the Stream features in Java8. I posted my unit tests too. I'm interested in ways it might be improved especially by using Java8 features. I reviewed the InetAddr class and realized it uses at array of bytes instead of ints. I did...
I wrote a simple synchronization primitive that I can use with async operations on an external REST service so that I don't call it twice from different threads and have one call fail due to not having the latest state. Despite obvious limitations of that design decision I think this should solve my problem... struct ...
I need to read Databases which contain 44-50 Tables, with around 5 Million entries in Total (~ 100k entries per Table). The Data consists of Positional Tracking Data in Sports (Players,Refs and the Ball) and Match-Events (Shots, Plays,Tackles,...): Match-Events are negligible regarding performance. Table: PlayerXYZ or ...
I have written the below code which loads the dictionary and checks if the given word is present or not. The implementation is using a hash table with a chained linked list. In regards to the hash function, I have kept it simple as I was not very concerned about collisions. Can someone please review it and let me know ...
I made this small and easy function that returns the largest common multiple of the elements of ms that is equal to or lower than max: LCMLthan = function(ms,max) { ms = sort(ms, decreasing =TRUE) max2 = c() for (m in ms) { max2=append(max2,m*floor(max/m)) } max2=min(max2) while (T) ...
This is code for performing a calculation that should be repeated with different levels and temperatures. I am concerned about the organization of this code as I feel it may contain too many helper functions and seems a little unnecessarily complicated. Only the getCharge() method needs to be exposed to the browser. Th...
For a leetcode problem to generate the valid parentheses of length 2n, I have written this solution. It is working for smaller inputs but not for larger inputs. Please suggest a way to optimise my code. I have read the Stack Overflow questions but was unable to implement the same concept in my code. //I have writte a ...
I've got a simple JavaScript function that takes multiple types of arguments. Inside the function I'm doing a check on the arguments to determine which way the user called the function: var build = function() { var args = Array.prototype.slice.call(arguments) var options = { to: {}, from: {}, ...