instruction
stringlengths
71
71.9k
I'm working on a basic strategy game for iOS and I have a question about the overall layout of the code in the program. I added some features to the game today and I had to add code to several different places to get the features to function properly. In general I think I am doing things correctly, but I fear I am fa...
This is the function I've implemented in an answer to this question. I've tried to make this as simple and idiomatic as possible, using C++11. Could this still be improved in any way? #include <algorithm> #include <cstdint> #include <iostream> #include <iterator> #include <vector> typedef std::vector<int> SplitValu...
Last semester in my Masters Program I developed this code for sieving. My professor wants me to write a report that he might use locally within the school, but I feel like I've done nothing that new, despite coming up with my algorithm without doing any research other than the bare numbers. Essentially it skips over a ...
I'm becoming acquainted with ruby by taking some of my legacy shell scripts and rewriting them as .rb. The pattern that is emerging is that I have a number of different dumb tasks, that do what they are told, and a coordinator that is responsible for ordering the tasks, and providing to the tasks the data that will be ...
Please take a look at this Fiddle. Is there a better way of building a table with titles in the first cell of each row, like this: <div id="area"> <table> <thead> <tr> <th></th> <th>A</th> <th>B</th> <th>C</th> </tr> </thead> <tbody> <tr> <td>Germany</td> <td>Yes</td> <td>No</td>...
Finding the nearest polygon out of a list of polygons seems to be quite a challenge on performance, due to lack of optimization. Consider the following image: I'll give the concept behind this. The "purple" pointer under the mouse is an entity and each blue blob is a polygon. The red ring denotes the nearest polygon, ...
I have a own made grid system and made a jQuery function for that to check if there are not too many columns in each row. If so, delete the HTML code of the row. Normally in my grid system, there fits 12 columns in 1 row, but I can change that. In HTML, I've written them like this: <div class="row"> ...
How to make the following code more efficient? """ Calculate the posterior distribution of p(pos|word) using Baye's rule: p(pos|word) \propto p(word|pos)p(pos). """ word_pos_dict = defaultdict(float) # Example, word|pos -> 0.0012 pos_dict = defaultdict(float) # pos -> 0.005 pos_word_dict = defaultdict(float)...
First, I'm in no way an experienced PHP coder. This is my 5th time working with PHP, so if you see anything that can bee improve, please point them out for me. I have the code checking for the $_GET variable and use them to create the page title: <?php $pgeName = safeVal(basename($_SERVER['PHP_SELF'], '.php')); $pgeBr...
I've just started learning Swift. I started with an example of RSS feed parser. I have a wrapper class written in Objective-C which converted the XML response into NSDictonary. I'm using the NSDictionary returned from my wrapper class. Then I need to iterate through the NSDictionary and fetch all the title and display...
I am doing a validation and I believe that there are many things that can be reduced or removed. I am still re-working this. But I am looking for some experts to look at my code and offer the very best approach for both individual and form submit error handling. (function(){ var calledIt = function (event, params...
Wrapper: internal static class Cache { private static ObjectCache InternalCache { get { return MemoryCache.Default; } } private static T CacheOrGetExisting<T>(string key, Func<T> valueFactory) { T value; object uncastedValue = InternalCache.Get(ke...
This challenge is from Talent Buddy: Tweets per second Japan Castle in the Sky airing broke a Twitter record on August 3, 2013. At one point during the classic anime movie showing, people submitted 143,199 tweets per second. This particular spike was about 25 times greater than Twitter’s steady state. Given an a...
I'm new to Python, with some background in Java and C# from a while ago, and more recently in scripting worlds like Bash and AppleScript. I wanted to be able to create classes that could report their instances limit their number of instances. Synthesizing various answers from Stack Overflow and general trial and erro...
I'm working on a photo website, the markup looks like this: <div class="gallery"> <figure> <img src="photo1.jpg" /> <figcaption>Photo 1</figcaption> </figure> <figure> <img src="photo2.jpg" /> <figcaption>Photo 2</figcaption> </figure> ... </div> I've come up with so...
I have a Servlet that makes an EJB call to a backing server which takes about a second to return some data that changes reasonably regularly. I can't cache the data on the servlet-side, so I have decided to put the call to the EJB into a separate thread and use a Future to get the data as late as possible. There is no ...
In a Win Form I'm doing initial validation in the Form. So before saving data, I want to validate whether all the required fields are filled (Text Boxes) by the user. There are about 18 such Text Boxes in the Form. Currently I'm doing it as follows. To make the code short only three fields are shown in the code. p...
I'm the the process of adding change auditing to my existing DB class which encapsulates database calls. Previously I would just pass in a String and a SqlParameter array but now I've added the class 'DBData' to contain the values required for the auditing. I'm not sure whether passing in this DBData object and then ca...
I would like to give an Integer to whatever demands it. For that I use the following code public class IntIDGenerator { private static int sequence = 1; public synchronized static int generate(){ sequence++; return sequence; } } It is thread-safe because the synchronized term in the meth...
Assuming an app has many display styles, fonts, colors, etc., and that we never want to hardcode values, I've created an AppVariables object that houses properties for all of the necessary styles in my app: class AppVariables: NSObject { /** * Fonts */ let UIFontPrimary10 = UIFont(name: "Heiti TC", s...
This is my solution to the competitive coding question on SPOJ here. It gives a runtime of 0.24 but the best solutions posted have a 0.0 runtime. How could I possibly achieve better results than this? #include<iostream> #include<cstdio> using namespace std; int rev(int num) { int rev_num=0; while(num) { ...
We all know that math notation is idiosyncratic. Canonical representation of math objects often have irregular grammar rules to improve readability. For example we write a polynomial \$3x^3 + x^2\$ instead of more uniform but more verbose \$3x^3 + 1x^2 + 0x^1 + 0x^0\$. When a coefficient equals 0, you don't write the t...
I wrote a simple generic intercalate function (that should be semantically equivalent to the Haskell intercalate). template <typename Fwd_It, typename Out_It> auto intercalate(Fwd_It first, Fwd_It last, Out_It destFirst, Fwd_It whatFirst, Fwd_It whatLast) { if (first == last) return des...
This is a TalentBuddy Challenge Your task is to write a function that prints to the standard output (stdout) the highest number of tweets recorded between each second in the array and the past windowSize seconds before it Note that your function will receive the following arguments: TweetsPerSecond which is an arr...
I am solving linear advection equation in order to learn parallel programming. I am running this code on Xeon Phi co processor. Below is a plot of how it scales up with increasing number of threads. I am still in learning process and this is my first "parallel" code. I am also not very familiar with architecture specif...
This is a derivative post from here. This is just a general review, so the question is the same: Is there something... That you would consider as a bad practice and why? That is just bad in some other way? This question applies to the function toRowEchelonForm(matrix, returnMethod). (Just to be clear, this is not a p...
The following script is being run with a cron. It runs once a minute to see if there is a reminder that needs to be sent. Should I make this run once every 30 minutes? The choices to send a reminder are, up to 12 hours: 30 minutes 60 minutes 90 minutes 2 hours Could this script be optimized/written differently? <?ph...
I was just wanting a code review on this image slider I made. I don't have anyone else to give me their opinion on the code I write outside of work. Is this sloppy? Is it wrong? Is it ineffective? Does it have bad performance? You can see my repo on the slider here. deitySlider.js var deitySlider = { init: fun...
I was tasked today with cleaning up data from a SSRS report put together by a DB programmer. The original report was to find duplicate serial number sales within a user-defined period of time. I was given an Excel file with the result data set and it smelled really funny, so I decided to go into SSRS and find out what ...
I completed a challenge of codeeval called BayBridges. It can be found here. I have uploaded my code on GitHub here. In summary, the challenge is to take a list of line segments, each specified by its endpoints in [latitude, longitude] format, and find the largest subset such that no pair of line segments intersects. ...
I'm doing a small FastCGI application in C and I've created this template system to keep the design away from the code. There's a binary tree containing all possible first characters, each node points to another binary tree containing all characters that can appear after it. Some nodes have the replacement, when they a...
HTML code for Add New button: <div> <a data-toggle="modal" href="#addnewDepartment" id="add-new-department-btn">Add New</a> </div> <div> <a data-toggle="modal" href="#addnewVehicle" id="add-new-vehicle-btn"> Add New </a> </div> Modal Dialog frames: <!-- Adding New Department --> <div class="modal fade" id="...
I tried to recreate a mini game (not sure about its name, I call it b10k) with 2048 looks, therefore it looked better if I use html elements, and I really am not good at working with them, but I tried: https://github.com/Cicada3301/b10k I could also find out that there is a bug that sometimes doesn't update the player'...
Actually, I just have no ideas. How can I make breaklines to make it more readable? Can anyone suggest ways on improving this? module TestingDataLoad def get_files_from(search_target) Dir[search_target].each do | d | testing_files={} if File.directory? d Dir.glob("#{d}/*json") do |file| ...
I made this method that takes any string and transforms it into a multiline text l; each line having the max (character) length specified by the rowLength parameter. How can I make this better, functionality and code wise? There is currently one known issue. It sometimes adds an empty line at the end because I have to ...
In input validation I'm using this validation method in my all Forms. Here I have a single handler for all TextBoxes in my Form and if I have other controllers like ComboBoxes I would use a separate handler for all ComboBoxes and so on. My only doubt in this approach is how users would feel about this as you can't foc...
I wish to locate the closest matching NxN block within a WxW window centred at location (x,y) of a larger 2D array. The code below works fine but is very slow for my needs as I need to run this operation many times. Is there a better way to do this? Here N = 3, W = 15, x =15, y = 15 and (bestx, besty) is the centre of ...
I have produced a working menu component for a project I'm working on, but would like to reduce the amount of code used and improve the methods - especially in the Paint implementation - still further, I feel like the function I've used and the way I've passed the variables to it is a bit 'hacky' - IOW, I bodged it. Wh...
Following code validates NIC number of a person (National Identity Card, no like SSN) Requirements are... Length should be 10 digits or characters All should be digits except the last one Last one would be x or v in simple letters Currently I'm using following method and its working. I just want to know that could th...
I want to create a form with a country drop down list so I can just google and get all the countries but the question should I just encode it statically or generate dynamically with PHP. (Note it doesn't have to be necessary country list just any static list with lots of data) HTML Example: <select> <option value="AF...
I'm following this let StringOfLengthConstructor<'c> (input:string, length:int, defaultConstructor:string->'c) = match input with | null -> None | x when x.Length = length -> Some(defaultConstructor(input)) | _ -> None type String3 = | String3 of string let String3 input = StringOfLengthConstructor<Stri...
I'm curious whether checking for null is redundant in this concrete example. public LoginJob(@NotNull String login, @NotNull String password) { super(new Params(Priority.NORMAL).requireNetwork().persist()); Preconditions.checkNotNull(login, "login is null or empty"); Preconditions.checkNotNull(...
I've recently made a calculator using Java and Swing. I'm okay with the results but I'm curious what are the major flaws I've made (assuming there are, because it is my first program making GUI). I can't think of a fancy way for not duplicating code in the function action listeners classes. Which other good-practice-ru...
How would you name this function (I gave in a name pipe in the example) which constructs combines a chain of functions with a single attribute into a single callable: # Python def pipe(*functions): """ pipe(c, b, a)(value) == a(b(c(value))) """ if len (functions) == 1: return functions[0] de...
Exercise 5-4 Write the function strend(s,t), which returns one if the string t occurs at the end of the string s, and zero otherwise. #include <stdio.h> int str_end(const char *, const char*); int main(void) { char *s1 = "Man is a rope stretched over an abyss."; char *s2 = "an abyss."; printf("%s\n", s...
Here is a login system I am working on. I just want an opinion on it and whether I am going in the right direction or am just completely missing something. The main thing I would like to know is: am I initializing my user session IDs correctly? Basically once the user enters their credentials, the system goes into the...
I have a shell script to configure Synaptics touchpad settings at login. Background You configure the touchpad with the synclient command. Its usage is synclient [-lV?] [var1=value1 [var2=value2] ...] For example: synclient PalmDetect=1 — to set a single setting synclient PalmDetect=1 PalmMinZ=10 — to set multiple ...
I am not sure if I am approaching this task the correct way. I have a view model with multiple string properties. I pass the model through an interface to a service class that contains a void to repopulate the user input with my desired format. using System.Globalization; using System.Text.RegularExpressions; using S...
Calculating probabilities in Minesweeper might sound like an easy task, but I've seen so many probability calculators that's either incorrect, horribly slow, or with ugly code (or all of them) so I have to share my code for this. This code is used within my Minesweeper Flags online game by the AIs AI_Hard, AI_Extreme3 ...
The code is the view part of my bookmarker - project for managing bookmarks by categories. It uses Python 3.4/Django 1.6. I have also included models.py for reference. The code does the following Providing relevant autocomplete JSON data Providing details of categories/bookmarks (both are DB models of my project) Open...
My application has a fairly important query that is used in a lot of places. Unfortunately it takes about 14 seconds to run, so I'd like to find a way of possibly improving it. The application receives incidents (right now there's about 70,000 total incidents, and about 16,000 incidents in this query), with each incid...
I am posting this question for input on comparisons between other sieving methods and opinions on what I have discovered. I believe this might be the fastest (singular, non-threaded) array implementation of prime sieving to date, correct me if I am wrong. My rudimentary benchmark tests stand as follows: My optimized c...
This is being used now, seems decent to me but I'm curious. if (m=s.match(/^\s*(https?:\/\/[^\s<>"]+)\.(bmp|png|webp|gif|jpg|jpeg|svg)\s*$/)) { // example s: http://mustachify.me/?src=http://www.someImage.jpg return '<img src="'+m[1]+'.'+m[2]+'">'; } if (m=s.match(/^\s*(https?:\/\/[^\s<>?...
I am working on a ground-up rebuild for an app that has a relatively simple purpose. Users can view/favorite entities that are backed by a RESTful API. I own both the client code as well as the API. For this rebuild, I wanted to refactor the networking code out of my view controllers and hopefully move my codebase towa...
Inversion Count for an array indicates – how far (or close) the array is from being sorted. If array is already sorted then inversion count is 0. If array is sorted in reverse order that inversion count is the maximum. Formally speaking, two elements a[i] and a[j] form an inversion if a[i] > a[j] and i < j Example: Th...
I am looking for a review of my code that implements a MyQueue class which implements a queue using two stacks. public class MyQueue<T> { Stack<T> stackNewest, stackOldest; public MyQueue() { stackNewest = new Stack<T>(); stackOldest = new Stack<T>(); } public int size() { return stackNewest.size...
CSS and responsiveness in multiple columns with fixed and scaleable elements can be done in many ways. I have created a solution that seems to work, though I have no idea whether this is best practice. Fiddle CSS html, body { margin:0 auto; padding:0; background: #fff; text-align: center; } /* Clearfix ==============...
I was bored and burnt out on more serious projects.... until I saw this Computerphile video on YouTube. Now I'm inspired again. Now I feel like spending some time implementing that recursive algorithm in a little console program. Fortunately, recursion is unbearably slow in this case. So, I ended up writing a small cla...
My concerns with this code: Is there a more efficient way to find files by pattern in Python? Does os.walk() work in Windows? Is this code pythonic? Should search() be broken down into 2 functions? Is it stupid to handle IOError exception by printing the error msg to the console? #!/usr/bin/env python ''' Findin...
I recently made a webcrawler that I submitted here for a review: Minimal webcrawler - bad structure and error handling? With that help, I've made a much cleaner and better(?) webcrawler. The only problem I have is that this crawler is extremely slow compared to the other one (13.2s for a depth of 5, compared to 1.3s on...
I've written a DNS tool in Node and would like to know if there's a better and more efficient way of handling the conversion from an IP to a long. I'm not too good at bitwise just yet and would like to hear any suggestions. Psuedo-code has been provided below. var _parse = function (ip) { var octets = ip.split('.'); ...
ids contains 100 ids that are comma delimited. Is it fine or does it need improvement? def getFriendPoints(ids: String) = { DB.withConnection { implicit c => try { var pointMap:scala.collection.immutable.Map[String,String]=Map() var i=ids.split(",") for(pos<-0 to i.size){ val...
This particular example is verilog, but my question is more about the state machine structuring, which would be relevant to both VHDL and verilog. So if I have a state machine, this one is fairly simple: always@(posedge m_axi_clk) begin if(m_axi_resetn == 0) begin current_state <= S_IDLE; end else begin ...
I have written a small application that lets the user search drives for their given input string. I am only returning the full name of files. What I have now is the following method to retrieve those full names: private IEnumerable<string> FindOccurences(string searchQuery, DriveInfo drive) { return drive.RootDirec...
I have the following code which attempts to match all strings like "*SOMESTRING" (which can include numeric values), but not "*SOMESTRING*". For this I am using a negative lookahead as follows;*SEX and *AN01ZORA should match, \*PCCL\* should not match. string s = " if 'L,....' MDC = '13' Then " + " if 'B,...
Consider this interview question: Given a Node with a reference to a child, its next, its previous, and a variable for its value (\$\frac{1}{2}\$ tree, \$\frac{1}{2}\$ doubly linked list structure), you have to find a way to flatten the structure. 1 = 2 = 3 = 5 | | 6 = 7 8 | 9 (refere...
Based on my previous post I completely re-factored my code to make it object oriented. Anything I could improve when it comes to: Object oriented code; Efficiency; Readability. Any other suggestions are also welcome! Validator class: class Validator { private $rules = []; private $errors = []; public fu...
I have this piece of code I've been working on for quite some time. It's a ListView with a search filter. Inside each row, it contains a user Image, a User's name and how many friends they have in common. Also the row contains a button each, for actions. I'm just indeed of some code refactoring, maybe some guidance? Di...
How to do optimization and provide less of code here: for _ in _get_valid_json(): if _['size'] != '': available_params = [ {'productSku': _['upcID']}, {'productUPC': _['upc']}, {'productColor': _['color']}, {'p...
My users may need to supply a 'disease category' to my site. I need to let them use all alphanumeric characters, hyphens and single quotes. Would someone review this to see if they feel it's reasonable safe? I'm very happy for suggestions to make it tighter, $disease_category = "some user input"; $reg = "#...
I recently bought this math-based boardgame for my little cousins, and am now trying to verify its design with some MATLAB code. The relevant parts of the game are: A board with numbers from 1 to 100 in one tile each, and each tile colored in one of nine colors There are three dice, the usual kind (1-6) In your ...
On a programming contest I came upon this question: Given a partially played 3 × 3 tic-tac-toe configuration, write a program to determine which player will have a better chance of winning if the game is continued, with player "x" playing next. The players are dumb robots and will pick an empty square randomly. Output...
I am working on this problem: Stacks Imagine, that you are employed by a software development company. You work now on the famous "D++ project", which is devoted to the creation of a new generation programming language. Your particular task is quite prosaic, though. You are to develop the memory manager being ...
I have a search-function, that searches for specific data within a huge Object. Depending on how good a found entry matches, the finding gets "matchPoints" (or "Priority") var findings = {}; for(var element in hugeObject){ var points = getMatchPoints( inputToSearchFor, hugeObject[element] ); if( points !== 0 ){...
I have a large file that I want to refactor. My idea is to make helper classes with helper methods so that I can modularize methods. Is that a good idea? For instance before refactoring: public void collision(PhysicsCollisionEvent event) { if (event.getObjectA() instanceof BombControl) { final Spatial node...
Given a set of non-negative integers, and a value sum, determine if there is a subset of the given set with sum equal to given sum. On similar lines, Partition problem is to determine whether a given set can be partitioned into two subsets such that the sum of elements in both subsets is same. Complexity: \$O(n \tim...
Given a set of \$n\$ integers, divide the set in two subsets of \$\frac{n}{2}\$ sizes each such that the difference of the sum of two subsets is as minimum as possible. If \$n\$ is even, then sizes of two subsets must be strictly \$\frac{n}{2}\$ and if \$n\$ is odd, then size of one subset must be \$\frac{n-1}{2...
Background My lab administers four computer programs in three separate appointments. At each appointment, the subject does the programs in a pseudo-randomized order. Also, three of the programs have subversions, which are also pseudo-randomized so that the subject could do type A of program 1 at the first appointment, ...
I like Ruby's string multiplication so I thought I'd see if I could do it in Swift. I came up with these implementations: @infix func * (left: String, right: Int) -> String { var result = "" for _ in 0..right { result += left } return result } operator infix ** {} @infix func ** (left: String...
Today's code is a filtering streambuf (and associated stream type) to automate word-wrapped output in C++: #include <iostream> #include <streambuf> #include <iomanip> class widthbuf: public std::streambuf { public: widthbuf(int w, std::streambuf* s) : indent_width(0), def_width(w), width(...
Mostly asking for critiques of vulnerability. Am I using any functions or methods that are unsafe? <?php $menu = array( "page1","page2","page3" ); $defpage = "page1"; $section = $defpage; if ( isset( $_GET['section'] ) ) $section = $_GET['section']; if ( !in_array( $section, $menu ) ) $section = $defpage; ?> This is ...
I wrote a variation of the Caeser Cipher and would like some feedback. Is it idiomatic? Can you generally see anything that can be improved? Use example: let e = enc "Hello World" "This is the key" in dec e "This is the key" Instead of taking a single value as the offset, it takes a String as the key and uses each re...
I'm in the process of working on a client's site. I have a section containing a ul with list items and a div containing the slides that are triggered when clicking on an li item. For instance, <li id="nav-one">Item One</li> triggers <div id="slide-one">...</div>. Here is the jQuery portion: var slidesNav = $('#slides-n...
Recently I've been wondering about ways of implementing objects in code that can be represented by other primitives. An example of this is a Vector, which can be represented by a Vector\$N\$D where \$N\$ is the dimension of vector, or it can be represented by an \$N\$-tuple. The reason this is causing me so much trou...
In an attempt to practice conditional statements in SQL I decided to design a tic-tac-toe game with MySQL. Let me know if you think any of the steps could be done better. Step 1: Create the game board: USE test; DROP TABLE IF EXISTS TicTacToe; CREATE TABLE TicTacToe ( ID INT NOT NULL, A VARCHAR(1) NULL, ...
v2 of this question is here and v3 is here To get a better understanding of C++11/C++14, I thought I would develop a thread pool, even if it has been done to death! The only dependency outside of the standard library is boost::lockfree::queue. threadpool.hpp #ifndef THREADPOOL_H #define THREADPOOL_H #include <atomic> ...
Introduction: The following two code samples are a direct comparison of performance between Cython and C++. I pieced them together with the help of others-- I barely understand how they work. Their speed in my computer is: 1.225s vs 3.989s (C++ being the faster). The purpose of this comparison is to decide which langua...
I updated my class with more functionality, but I kind if feel like it's a mess or that it can at least be improved by a bit readability, efficiency and/or DRY wise. Anybody who could see if that can be done? Any other suggestions are also welcome. class Validator { private $errors = []; private $rules = []; ...
I have the following UserServiceProvider and I'm wondering whether so much dependency injection is overkill: use Illuminate\Support\ServiceProvider, App\Repositories\Eloquent\User\EloquentUserRepository, App\Repositories\Eloquent\Profile\EloquentProfileRepository, App\Repositories\Eloquent\Seller\EloquentSellerReposit...
Given an unsorted array of integers, you need to return maximum possible \$n\$ such that the array consists at least \$n\$ values greater than or equals to \$n\$. Array can contain duplicate values. Sample 1 input : [1, 2, 3, 4] output: 2 Sample 2 input : [900, 2, 901, 3, 1000] output: 3 What do you folks thin...
#!/usr/bin/env python ''' Search for files using wildcards amd magic ''' import os from fnmatch import fnmatch import sys import argparse import magic def cmd_args(): ''' returns a argparse namespane ''' parser = argparse.ArgumentParser() parser.add_argument( '--root', default='.', help...
Given an array, print the Next Greater Element (NGE) for every element. The Next Greater Element for an element x is the first greater element on the right side of x in array. Elements for which no greater element exist, consider next greater element as -1. Examples: For any array, rightmost element always has next gr...
Learn You a Haskell gives an exercise to implement the following function: -- make a function that simulates tossing a function 3 times import System.Random tossCoin3 :: Int -> (Bool, Bool, Bool) tossCoin3 x = let (num1, gen1) = random (mkStdGen x) :: (Int, StdGen) (num2, gen2) = random (gen1) :...
I'm following up on this question. I made a few decisions about my model and implemented recommendations accordingly. TL;DR the link Uses a loop algorithm to return a Fibonacci number \$Fn\$ of any given ordinal position \$n\$. Changes I'm now using a BigInteger type to avoid Integer Overflow. I can now return an ar...
I'm trying to optimize my code (time optimization) based on this problem: Let S be a set of strings. Each string in S is associated with a set of elements. Consider, for example, S = {"home", "tree"}. Implement a data structure that is a collection of sets and supports the operations Union, Move and Print. Initi...
Giving the following example list the task is: find out whether the second expression is in the first one. * shall be considered as a wildcard for any character and one should be able to escape it \* Hello,ell This is good, is CodeEval,C*Eval Old,Young should evaluate to true true true false I wrote the followi...
I'm playing Code Hunt on level 2.06 (loops). This level is about counting the number of "a" in a String. public class Program { public static int Puzzle(String s) { int ret = 0; for(int x = 0; x < s.length(); x++){ if(s.charAt(x).equals('a')) ret++; } return ret; } It actually works, but the game sco...
Old code: Login system security This is an update on the code and suggestions I received from generous users on the old thread. So same rules apply, just check it out, tell me what you think. Is it better or worse? is the security getting better and if so what else can I do to make it better? Are the sessions correctl...
Learn You a Haskell presents the randoms function. I implemented it as follows: -- randoms that takes a generator and returns an infinite sequence -- of values based on that generator import System.Random randoms' :: StdGen -> [Int] randoms' g = num : randoms' gen where (num, gen) = random g Please critique it....
The subset size should be greater than or equal to 2. How can I speed up this code? #include<stdio.h> #include<stdlib.h> #include<math.h> #include<malloc.h> #include <iostream> #include <vector> long long int set[100000]; long long int counter, j; long long int ans,min,count; bool ha; long long int pow_set_size; long ...