instruction
stringlengths
71
71.9k
This code simulates a polygon (say a triangle) with a person at each vertex, every person is looking at the next adjacent vertex/person. They all start moving towards each other with a constant velocity "trying to chase other". I could not understand this conceptually so I created an applet in Java to help me understan...
This is an online problem. The challenge is to print the kth prime number, for each k given in the input (1 ≤ k ≤ 15000). The first line of input indicates the number of inputs on the subsequent N lines. Example input: 4 1 2 3 4 Example output: 2 3 5 7 (the 1st 2nd 3rd and 4th prime numbers). #include <stdio.h>...
I watched a presentation by Dave Thomas on Elixir where he gave an example problem that he solved using functional programming. He mentioned using Ruby to solve the same problem, but did not show an example. I decided to give it a try. The problem goes something like this: For a list (Ruby doesn't have lists, but for o...
I currently have a working code that does exactly what I want it to do, loops through a particular part of an excel document looking for certain keywords, then pasting those keywords into a separate sheet in the excel spreadsheet. It is just very long and doesn't allow for any more than 20 repetitions. I was wondering ...
Does this extension method contain unnecessary work? - Thanks for reviewing Scenario - A series of tables are Key-Value pairs (Int "Id" / nvarChar "Title"). This extension method "dots-off" any integer ("Id") and provide the corresponding string value ("Title") given a target "type" Used in aspx-code-behind. An extens...
Just for practice, I am writing a tic tac toe game in Python 3.4. My main goal is to make expandable, for example allowing larger boards and more than two players. The way my project is arranged is something like: lib.py - All the functions and classes needed for a tictactoe game ai.py - Functions for the artificia...
The exercise 1.3 of the book Structure and Interpretation of Computer Programs asks the following: Exercise 1.3. Define a procedure that takes three numbers as arguments and returns the sum of the squares of the two larger numbers. My answer is this: squareTwoLargest(X, Y, Z, R) :- ( X > Y -> A = X, B = Y ; A =...
I was writing a program in C++11 to find top k words from a file. I think priority queues will give the optimal solution so I implemented using that. The code works and compiles. Could anyone please review this and suggest some more C++11/14-ish things to do? I also have some specific questions: Is there way in C++11...
How do I make this efficient? #include <stdio.h> #define MAX 1000000000 int main() { int n,temp,prod,i,j=0; scanf("%d",&n); for(i=1;i<MAX;i++) { temp=i; prod=1; while(temp!=0) { prod=prod*(temp%10); temp=temp/10; } if(prod==n) ...
I have some fascination with terrain generators, so I whipped up this generator in Python. The way it works is pretty simple, but I figure that I should give an explanation for those who don't want to try and figure it out. The initial 2D terrain array is generated with a provided width and height, and then filled ent...
My Python-based web server (Tornado module) is pretty complex and keeps going down (seems like usually in the middle of the night), so here's a bash script that kills the process, restarts and emails and txt messages me: #!/bin/bash NOTIFYEMAIL=<my_email_address> SMSEMAIL=<cell_phone_number>@<carrier> # ie. pm.sprint.c...
I am challenging myself to try to attempt to write a function that is as efficient, portable and failsafe as possible. The function is very simple and just converts a string (or wstring) to lowercase. Are there any improvements you think I could make and any errors I have done? #ifdef UNICODE typedef std::wstring tstr...
I am working through a new challenge on CodeEval.com and I think I am getting a correct result but I can't get through their grader. I am not exactly sure where error is. I didn't post this on stack overflow because I also would like to get your opinion on the code and the algorithm that I came up to solve this. Thi...
My teacher wants us to create a program that runs n games of war and calculates the average number of battles, wars and double wars that occurred. He has very specific rules (not necessarily the actual rules of war). I know there's some redundant code in the deck building and splitting for each game, but that's how he ...
I'm solving exercise 2 from lecture 3 of Berkeley's CS 61A (2012): Write a function min_element that returns the minimum element in a tuple. def min_element(tup): """ Returns the minimum element in tup. >>> a = (1, 2, 3, 2, 1) >>> min_element(a) 1 """ I know that Python has a built-in min functio...
I have a nested hazelcast distributed map: Map<CountryId, Map<CityCode, Map<data_key,data_value>>> where "data_key" is "population", "literacy_rate" and "gender_ratio". Below is the class where I have implemented a method which adds new city data to a specified country. import java.util.HashMap; import java.util.Map; ...
I am trying to create max-heap for practice. Are there any bugs? Are there ways that I can improve the code quality? public class MaxHeap <E extends Comparable<? super E>>{ List<E> list; public MaxHeap(E[] array){ this(Arrays.asList(array)); } public MaxHeap(List<E> list){ if(list == null) throw ...
I am doing a beginner C++ project and it's simply a library management system where a student will hire, give back a book, book and hire records are stored in a binary file etc. I'm approaching the project as though the project would be used by other developers and that I need to design the classes so they cannot be in...
I am using a CQRS type patter for querying data in my application. I am currently using entity framework to connect to the database. public class GetCustomerQuery : IQuery<Customer> { public string CustomerId { get; set; } } public class GetCustomerQueryHandler : IQueryHandler<GetCustomerQuery, Customer> { pu...
I keep forgetting that the standard join() can only take a single iterable, so I made a few functions that act recursively on any passed arguments. Somewhat ironically, the deep version of join() isn't called by the user, but only within the deep version of sum() - the standard sum() breaks and tells you to use join() ...
I'm writing code to compute a single value answer to a given numbers in integer array such that step sum is calculated till only 1 number is left. For example: Input: 3,5,2,6,7 Output is computed as: (3+5)+(5+2)+(2+6)+(6+7) It remains like this till I only have a single number left. 3 5 2 6 7 8 7 8 13 ...
I'm solving exercise 4 from Discussion 3 of Berkley's CS 61A (2012) (see page 4): Fill in the definition of cartesian_product. cartesian_product takes in two tuples and returns a tuple that is the Cartesian product of those tuples. To find the Cartesian product of tuple X and tuple Y, you take the first element in X a...
I am gradually completing the CodingBat exercises for Java. Here is the one I just did: Given an array of ints, return true if it contains no 1's or it contains no 4's. Here is my code: public boolean no14(int[] nums) { int oneCount = 0; int fourCount = 0; for (int i = 0; i < nums.length; i++) { ...
extension Array { func flatten<TResult>(transform: (T) -> TResult?, childArray: (T) -> [T]) -> [TResult] { var result = [TResult]() for original in self { let transformed = transform(original) if transformed != nil { result.append(transformed!) } ...
I am currently attempting to create a two SVG overlay / masking like the image below: I have created a SVG for the overlay. As it stands, I am trying to create two elements one for the green side and one for the blue side. For what I am trying to achieve, is this the best approach? If not, what is? Is it worth creati...
A long should be treated as a list of 32 unsigned numbers, each of them just two bit long. So 0x1234F... represents {0, 1, 0, 2, 0, 3, 1, 0, 3, 3, ...} and 0x55AA0... represents {1, 1, 1, 1, 2, 2, 2, 2, 0, 0, ...} Given two such lists, I need to compute the absolute values of the pairwise differences and sum them up....
Ι have the following database: SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET time_zone = "+00:00"; CREATE TABLE IF NOT EXISTS `Authors` ( `AutID` int(11) NOT NULL, `Name` varchar(50) NOT NULL ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1; INSERT INTO `Authors` (`Au...
I was able to run the form to update the data of the user profile, for the moment is in a rough version, but I know that can be improved. I post what I did, I hope you could help me to improve the code that definitely is unclear and with defects. //form update if ((isset($_POST['submit'])) || (isset($_POST['email'], $_...
I work on a .NET application that very loosely follows an n-tier kind of architecture (the business objects (not logic) and data access are split out). We are now looking to start refactoring the code into an MVP architecture. Based on some previous work done by someone else, I just refactored a screen into what I hope...
I'm using Python 2.7.5 in a GIS environment (namely: QGIS 2.8.1, or PyQGIS). sys.version_info(major=2, minor=7, micro=5, releaselevel='final', serial=0) The aim is to identify spatially identical Polylines (i.e. overlapping) and sum a value from a selected field. For other polylines with no matches, the code just rep...
I noticed there's some code on StackOverflow that is, to put it mildly, suboptimal. I'm posting here to see if we can provide a better solution. Here's a proposal for fixing it. The approach is to provide a small utility class with static methods, so it can be used just like Math.method(...). The standard deviation imp...
I have these struct(s) to keep data about temperature measurement: // data structure representing day struct Day{ vector<double>hour; Day(); }; Day::Day(): hour(24){ for(int i=0; i< hour.size();++i) hour[i]=not_a_reading; } // data structure representing month struct Month{ int month; vector<Day>da...
With the following Code I try to compare the content of two Worksheets. The first column contains a key that is unique and the following columns contain data that I want to compare (My data sets contain around 7000 rows and up to 40 columns). My question is if there is a way to make the code run faster. Since the prog...
I asked a previous question of this same program. I would like more opinions before I submit this assignment since I edited the program after receiving feedback last time. public class Room_Dimension { //Data fields private double length; private double width; //Constructor public Room_Dimensio...
I've coded a working implementation of the A* Algorithm however it's not meeting my performance expectations - it explores way too many nodes and takes a lot longer to find a route than I expect. private Vertex dijkstra(Vertex startLocation, Vertex endLocation, int routetype) { Long startTime = System.nanoTime(); ...
Given a multi-dimensional array representing a board in Sudoku, the function should be able to return whether the sudoku is valid or not. Examples: var goodSudoku = [ [7,8,4, 1,5,9, 3,2,6], [5,3,9, 6,7,2, 8,4,1], [6,1,2, 4,3,8, 7,5,9], [9,2,8, 7,1,5, 4,6,3], [3,5,7, 8,4,6, 1,9,2], [4,6,1, 9,2,3, 5,8,7], ...
Is there any better way to strip the time information in a DateTime Object than creating a new DateTime Object? For example, if I just want today's date and not time, is the only way is to do the following? DateTime now = DateTime.Now; DateTime Today = new DateTime(now.Year, now.Month, now.Day);
I've written a simple text game in Python to show you. I would be glad if you would spare a quick look and point out the style errors so I wouldn't pick up bad habits. """ A text game "Bob, the Cookie Cooker". """ import random COINS_FOR_WIN = 1000000 FINE_COOKIE_PRICE = 30 POOR_COOKIE_PRICE = ...
I decided to avoid the trivial isPalindrome lst = lst == reverse lst and tried writing a method with pattern matching and recursion. allButFirstAndLast :: [a] -> [a] allButFirstAndLast = tail . init isPalidrome :: [a] -> Bool isPalidrome [] = True isPalindrome [a] = True isPalindrome [a,b] = a == b isPalindrome lst = ...
I'm processing 2 DataTables: SSFE: Contains the values I want to find FFE: Is larger, smaller or equally large as SSFE, but does not necessarily contain every value of SSFE The values I need to match between these tables are integers, both tables are sorted from small to large. My idea was to start searching on the f...
So, I'm creating a chatroom with no 3rd party libraries and currently I'm logging people in like this: public void run() { try { this.running = true; ServerSocket ss = new ServerSocket(1000); while (this.running) { this.threadPool.execute(new InfoGrabber(ss.accept())); } ...
I have a method in my rails project that initializes a new user by copying some properties of another. The method should also retain entered parameters if saving the new user is rejected. Rubocop complains that Assignment Branch Condition Size for this method is 42.02/15. How can I improve this? def setup_user_clone ...
One fun feature that was added (fairly) recently in .NET is the [CallerLineNumber] attribute, which, in conjunction with [CallerFilePath] and [CallerMemberName] can allow for some very nice logging methods. I was thinking today, though, that they might be used for another interesting purpose. Consider the case where y...
I created a library class in CodeIgniter that handles building the HTML body view. This class builds the body, adds content and adds javascript element tags at the end. The body is built by using a layout, inserting the content to the appropriate hooks within the layout and finally the javascript. Layout, content and ...
I am working on a puzzle to find the minimum number of coins needed to buy a product. I am given three coins: 1 3 5 and also a number representing the price of a product: 11 The answer here would be three, since it takes at least three coins to reach this number. 5, 5, 1 I decided it was best to use Ruby's repeate...
I am new to Python and wanted to make sure my code answers the question for my assignment due. My Task: A priority queue is a queue in which each item is assigned a priority and items with a higher priority are removed before those with a lower priority, irrespective of when they were added. Integer values are ...
I found the following challenge online: Create a function that takes a string and returns that string with the first half lowercased and the last half uppercased. eg: foobar == fooBAR If it is an odd number then 'round' it up to find which letters to uppercase. That sounded easy enough but I found the last requiremen...
I have ridden to much about MVC and SOLID, so I have a mess in my head. I have written a small MVC application and I need your experience and sober mind. index.php - Start point of my app <?php require 'libs/Bootstrap.php'; $app = new Bootstrap(); $rover = new Index(); $rover->create('input.txt'); Bootstar.php - mini ...
I've been trying all night to get my fizzbuzz to use below 20 MB of RAM but I can't seem to get it much smaller than this. # Sample code to read test cases args <- commandArgs(trailingOnly=TRUE) test.cases <- strsplit(readLines(args[[1]], warn=FALSE), '\n') args <- NULL for (test in test.cases) { if (length(test) >...
I have written some code in Java that checks if the strings Firstname and Lastname are valid names. These are inputted by the user. My code works as expected, but I would like to optimize and shorten the code such that it is readable and understandable. Both these strings, Firstname and Lastname, will not be null or em...
I have a class that holds functions for caching using PHPFastCache. There are quite a few static functions in here and for each one I am declaring: $cache = phpFastCache(); Is there a better way I can do this? It just feels wrong. Below is the full class maybe there are other changes I can do. /** * Class Cache * Us...
This code has been developed with help on Stack Overflow. It is designed to compare two XML files and print the node for any differences (i.e if a entry appears in A.xml and not B.xml and vice versa). #include "pugixml.hpp" #include <iostream> #include <unordered_map> struct string_hasher { unsigned int operator(...
I am making an app that shows some pictures and you can like each picture. I am sending a POST request from the Android device. In my backend I have a Python script that takes parameters category and URL of the picture, opens a JSON file, and modifies the "likes" value. This is the Python script: #!/usr/bin/python # Im...
The class below will be used to track the execution time of various operations. There is no need to dip into C libraries to get formatted output then. Output would be something like this: 10 seconds 345 milliseconds 324 microseconds 23 hours 32 minutes 15 seconds 324 milliseconds It depends on the class initializat...
I want cache object for one value, which have two expiration limits. One "soft" limit indicating "value is old, but is still valid, but is good time for reload the value". And one "hard" limit indicating "value is old and reload is required". The cache will be used in web server and will be accessed from several reques...
HTML <table> <tr data-parent="0" data-id="1"> <td></td> </tr> <tr data-parent="1" data-id="2"> <td></td> </tr> <tr data-parent="1" data-id="3"> <td></td> </tr> <tr data-parent="3" data-id="4"> <td></td> </tr> </table> Where data-parent points to the data-...
I have been using Entity Framework 6, AutoMapper, ASP.NET Web Api and hit a few problems along the way, each time it was recommended that I could change my code from Inheritance to use composition design instead. After the last problem, and since the software is in early stages, I thought I would try the composition m...
The following is a set of classes that read metadata from Sql Server tables and populates local objects. It works, but I feel like there's too much duplication happening and too many places changes need to be made if something changes. On the database side, the relevant metadata is collected into 4 tables with an addit...
Problem statement Calvin is driving his favorite vehicle on the 101 freeway. He notices that the check engine light of his vehicle is on, and he wants to service it immediately to avoid any risks. Luckily, a service lane runs parallel to the highway. The length of the highway and the service lane is \$N\$ units. The s...
I'm trying to understand where my ruby implementation of this fails and hoping for an expert to shed some light on this situation. I've tried to make this a very simple example with the idea that setup is minimal. The Problem: I need to be able to log very quickly, ideally over UDP. Alternatively I can log to a file ...
I wrote this Console.Write function to use in my applications where I need to easily color-code output. Example syntax would be: Console.WriteLine("<f=red>this is in red"); Console.WriteLine("<b=gray><f=white>This is white on gray. <f=green>This is green on gray. <b=darkmagenta>This is green on dark magenta. <b=d>This ...
I am (still!) going through these CodingBat exercises for Java. Here is the one I have just done: Return an array that contains the exact same numbers as the given array, but rearranged so that all the zeros are grouped at the start of the array. The order of the non-zero numbers does not matter. So {1, 0, 0, 1} becom...
When developing a user interface that allows sorting by various different fields, I noticed that Array.prototype.sort() is extremely slow for large inputs. After some investigation, I found out that the problem was that my compare function was being called upwards of 8.5 million times for an input array of length 7500....
Here's a method inside my controller that reads the values of angle and point data from my database. Then it grabs the data and adds it to a new list and sends the JSON to the view. I can't simplify this simply putting my if statements into two ActionResults because I can only bind one datasource to one kendo grid. [Ou...
In Flatten to get all child controls of certain type in a UIView, methods were discussed to recursively flatten a tree-like structure in Swift, resulting in an array of all elements. Motivated by that thread, I have written a flatten function which creates a sequence instead. This can be an advantage if the resulting e...
Today I thought about Factory Design Pattern in Swift, and I do an implementation with Extension. My post is about if anyone have any observation or issue about this implementation violate any convention about Factories? Can I do this way? I did it because I thought the statics function in my object not smell good, and...
This is my first serious programming effort, so I'd like some comments about what I did so far. Project structure: / |--App/ |--Backend/ |--Common/ |--Configuration.php |--Route.php |--Frontend/ |--webroot/ |--assets/ |--index.php |--public_html -> link to App/webroot/ |--vendor/ |-...
I'm working on an iOS app which handles API request based on authentication. Authentication is done through OAuth and every API request is sent along with access_token. In certain cases, the access_token might be expired causing the API request to fail. I would need to call the refresh_token method to refresh the acces...
I am completing the CodingBat exercises for Java, and, having learnt from the answers to the previous one, I completed the one that follows: Return a version of the given array where all the 10s have been removed. The remaining elements should shift left towards the start of the array as needed, and the empty spaces a...
I know there are other ways to create a login script like Object Oriented, Prepared Statements and PDO, but how about those old MySQL PHP users like me trying to change from old style to the new ways? Here is a login script code I created for those like me changing from MySQL to MySQLI the easy way. Please take a look ...
I have a function that converts an integer to its binary representation. I am wondering if there is any way I can improve the function. public List<string> Conversion(int x) { var bitConversion = new List<string>(); var result = x; while (result >= 0) { if (result == 0) ...
Using this page for a starting point into comparing MD5 hash values from files in two different folders, I've put something together that outputs either Copied if both files MD5 matches or Check if the MD5 hashes do not match. I want to find out if there's a better method for accomplishing this. #Requires -version 4.0 ...
For minesweeper algorithm, instead of the most obvious BFS or DFS solution, I want a O(1) space solution. First of all, I'll explain how the program works. I will pass in a 2D array, with 1 represent mine and 0 represent blank space. The program return true if the map can be opened with single click. Return false if i...
I am trying to implement a shutdown method in queue implementation. I took the code from BlockingQueue source from Java and trying to check the shutdown method. Will the following code be thread safe and an acceptable implementation? import java.util.concurrent.atomic.*; import java.util.concurrent.locks.Condit...
Would you have any suggestions for improvements for the code below? def my_transpose(arr) # number of rows m = arr.count #number of columns n = arr[0].count transposed_arr = Array.new(n) { Array.new(m) } # loop through the rows arr.each_with_index do |row, index1| # loop through the colons of one ...
After a discussion of which users were from Australia, I wrote my first SQL query to find out: SELECT u.DisplayName'Display Name', u.Reputation'Rep', u.Location'Location' FROM Users u WHERE u.Location LIKE '%Australia%' ORDER BY 'Rep' DESC As always, please tell me the good, the bad, and the ugly. The query can be fou...
I just wrote a small class that generates perfectly unique colors(or that is the plan anyway). I found the original index shifting snippet online, and was just wondering if it could be improved in anyway, or if any problems could arise from using it. Here is the class which is used to create the unique colors. public c...
I am looking to enhance my VBA skills and efficiency with the code below. It currently executes at about 20 minutes. I just recently learned how to use public functions but this project is very robust and I haven't been able to make it more efficient. I've cut off two Case requirements {Auto - Sentra/Van Fleet ($) ;...
I am working my way into learning a bit of Scheme (actually, Racket) with the help of a few practical problems to solve. In this case, I want to split a flat list of symbols at a certain delimiter symbol, discarding it and returning the list of split chunks. #! /usr/bin/racket #lang racket (define (split lst del) ...
I have written two Perl subroutines to flatten and unflatten a complex hash or array key. This can be useful in situation when you are traversing/parsing a complex data structure like JSON and want to store a given complex key to be later used as an index into a modified data structure. The reason for writing this, is ...
I've created two simple methods: one to instantiate a new XMLHttpRequest object and open the request and another to handle the request. Can you please point out improvements that can be made or any shortcomings in my code? ajax: function(opts) { var xhr, method, body, constructor; xhr = new XMLHttpRequest(); m...
I decided to learn a Lisp-ish language and I am discovering a very weird and new syntax. The obligatory first program, that also uses all the fundamentals, is the number guessing game. Did I define too few or too many constants? Is my code properly spaced and indented? Is there a cleaner way to exit the loop than err...
I wrote this program to determine the Greatest Common Factor of any 2 given numbers, and would like to know of any improvements that can be made. I have tested it using a loop and 2 randomly generated numbers and it seems to work perfectly: import java.util.ArrayList; import java.util.Scanner; public class GreatestCom...
I wrote this code, called arrayHistogram, that would generate a random number within a set range, and print it in an array randomIntArray. It would then make another array arrayHist that would count how many times each number in randomIntArray occurred. The program works, but, I feel I have a few semantic errors in the...
I made a class to manage saved file in drive with Swift, and I tried to do the best work. Can someone get me a feedback about this class? What can I improve? Is this a good way to save a file? import UIKit class TCFileData:NSObject, NSCoding { override init() { } required init(coder aDecoder: NSCoder) { ...
I know this has been done a million times before, but this is my implementation of bubble-sort, insertion-sort, merge-sort, heap-sort, and quicksort. Any feedback on how to make it better would be most appreciated. Also, I seem to have a large number of functions in the code before main(). Is it preferable to put th...
I got bored had time to kill in work and was creating a few things using plain JS (no frameworks allowed! I wanted to get used to progressive enhancement). I realized I would run into a problem if I wanted to access things in other scopes that might be loaded after my current file, and I didn't want to have to explicit...
I finally solved this challenge with using recursion and figured out why the automatic scorer wasn't passing my previous solutions. I was using NSMutableArray to store the numbers and with N=18 I was running out of allowed memory by codeeval.com. I rewrote the code using integer arrays and I received 100% but still th...
I know that Python has a built-in list data structure, but I want to implement my own linked list and stack data structures for practice. I have three classes Node, Stack and List. The code works, but I feel there is a better way to do this. I would like to have some general critique. class Node: def __init__(self...
So, sᴉɔuɐɹɥԀ suggested I write a SEDE query to find first questions with answers posted within 24 hours, and here it is: WITH QData(OwnerId, CDate) AS ( SELECT Q.OwnerUserId [OwnerId] ,MIN(Q.CreationDate) [CDate] FROM Posts Q WHERE Q.PostTypeId = 1 AND Q.OwnerUserId IS NOT NULL GROUP BY Q.OwnerUserId ), Fi...
I have a program which reads and analyses MPEG-TS files. I've been using gperftools to identify hotspots and optimize them, and 45% of all samples at this point are in my main bitstream reader function. I've already: Reduced the number of overflow checks to one per call (not shown here, since the overflow check occurs...
I am using below code to recognize which set up I need to use in Codeigniter: $dev_urls = array('dev.com'); $prod_urls = array('prod.com'); if(in_array($_SERVER['HTTP_HOST'], $dev_urls)){ define('ENVIRONMENT', 'development'); } else if(in_array($_SERVER['HTTP_HOST'], $prod_urls)){ define('ENVIRONMENT', 'produc...
I have written the following utility, as my first non-tutorial program in Go. The purpose of the utility is to connect to a torque/force sensor (aka load-cell) via UDP; to send an initialization command; and to record the resulting stream of measurements. Since I am planning further functionality (setting duty cycle ...
The Aim Since I very rarely write code to do things other than business logic anymore I've set myself a challenge: Split a string into a list of substrings by splitting on a matching string, without using string.Split() or similar methods of string (substring, indexof, etc) or LINQ methods (edit or regex /edit). The me...
I am completing the CodingBat exercises for Java. Here is the one I have completed just now: Given n > = 0, create an array length n * n with the following pattern, shown here for n = 3 : {0, 0, 1, 0, 2, 1, 3, 2, 1} (spaces added to show the 3 groups). Here is my code: public int[] squareUp(int n){ ...
I am using the below function to set month information on context passed. It is working fine, but please review it and let me know if there are any potential flaws or any improvements in this code. /* Expects month to be in 1-12 index based. */ var monthInformation = function (year, month) { /* Create a date. Usual...
I want to throttle asynchronous actions at a specific maximum rate of n actions per t period, and have pending actions wait until there is a free slot (rather than drop them). I want to receive the outcome When an action completes or fails. I also want the option of cancelling an action. The order of actions is unimp...
Please help me review this code. I want to make it both accurate and more Go-styled. Go Playground code package main import( "fmt" ) type TreeNode struct { val int left *TreeNode right *TreeNode } func isSameTree(p *TreeNode , q *TreeNode ) (bool){ if p == nil && q == nil { return true ...
I wrote a script that one way encrypts a user's password by generating a key, and multiplies by the ASCII value of the character and the ASCII value of the key character at (the position that the character has in the password string) and repeats this for the previous positions in the string meaning a key string with AS...
Based on the excellent answers provided for my previous question, I've thoroughly revised my attempt at "deep" versions of all, any, etc. It uses the recommended encapsulated flattening function, and streamlines some unnecessary stuff. def flatten(*sequence, preserve=False): for item in sequence: try: ...