instruction
stringlengths
71
71.9k
I'm trying to improve my code to find all the prime numbers within a set range as fast as possible, and I am trying to make it even faster. On my github page here, I have some optimization settings within Visual Studio that help improve the speed. #include <iostream> #include <fstream> #include <Windows.h> #include <co...
I am a beginner in JavaScript and Phaser and wrote a Snake game. I think there are lot of things I could have done better. I am looking for some advice on how I can improve the design and refactoring of the code. You can play the game here. var mainGame = { preload: function() { game.load.image('snake', 'im...
Yesterday, I was bored and decided to write a random password generator. At first it used numerous temporary files, changed that by using arrays. This was written on OS X and should work on Linux with minor tweaks (at least change all gshuf to shuf). Example use: $ pw -c 3 -l 20 -a b -nsr Vh.9"7`gN;;$kV*/LddE q);S;byf...
I've made a program in C# that generates Mersenne numbers starting from the current largest known Mersenne prime. It then calculates the modulo between those numbers and smaller ones starting from 3 in order to figure out if it is divisible. I've used some math tricks to make the process pretty fast, and so I can check...
The program consists of two functions: the helper predicate function singleton-list? that checks whether a given list contains only one item and the function that does the actual job all-same?. ;; Predicate function: singleton-list? ;; ----------------------------------- ;; The singleton-list? predicate function tests ...
This is a continued improvement from discussion here (Find the shortest whole repetitive substring), since code has changed a lot dues to improvement, I post it here. Major smart ideas are from arvindpdmn. Major algorithm ideas, since we need to find wholly repetitive sub-strings, we only build Trie tree if the sub-s...
Input: Input contains one string S which consists of big and small latin letters, digits, punctuation marks and brackets from the set []{}(). Constraint: Constraints. The length of S is at least 1 and at most 105 Output: If the code in S uses brackets correctly, output “Success" (without the quotes). Otherwise, ou...
I have the following functions in JavaScript: function SelectFirstVisiblePublicationAndHideIt ( PageObj ) { var hideButtonXpath = "//img[@title='To hide this item in your profile, mark it as invisible']"; var hideButtonArray; var numberOfHideButton; var publicationTitle; aqUtils.Delay(500); hid...
I wrote a game solver similar (but with reduced features) to an application called GamesmanClassic but in C++. The general idea is that (roughly speaking) board games can be represented with the four following functions: initial_position -> Starting board position generate_moves(pos) -> Generate all valid moves give...
I have to co-operate with third party APIs from where I get a list and I have to remove certain elements before passing it toward. I have a working solution but I am opened for every suggestion to make it better or more reliable (assuming the third party API maybe will change a bit in the future): public List<Column> r...
Project Euler Problem 10 asks for the sum of all the primes below two million. I'm creating a list of primes and keep checking any new number for divisibility with only prime numbers. I thought it should take less time but it is going over 4 minutes. How should I approach such a problem? #include<iostream> #include<lis...
Here is my code: def read_Coordinates_Atoms2(fileName, only_CA = True): ''' in : PDB file out : matrix with coordinates of atoms ''' with open(fileName, 'r') as infile: for line in infile : if only_CA == True : if line.startswith('ATOM') and line[13:15] == 'CA': ...
I've followed the steps from this video from railscasts for setting ENV variables. This is my configuration: config/database.yml default: &default adapter: mysql2 encoding: utf8 pool: 5 username: <%= ENV['DATABASE_USERNAME'] %> password: <%= ENV['DATABASE_PASSWORD'] %> socket: /var/run/mysqld/mysqld.sock d...
Its been years (10+) since I have worked with sorting algorithms directly. So I have been trying to go over them again to refresh my memory. The thing is my ideas of how to do it doesn't seam to match the way I have the tutorials doing it. Does it matter? Assuming that my code is working I would almost mean that its ...
I want to pass errors in errors in order to know exactly the chain of causes, but without augmenting or even reading any stack until this becomes really necessary. And this is how I would achieve this: class RError extends Error { constructor(options = {}) { super(); this.name = options.name; ...
Take in a natural number n ∈ N, then process and output a(n), with a(n) being the number of quaternary strings (with 0, 1, 2, 3) of length n, where (from left to right) there never follows a character (i + 1) directly after the character i. For example, n=3 results in a(3) = 42: 000, 002, 003, 020, 021, 022, 030, 031,...
I've just refactored some code for a search box which takes a user search term, hits an API, returns a list of possible locations, and processes the users chosen result by sending them to a map page with their chosen result populated in the URL. I'm trying to improve my JS skills from just getting stuff done, to doing ...
Recently I came across this, here is an excerpt from it, This is another problem about Indraneel's library. His library has one long shelf. His books are numbered and he identifies the books by their number. Each book has a distinct number. He has lost many books, since many of his friends borrow his books and n...
I'm working on an isomorphic javascript module (query-hash) to handle query strings and base64 tokens. It's essentially a simple key-value object with methods for taking in data and giving it back in the format you ask for. function queryToObject(queryString) { return queryString.split('&') .map(kv => kv.sp...
Yesterday I posted my Generic List and received great feedback from it. I have taken the feedback to heart. Today I'm posting my take on the linked list in c#. LinkedList.cs using System; using System.Collections; using System.Linq; namespace GenericDataStructures { /// <summary> /// This is a singly Linked Li...
I have written yet another n-puzzle solver. I used the A* algorithm to search with the Manhattan Distance heuristic. It worked very well for the 9-puzzle (3x3) but was unusable for most instances of the 15-puzzle (4x4.) In fact I would exhaust all RAM before I got anywhere near the result. So I switched to IDA* and ...
The app is functioning but I am not sure if I have done it properly. The code is present in my GitHub repository. The demo can be viewed here. In this application a user can search for anything in a location of choice. I have used Foursquare (used for getting search results) and the Google Maps API (used for getting lo...
I am trying to fully understand interfaces and abstract classes in Java and from what I understood, I created a sample console application. Is there an error in the design or is this basically what interfaces and abstract classes are? Animals.java (interface): interface Animals { void callSound(); int run(); ...
I'm trying to implement a stack data structure, but not on the heap but using the stack. Also not using any Node or Element struct but raw ints. Is this feasible? This is my code (with debug printfs) and the output is below. It doesn't seem to work atm. My general idea was: Get some stack address (see create_stack())....
I want to improve my code. Is it possible to get the plot without repeating the same instructions multiple lines? The data comes from a Pandas' dataframe, but I am only plotting the last column (Total Acc.) e=df['Total Acc'].round(4)*100 #The repetitions start: row_awa = e.loc['AWA'] row_rem = e.loc['REM'] row_s1 =...
This is my first attempt at creating a Ruby script. I set up a Cron job to run this script every hour. I'm requesting constructive critiques and suggestions for making this better. Sidenote: I've hard coded the location to my hometown. I don't plan on changing it to another location. Here's an example of the expected o...
This works, but is very very slow. Any recommendations on better, less trivial ways of accomplishing this would be appreciated. With a smaller dictionary it's fine, but the dictionary is about 80 different mappings. I also hardly ever work with JS so any input would be great. Obviously I have not included the dictiona...
Nodes will be for simply linked lists, circular lists, maybe later on extending them to work with graphs. I'm trying to be as defensive as possible, will this leak memory? It runs perfectly I'm just concerned about coding style and best practices. Especially regarding the allocation I'm not 100% convinced of my solutio...
I've got a solution for Project Euler's problem 45. Triangle, pentagonal, and hexagonal numbers are generated by the following formulae: $$\begin{array}{lll} \textrm{Triangle} & T_n=n(n+1)/2 & 1, 3, 6, 10, 15, \ldots \\ \textrm{Pentagonal} & P_n=n(3n−1)/2 & 1, 5, 12, 22, 35, \ldots \\ \textrm{Hexagonal} & H_...
I am using the SICP book. There is an exercise in which you need to create a function that will receive a list as an argument and return a list with the same elements in a reverse order. I know there are more efficient solutions than the one I am going to present. However, I really learn by analyzing things that came u...
I'm working on simulating a number of processing elements (nodes) which do some work in parallel and communicate by exchanging messages. The message exchange is not in the scope of this post, but it restricts the modelling of the parallel tasks because they are not completely independent and thus cannot run in any orde...
Have some ideas to improve code from this discussion (Find valid triples for a sorted list of integers) and post new code in a new post. The new idea is to try to remember where low bound searched last time, and when doing the search, only search from the lower bound where last search is satisfied, since with j increas...
I am looking for a way to optimize this code so that it runs faster. I am trying to calculate the total items used, if for every x items used, you get one additional item to use. This is the code I currently have. I get the correct result, but with a large amount of items, it is taking too long to calculate. public s...
This is a problem that I had in mind for a loong time and today I decided to give it a go, the basic idea is you enter a number/sum and the program outputs all the possible ways this sum can be formed let's say we have 3 as input the output will be (1, 1, 1),(1, 2) I don't think that the code is really efficient so any...
I am just beginning to learn JavaScript and although I feel I am starting to grasp the language, I don't feel I know how to structure an app properly. I decided to start small and build a "TODO"-app using a modular pattern. I am aware that I should use more validations, there are unused functions, and there may be a m...
let deltaF: TransformBlock = { f in let transformation = (f > pow((6.0/29.0), 3.0)) ? pow(f, 1.0/3.0) : (1/3) * pow((29.0/6.0), 2.0) * f + 4/29.0 return (transformation) } Says here that this expression is too complex to be solved in reasonable time. Is there any way to simplify it? This code is m...
Note: Since my time has passed for this challenge, I do not remember exactly the stipulations but will attempt to recapitulate them to the best of my knowledge. Essentially, the challenge was this: Given a list (from 1 to 2000 elements) of random integers (from 1 to 999999) write a function, answer(l) that accepts a l...
I'm intern and work on a project where I develop DRF API that need to interact with mobile app written by my colleague with Ionic framework. We are creating new user. My view method is following: class NewUser(generics.CreateAPIView): model = User permission_classes = [permissions.AllowAny] serializer_clas...
I have written a simple window event capture wrapper that gets events that happen to the window, and can be checked anywhere in the program through a global class. I wanted to be able to create a callback anywhere in the program with any event that I have asked to be checked. To hold the data that is returned from the ...
My use case is to dispatch multiple long-running tasks to execute concurrently. The expectation is that the tasks will be IO-bound (e.g. network requests), but importantly each task is different. This is not a question about data parallelism. I've written a simple pool type that wraps a sync.WaitGroup and collects any ...
Below are two examples of arrays (with a special ordering with odd numbers on one side, and even number on the other side) I have, with some given len: 9 7 5 3 1 2 4 6 8 11 9 7 5 3 1 2 4 6 8 10 For some value z, I want to find the column the value is in. MATLAB code I wrote: if z == 1 column = ce...
The problem here , requires me to find the best possible combination of values in an array which is nearest to 0 and are adjacent to each other , here is an little excerpt from it, The government of Siruseri has just commissioned one of the longest and most modern railway routes in the world. This route runs the e...
Sadly enough I have a bit of code that is really slow and being a newbie in programmation, I don't have the faintest clue on how to optimize. Is there any way to make those calculations faster? This code calculates the worst case of some parameters cycling through AktBeam and FileCounter (those cycles contain a LOT of ...
I'm new to Android programming and this is my first project so I'm not sure if this is the correct method of rendering the toolbar or the navigation of the drawer on the screen: So I have a BaseActivity class that has the methods displayToolbar() and displayDrawer() to display the ToolBar and the Navigation Drawer resp...
I’m new to Java programming and uncertain if I used the right approach to solve my job. This little program uses the iText library to split one big PDF into smaller documents. The trigger for this is a text on every page in a specific region (found with a RegionTextRenderFilter). In all the smaller documents I also ha...
Here is my case I made list of items when I click at any item it should navigate to certain activity. Here is my I am done First I set number of constants to distinguish between each activity // constants to show activities onclick event private static final int LOC = 0, SERVICES = 1, PRE_APPROVE = 2, CLAIMS = 3, BENE...
I'm trying to catch WPF using MVVM pattern, where my set of models is implementing ObservableCollection as well as Entity Framework's DbContext. My project is quite simple movies database (looking for movies on disc, getting info about these movies from web, and so on...). I will be glad for any notes and recommendati...
With a few experience of python and golang, I tried to make (simple) thread pool executor. Tasks of the executor must be copy-constructible std::function<void()> and the result of tasks are required in the main thread. My Header and Implementation File: #include <iostream> #include <queue> #include <chrono> #include <...
I have an array that I am shifting by a certain number of spaces. I am wondering if there is an better way to do the shift with less touches. Here is my code function rotate_array(array, shift){ if(array.length -1 <= shift){ shift %= array.length; } for(var i =0; i < shift; i++){ var firs...
This code is intended to choose the best poker hand of five out of a set of cards. The cards are represented by a list of strings, where each string contains the rank and suit (e.g., 'AC' represents an ace of clubs). The code also handles numerical ranks for the face cards, so the string could also be '14C' for ace of ...
Although TI-83/84 calculators support multiple data types, such as real numbers, complex numbers, 1D and 2D lists, fuctions, etc., there is no data type for vectors. This program is my attempt to take the sequence three sequence functions (u v w), which are rarely used for their intended function, and transform them i...
I've created a "simple" function that receives a MySQLi resource and, using a custom where query, will fetch random IDs from a provided table. Some caveats on this: No object-style! This needs to be understood by people who only know the old mysql_* procedural API; No order by rand()! It is slow, but very tempting; It...
I'm a novice C++ coder, taking my first class this semester, and we have a project coming up. I get the program done early and it works as expected, but I don't know if it's too messy and can be cleaned up. It's a simple ATM program that allows you to create multiple accounts and withdraw or deposit money in them. Any ...
I have an assignment where I need to find out if any of the meetings in a list of meeting class object have overlapping datetime ranges. What I have so far is this: public class Meeting { public DateTime Start { get; private set; } public DateTime End { get; private set; } public Meeting(DateTime start, Da...
Why will this code work for a smaller multiple like 10 but time out for anything over 13? Can this code be revised to work for larger numbers? (I have an alternate solution but wanted to see if this code could be fixed to work for more multiples.) #2520 is the smallest number that can be divided by each of the numbers...
I decided to make a simple tic-tac-toe game in C++ as a small project. All help and suggestions are greatly appreciated! main.cpp: #include <iostream> #include <string> #include "TicTacToe.hpp" TicTacToe game; void turnPlayer1(); void turnPlayer2(); bool gameOver = false; int main() { std::cout << "**************...
In the SplashActivity of my Android Application, the following sequence of events occur: Check if Google Play Services is installed If Google Play Services are available, start the InstanceIDListener service Check if app needs to be updated Load country info using network IP Previously, I'd implemented this logic usi...
I have the following class structure: public class CustomDAOImpl implements CustomDAO { public List<Organization> getOrganizations() { List<Organization> results = new ArrayList<Organization>(); Client client = ClientHelper.createClient(); Resources<OrganizationResource> response = clie...
I wanted to restart the big-float project I had paused the moment I suddenly realized that the implementation of the main four rounding modes (which I postponed so long, that I got all of the IEEE-754 functions implemented in the meantime) needs three guard bits. And it needs them from the beginning. Which needs a comp...
SmallVector is almost same as std::vector except it keeps its data inside a large array. Similar to std::array, its size can not get bigger than the SIZE parameter. However, unlike std::array it may hold less than SIZE elements. I try to made it constexpr, but it is not really possible, because push_back need to throw ...
I made a program in C++ where it calculates the distance between two coordinates. Is there anything to improve? Add? Make it more user-friendly? Code: #include <iostream> #include <cmath> using namespace std; int ch; double x; double y; double a; double b; double answer; double distanceBetweenTwoPoints(double x...
I want to create a shopping cart project with discounts for products. For instance, if you buy 2 books, you can get 10% off Parker pens. I created a shopping cart example, but without exception handling in this version. Are my classes Product, Basket, Offers and Discounts properly structured, or what changes do I need ...
I found this question online as an example from a technical interview and it seems to be a flawed question in many ways. It made me curious how I would answer it. So, If you were on a technical Python interview and asked to do the following: Write an algorithm that receives a dictionary, converts it to a GET string, ...
A little bit of background; I'm a high school student in my junior year and I attended a tech competition last year when I enrolled in my high school's CS I course. Below is what I submitted to the competition and even though I won in my category, I remember the judges telling me that I could do better by implementing ...
I have n indexed socks, each of which has one of k colors. I also have a list that states which two socks I must wear at each of m days. Of course I want always wear same color socks. But unfortunately I must follow the list. What I can do is to re-color some socks. The paint is expensive so I want to re-color the leas...
I got bored and decided to write my own function to verify if a string contains another string. I was wondering if there's any major difference between these two function except the one I wrote being more complicated. bool Contains(string str, string find){ for (int i = 0; i < str.length() - (find.length()-1); i++)...
This is a program I made to practice using turtle graphics. I am looking for pointers specifically on how I handle the game board. Currently it holds all of the grid objects in a nested list. Sorry if the documentation in the program is unconventional. This is one of my first projects and I'm excited to see what I can ...
Input: The first line contains the number of vertices \$n\$. The second line contains \$n\$ integer numbers from the range \$\left[−1, n − 1\right]\$ representing the \$0\$-based index of the parent for each vertex. An index of \$-1\$ designates that vertex as a root without a parent. It is guaranteed that there i...
I have a method that retrieves information relating to a Contact that was made between two Companies. I am looking to improve my code in any way and am intrigued in hearing any recommendations you may have on how this method can be improved. I use it throughout my program but modify it according to the DataModel I am a...
Brief summary: The vanilla GoF visitor is great for altering items within a tree of elements, but when the visitor visits an element it can only change the children of that element not the element itself. For example, a visitor altering the DOM of a webpage could search for everything that contains an image and replace...
In the old days when C was the predominant language under the hood and STL/templates were Alex Stepanov's dream, in order for programmers to achieve generality for functions and data-containers, the void* was used as input argument or underlying container type respectively. A typical example is qsort which is located i...
I am currently reading Michael Kerrisk's book, The Linux Programming Interface. This is one of the exercises from the end of chapter 4 (I'm working in Rust, not C). A Rust implementation of the tee program on UNIX systems. According to it's man page The tee utility copies standard input to standard output, making a co...
I'm working through a course now, and was tasked with the following: Write a function, no_repeats(year_start, year_end), which takes a range of years and outputs those years which do not have any repeated digits. You should probably write a helper function, no_repeat?(year) which returns true/false if a single year do...
I am trying to solve the scenario involving 1 producer and 5 consumers. The producer puts data to queue and waits till all consumers have finished before adding more data. Please review and let me know if there is room for improvement. import java.util.LinkedList; import java.util.Queue; public class ReadUpdate { ...
I am coding on codingame.com, where one of the 'easy' challenges is to assign MIME type strings to input strings of file names based on their extensions. My code passes four out of five of the test cases, and the last one is an optimization test. A big data set is inputted, and my approach times out. I started coding ...
The program below basically reads configuration data from an .ini file in ini format. The exemplary configuration file was also added to this post . Let me know how I can improve it, please. using Sahara.Core.Logging; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using Syste...
I need to organize the following objects in a array applying the following rules: Group all object by source In each group order them by order property Rewrite each order property keeping their order starting from 0 I have drafted an initial solution below, the final result is present in the code comment and the scri...
For playing a Poker tournament, I wanted to create an application which should calculate the pot and the money of all players at every time. PokerBank class: public class PokerBank { /** * @param args the command line arguments */ public static void main(String[] args) { System.out.println("---------------Spiel...
I have a program where users can add integers to a list and then I want to check the list to see if any three consecutive integers in the list sum to a specified value. I have been told that it is taking too long when ran with a large number of integers in the list. The timing test that I am not passing is based upon l...
I created a script to import several CSV files from various sources and one CSV file with a list of systems in it. the script searches each CSV file to see if the system exist in the file and if it does then write the property information to a variable. The challenge that I have ran into is there are 26,000 systems to ...
There are good penetration testing tools in the market in which we can perform various activities gather information from the hosts effectively. But those tools are not helpful always like if we are using some public computers we need administrative rights to install wireshark,social engineering toolkit etc., and at th...
Is there a more efficient/performant way to accomplish this with vanilla js (no libs please) as the looping is slow? Also, how can I make it more flexible, so the HTML option values can vary a little, if need be? I need to cover different option values in HTML but they mostly follow the same format. Here are some other...
This is implementation of a Datepicker by our outsource colleagues. I want to get an objective criticism of code style and approaches used. I see: Global variables with popular names Styles inside JS Not allowed attributes like cellpadding Please help me find other problems. I believe that this code is not ready for...
I have a Product entity and a ProductCategory entity. Given the Product entity, my application checks the database via a repository to see if the ProductCategory already exists. If the category is not found in the database, then the application should persist it. Currently, I have this code in the service layer as foll...
Over the past year I've found myself moving from back-end development to something more akin to full-stack development. I've created the following jQuery plugin as a test of my hopefully-not-so-fledgling JavaScript/jQuery skills. The plugin is used to inject <option> tags into the element(s) specified, and should follo...
I was inspired by a solution in Think Python: How to Think Like a Computer Scientist. I structured mine (into two functions) according to it, and used the technique used in rotate_letter. It's here if you're interested. How can I make this better in all aspects (documentation, algorithm, variable names, and etc.)? Is m...
I'm working on a parser library for substituting strings in dictionaries, with things like globals etc. Wanting to get opinions on the direction I'm taking and where I can improve the script. This currently works class DictParser(object): def __init__(self, dictionary): self.working_dict = dictionary d...
The Koch snowflake is a well known fractal. Beginning with an equilateral triangle, a smaller equilateral triangle is placed halfway along each edge of the shape. This process then repeats on each edge of the new shape. Here is my attempt to plot this in MATLAB. clc, clearvars, close all; length = 1; % Original side ...
Update: git repo: https://github.com/muhsinali/picture-example-minified This is my first project that I've written using Scala and the Play framework. It's a simple application that allows the user to store pictures and see them (no edit/delete functionality, just to keep the code review simple). I have included a coup...
Here is the task from a beginner's course: Write a method that takes an array of numbers. If a pair of numbers in the array sums to zero, return the positions of those two numbers. If no pair of numbers sums to zero, return nil. This model solution does not use idiomatic Ruby, because at that point in the course, we...
We have a JavaScript function declaration as such: function itemIncludesTotal(item){ var includeItem = false; if (item.lineItem.hasOwnProperty("details") && item.lineItem.details.hasOwnProperty("total") && item.lineItem.details["total"] && !item.lineItem.restricted ){ includeItem = t...
I've decided to learn a bit of C++, and so I've started with a simple linked list. There's no input to the program and should always output hlo. This is as in main I build a list consisting of hello, and use Get and last to get the data. I don't know C++, or C, and so this is mostly a stab in the dark. I don't know if ...
The task: Write a method that takes in a number and returns true if it is a power of 2. Otherwise, return false. You may want to use the % modulo operation. 5 % 2 returns the remainder when dividing 5 by 2; therefore, 5 % 2 == 1. In the case of 6 % 2, since 2 evenly divides 6 with no remainder, 6 % 2 == 0." Model sol...
The task: Write a method that takes in a string. Your method should return the most common letter in the array, and a count of how many times it appears. Model solution: def most_common_letter(string) most_common_letter = nil most_common_letter_count = nil idx1 = 0 while idx1 < string.length letter ...
I just had an interview for the C#.NET developer position and I was asked to find the first non repetitive char in a given string without using any library functions but just the basic constructs of the language such as fors and ifs. I presented this solution considering the quick time constraint. I request evaluation ...
I wrote this code to check the even numbers from the List. After finding even number I twice the even numbers with the help of Map and then find the sum of each even number after making it double by use of the reduce method. import java.util.Arrays; import java.util.List; public static void main(String[] args) { List<...
This is my first attempt at creating a simple Python tool that tracks the time of certain activities retrieved from a database. After stopping the timer, this tool writes the duration of the activity into the database. Can you please provide me some tricks to make this code more Pythonic? objects.py #!/usr/bin/env pyth...
I'm processing a list of files, and want to check the filenames against a list of regex, like: IGNORE_FILES = [ re.compile('^./Vendor.*'), re.compile('^./Pods.*'), … ] def in_blacklist(file): return len(list(filter(lambda r: r.match(file) != None, IGNORE_FILES))) > 0 def in_whitelist(file): retur...
I want to set flags which are given in string representation in any order. And it is intimidating, because you have to check like 2^3 possible options in my occassion. I was just wondering is there any better way to do that than just simple brute-force. Any optimization and readability improvment would be great. This i...
There are some things that smell about this code, for instance multiple checking, length both returning value and changing some other variable. But I can't for the moment figure how to make it nicer, or if that's even possible. Converting it to stack-based solution seems to be making it a bit too-complicated. Please pr...