instruction stringlengths 71 71.9k |
|---|
I'm just at the beginning stages of making a simple chess engine. I have a function that when passed the x and y coordinates on a 2D list can enumerate all possible moves for a piece. It assumes there are no other pieces on the board, and that all moves are possible (see example list of moves below) and a separate func... |
This code validates the following:
enddate should not be less than or equal to startdate.
startdate should not be less than or equal to the date today unless document.getElementById("ltype").value == "1".
The maximum gap between startdate and enddate is one year, more than that should cause an error alert.
Please rev... |
My goal is to remove whitespaces from string elements of my list, and to remove empty string elements altogether. My code:
def modifylist(lst):
lst = [elt.strip() if type(elt) is str else elt for elt in lst]
while '' in lst:
lst.remove('')
return lst
Is there any other method th... |
I have the following code:
for j in range(rows):
for i in range(cols):
k = j * rows + i
k1 = k + 1 if i < cols - 1 else k - 1
k2 = k - 1 if i > 0 else k + 1
k3 = k + cols if j < rows - 1 else k - cols
k4 = k - cols if j > 0 else k + cols
w1 = U[k]
w2 = U[k-... |
A tourist wants to make a good trip at the weekend with his friends. They will go to the mountains to see the wonders of nature, so he needs to pack well for the trip. He has a good knapsack for carrying things, but knows that he can carry a maximum of only 4kg in it and it will have to last the whole day. He creates ... |
I am writing a solved for 15 puzzle game which will find the solution path to any NxN board. For easier boards the algorithm works great solving almost any 3x3 boards, most 4x4 boards, but when I go 5x5 and higher I will often run out of memory. This is the implementation:
@WorkerThread
public Solution findPath(Board b... |
I was solving this question on a site that gives you a 1d array called grid
grid = ['top left', 'top middle', 'top right',
'middle left', 'center', 'middle right',
'bottom left', 'bottom middle', 'bottom right']
and you're expected to write a method fire(x,y) that takes in two coordinates ... |
I've seen a lot of Brainf**k interpreters in various languages. I decided that actually interpreting Brainf**k is too hard, so instead of that, I wrote a 'compiler' in Ruby that directly transcribes BF to Ruby code. This is Version 1.0, and I'm looking for any tips on how to make it more efficient.
There are a few thin... |
I'm sending data from a form with a variable number of fields via an Ajax call. Some of the fields are grouped together so I have opted to send them as an array of JSON objects to keep the groupings, but there are a number of ways of doing this. For client-side, is it better to read the form as JavaScript objects and ... |
The algorithm works in steps:
Produce the graph in the form of an adjacency list
e.g. this graph
0 - - 2
\
1 -- 3
produces this adjacency list
{0: [], 1: [0], 2: [0], 3: [1, 2]}
0 depends on nothing, 1 depends on 0 etc..
Iterate through the graph and find nodes that does not have any dependencies
Question... |
I'm in the process of refactoring one of my open source projects, branch here.
The basic idea of the refactor is to allow for classes and all of its children in the graph to be scoped. I wrote a blog post about it here.
The container is abstracted into an interface:
public interface IScopedContext : IDisposable
{
}
... |
This code feels long and clunky to me. How can I make it shorter, if possible?
I am writing for a libGDX game, and I need a skill algorithm.
I want it so once the player picks up something (which I already have checked for) I set a, b or c to a certain SkillType, the enum down below. Then, I want to get the value of th... |
Based on a question on SO I thought I'd knock up a cmdlet to perform an unpivot on an object. I've not yet considered all the options (e.g. what happens when objects with empty lists are passed), so there are likely a few issues, but I wanted to get it out to the community early / see if people think this is useful or... |
I would like to get opinion if I am doing this right. I am creating a helper class that is globally accessible to my whole project. I want it to be easily called like Facebook.loginUser()
My code is like this:
class Facebook: NSObject {
class func LoginUser() {
println("Login user...")
}
}
And on usage just c... |
I wrote a function to reduce the size of JSON objects that works simply by turning every associative array into an indexed one, and moving each property's name to the first row of the data array (ordering it a bit like a CSV file, I guess).
<?php
/**
* Converts a list of associative arrays into indexed arrays.
*
* ... |
Can you please tell me whether this is a good way to get the user's IP (IPv4 or IPv6)? Does someone have a better way to do this? Please take a look at the entire code, the server_params order and the comments.
/* We are looking for ip in server params */
$server_params = array('HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR',... |
Previous iteration.
You know, I think this is the fastest I've ever pushed out an update to anything. This is Version 2 of my Brainf**k to Ruby converter, and the generated code looks... Well, like Brainf**k, converted directly to Ruby, with no attempt at making it more readable.
I'm looking for any tips on making thin... |
In context of preparing for a coding interview, I gave the division problem a go using Java. This is what I came up with. It's a little bit different to other solutions I've come across the interweb.
Implement integer division without using multiplication or repeated subtraction (i.e. to divide n by d, you man not rep... |
I am looking to implement a method that is capable of merging 2 dictionaries using generics. I've seen several great answers on SO already, but none handle the case of nested dictionaries. As in, what if the value of the dictionaries is another dictionary.
In order to tackle this, I created the following method:
using ... |
I have a login web page where a user enters their email and password and I need to check if:
the entered email exists in the DB and
the entered password matches the hashed one from the db.
The password in the DB was hashed with
$pw = password_hash($_POST["pw"], PASSWORD_BCRYPT);
and is stored in a VARCHAR(255) colum... |
See the previous iteration. I have incorporated the answer of h.j.k.. Now I have:
LineStringSerializationFactory.java:
package net.coderodde.lists.serial;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Scanner;
/**
* This class contains static methods for serializing... |
I've written a method for an API call that updates a store menu. It takes JSON as input, in the following format:
{
"menu" : {
"item_groups" : [
{
"id" : 1,
"name" : "Drinks",
"items" : [
{
"id" : 1,
... |
A little background - these are classes I've written on top of an Entity Framework model that represents tables on Sql Server with the following names:
Dictionary.Databases, Dictionary.Schemas, Dictionary.Tables, Dictionary.Columns
SysData.Databases, SysData.Schemas, SysData.Tables, SysData.Columns
Compare.Databases,... |
I wrote the following simple function in JavaScript that finds the sum of all the multiples of 3 or 5 below a value, given from a text-box.
I have used \$\dfrac{n}{2(a_1 + a_n)}\$ (sum of arithmetic sequence).
I was wondering if there is a way to shorten or otherwise improve this code.
function sum_of_all_mul_3_5(){
... |
Since it has too many loop, loop inside loop, this works very slowly. How can we increase the speed of this program? I am trying to copy a range from one file to another file of same name in different folder. I have folders named "A","B","C"..."G" inside c:\Charts\1\ and c:\Charts\0\. Inside each folder "A","B","C"..."... |
I am trying to optimize the usage of TopicClients in my app. The instance is originally covered by interface and passed by IoC, so the IoC will dispose it at the end of the program life cycle. This way I think I am saving some resources for the create/dispose of the client.Is such an implementation safe? Are there any ... |
First version: Go (board game) in Java
What's new:
I now use (as advised) HashMap<GoPoint, StoneColor> where GoPoint is my "coordinate" class and StoneColor is an enum.
Game allows only legal moves.
Player can pass (skip turn).
Player can choose the size of game board.
Code is more readable (I hope).
Better separatio... |
The following code creates a JFrame with a JTextField array in it. It also creates a JMenuBar at the top which allows you to select how many JTextFields you want to display (1-20) and then uses various layouts to display them on the JPanel.
I'm looking mainly for comments/thoughts on how the program lays out the JTextF... |
My service:
myApp.factory("MediaService", ['$http',
function($http) {
return {
all: function() {
return $http.get('/media');
},
save: function( data ) {
return $http.post('/media', data);
}
}
}
]);
My controller:
myApp.controller("MediaController", ['$h... |
I've created a decorator in my Rails application. However, the initializer has 3 params. Is this generally acceptable in decorator or should I refactor this or try a different pattern?
class FileBinderDecorator
attr_reader :binder, :credential, :page
def initialize(binder, credential, page = 1)
@binder = binde... |
I have the following 4 functions that work, however, I am sure that utilising promises will improve my code. I just find them so confusing.
$scope.takePictures = function() {
document.addEventListener("deviceready", function() {
var options = {
quality: 75,
destinationType: Camera.... |
I am working on writing a Code Golf King of the Hill challenge, the details of which can be read here. You can read the full code here.
Briefly, the game proceeds in cycles of night then day. There are two mafia, who collectively kill one person at night, and five town sided players (some of whom have roles during the ... |
I have an ArrayList of Strings. I want to delete all elements with a particular value and the element immediately after that one.
I have an ArrayList with the elements "Ape", "Bear", "Cat", "Dog", "Emu", "Fox", and "Gopher". Any time I see "Cat", I want to delete "Cat" and the element immediately following it. So in... |
This code calculates the factorial of a number on multiple threads. My issue: it is only a little bit faster than the sequential version of it (and I think I know why, I just can't find a way to solve this).
I use boost::multiprecision::cpp_int so the limits of default integers are not a problem, the size of integers i... |
I have a Ruby program which should solve the following problem:
Consider the divisors of 30: 1,2,3,5,6,10,15,30. It can be seen that
for every divisor d of 30, d+30/d is prime.
Find the sum of all positive integers n not exceeding 100 000 000 such
that for every divisor d of n, d+n/d is prime.
require 'prime'
cl... |
I am new to Perl and I wrote this Perl script to calculate bytes of code and lines of code in a directory. I want to know if there are any improvements that can be made to it.
#!/usr/bin/perl
# codestats.pl
# A perl script to calculate the number of lines of code in a project
# and what type of lines those code are, su... |
In my system I have a history repository.
My history class is big and with a lot of information regarding operations.
My warehouse needs, for some actions to know which histories are caused by the same action.
My first idea was to create an overloaded version of each method requiring to write histories and make all the... |
This is working code from a dataTable, which shows the function executed after the row is created:
"createdRow" : function (nRow, data, iDataIndex) {
var $row = $(datatable.row(nRow).draw().node());
var $quantityInput= $row.find("input.quantity");
var rowClass;
if ... |
Here is a code snippet of a class that I be interested to refactor. I was in doubt on how to proceed with the process of instantiation. The original ask was here. After think about it and heard some opinions I end up refactoring and splitting the instantiation in several constructors, one public and all others private.... |
I have written this script that downloads two tables from the db, preforms an intersection on them and adds 2 new columns to the resulting table, and uploads the resulting table to the db. It's a bit slow and I realize my code is messy (I'm new to Python and GIS). I suspect more steps can be done in parallel, for examp... |
Previous iteration.
I think this is about as good as it's gonna get, but just for kicks, let's do one more round of iterations.
As before, it's a very simple substitution from Brainfuck to Ruby, with fancy things like joining duplicate lines into one and indentation.
Some things that bug me:
The regex (/\++|-+|<+|>+|[... |
Every once in a while I need to get some random computer thing done; so I write something to do it for me. This is one of those. It needed to be able to send text to, and receive text from, a server - without blocking. I am asking for feedback with the premise of what kind of code this is: A one-use hack.
#include <std... |
I'm developing a WinForms app to manage some settings and profiles for multiple video games. The list of video games is specified by the user, and I'm trying to figure out how to properly maintain that list/collection throughout the lifetime of my application.
I decided on an XML file to manage the games list which loo... |
Using PHP and jQuery, I was able to make this countdown timer. I've searched various books and obviously on Google, but couldn't find this type of approach as used by me here. I sincerely feel there is something wrong with it. Can anyone tell me if this is the right approach?
<!DOCTYPE html>
<html>
<h... |
I'm trying to create a program that creates a record of how many times letters appear in a given string (ignoring blank spaces) using recursion.
s = "Hello there this is the string"
new_s = ""
for i in s:
if i != " ":
new_s += i
new_s = new_s.lower()
com_dict = {}
def merge_count(s):
global com_dict
... |
I'm working on a networked game. In this game, the base entity is called an actor. An actor can either be replicated or local, with each instance having a "replicates" field that represents this.
When managing a scene, a collection of actor must be maintained. My problem is finding a suitable solution to this. Right no... |
I have a UIScrollView full of vertically stacked subviews which I want the user to rearrange as they desire. I've implemented a UILongPressGestureRecognizer on my UIScrollView to successfully move the items around.
The more difficult part is when the user brings their finger to the edges of the scrolling area, the UISc... |
The Stocks Problem: Given an array of n integers representing the
price of a stock over the course of n days, determine the maximum
profit you can make if you can buy and sell exactly 1 stock over these
n days.
My solution is using the same approach as the merge sort algorithm. It is implemented using Java. I a... |
I try to create a private chat with Python but I don't know best practice.
It's only for study purpose, I'd like understand the logic behind a simple private chat with socket and the best mode to implement it with no framework.
For now, It's not important to check for example if username has > or other, only socket pro... |
I wrote a class to return the number of whole weeks between months in the same year. I need suggestions on my code.
public int year;
public String m1;
public String m2;
public Solution(int Y, String A, String B) throws ParseException {
this.year = Y;
this.m1 = A;
this.m2 = B;
String dateOneInput = y... |
I have the following code to extract results of an airline web service. I am wondering if there is any better approach to this. The code is supposed to ignore any flight that has more than 1 transit.
All retrieved results from the airline web service are in the AvailabilityRes class.
for (int i = 0; i < availabilityRes... |
I have a class that creates user accounts and to avoid SQL injection attacks, I am using the following functions to sanitize both the user name and password inputs:
$admUsername = filter_var($_POST['admUsername'], FILTER_SANITIZE_STRING);
$admPassword = filter_var($_POST['admPassword'], FILTER_SANITIZE_STRING);... |
Recently, I got a very interesting task: to realize the hash table that works in multi-process server in common memory, each element of which must have a TTL property. It was suggested to implement the TTL, as an additional process that walks through the table every second and corrects the TTLs of elements. I think thi... |
I am new to HTML and programming in general and am currently working on setting up my first website.
For this I created a couple of PHP pages with a separate file for each of them and in order to avoid duplicating code I tried to remove as much as possible from the pages header and saved this in a separate header file... |
The below Python 3 program scans 4 files a.txt, b.txt, c.txt, d.txt and then outputs the read data into a file output.txt in a formatted way. The first line of each file is guaranteed to have a header and the second line of each file will be blank. I'm required to scan those four files.
Program:
def main():
with op... |
I've been working on a safe inserting method for a while, and I think I've found a pretty secure way to do this. Would you CRitters mind taking a look at it and maybe give me some tips to improve my script?
function dbRowInsert($table, $data) {
require_once('../config.inc.php');
$buildData = null;
$countL... |
I have this method:
public void AddNLogConfigurationTypeTagret()
{
var filePath = _loggerModel.file_path_pattern.Replace("\\YYYY\\MM\\DD", "");
var dateTime = DateTime.Now;
filePath += "\\" + dateTime.Year + "\\" + dateTime.Month.ToString() + "\\" + dateTime.Day;
var filePattern = _loggerModel.file_name... |
I have a dialog that houses 6 security questions and 6 security question answers.
I want to pass the data the user selects and enters from the view to the controller to save the data in session. Right now, the code works perfectly but it is a mess. I am passing 12 arguments to my controller action! I am validating the... |
Prompt:
Each new term in the Fibonacci sequence is generated by adding the
previous two terms. By starting with 1 and 2, the first 10 terms will
be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not
exceed four million, find the sum of the even-valued... |
I am creating a jQuery plugin to be used to stick the headers and footers of tables (or other list data) to the top and bottom of the viewport while scrolling. (i.e. scrolling down the page, the header sticks to the top of the viewport and footer is always visible while table is in view)
Example: http://jsfiddle.net/kb... |
I'm new to VBA and am trying to write a macro to move data from an exported file to an excel template. The code below works, however I have to add many more ranges of data and am worried it will be hefty to run.
Sub MoveData()
Dim fileName As String
Sheets("Cover").Select ... |
This code is my solution to this Reddit challenge:
Description:
NASA has contracted you to program the AI of a new probe. This new probe must navigate space from a starting location to an end location. The probe will have to deal with Asteroids and Gravity Wells. Hopefully it can find the shortest path.
Map and Path:
... |
I came through a question on Stack Overflow, which shows this array structure:
array (size=4)
0 =>
array (size=3)
'id' => int 1
'name' => string 'Anniversary' (length=11)
'parent' => int 0
1 =>
array (size=3)
'id' => int 12
'name' => string 'New arrives' (length=11)
'pa... |
I've got a Python script that traverses two file trees, checking all .wav files for duplication.
I'm still an undergrad, and have never worked with audio before. I'm not entirely sure this is going to be a valid comparison.
I lost the SO answer I was using as a guideline, but the general idea is to split the audio int... |
This is my code I made that extracts data from a .csv file stored on the web. My sheet called 'New Data' stores this data for 2 days. I store 2 days worth of data so that when I run it next time, it pulls the data from the web, compares to the data I pulled yesterday, and then places any of the data that doesn't match ... |
I was looking for questions that might be asked in a technical interview and I found this one:
Write a function that determines if two integers are equal without using any comparative operators.
I'm using Java and my solution was to wrap the ints in an Integer object, convert that Integer to a string and return:
(fir... |
Related to Resx Translation Helper, V.2.0 Remove Files Window
First, I implemented the changes suggested in my last question, then I changed my entire code base to support editing 1-N Resx files. So, this question covers the main window. In particular, I wasn't able to remove all the code from the code-behind, and I ... |
Related to Resx Translation Helper, V.2.0
This is the code for the Remove Files window. I was able to keep code out of the code-behind here, but I have a feeling I botched something else.
IDisplayOpenFiles.cs:
public interface IDisplayOpenFiles
{
object DataContext { set; }
event EventHandler Closed;
voi... |
I am writing a program that needs to retain specific data but that should not be easily readable. I am in no way very skilled in crypto but I wrote this class that takes all of the data in and then returns the AES encrypted strings.
Is this an appropriate way to encrypt the data for storage in XML?
public class Crypto ... |
Following Data Science from Scratch by Joel Grus, I wrote a simple batch gradient descent solver in Python 2.7. I know this isn't the most efficient way to solve this problem, but this code should be running faster. How can I speed it up? My gut is telling me that mse_grad2 is the problem...
from __future__ import div... |
I was wondering if this code could be optimized in any way? For instance, could I use a for each loop here? Are there other ways I could write this which would make it easier for me, or the person reading it to understand?
public static void printFactors(int factorsOf) {
for (int i = 1; i < factorsOf; i++) {
... |
I'm new to C# (coming from a JavaScript background) and it seems like this code could be greatly improved.
This SQL query:
SELECT RegionString,SubRegionString,CountryString,COUNT(*) AS size
FROM table
GROUP BY RegionString,SubRegionString,CountryString
Returns:
RegionString SubRegionString CountryString Size
--------... |
I have the following script in Perl that does the following:
Prompts user for time in epoch. If user enters '########', the query will look for all reports generated after that date/time. If user does not input time, it will just look for all reports in past day.
Connects to a database, runs a query to receive reports... |
I have two arrays, each with shape (1, 51, 150, 207)
I need to add them such that:
newarray[0][0][0][0] = array1[0][0][0][0] + array2[0][0][0][0]
newarray[0][0][0][1] = array1[0][0][0][1] + array2[0][0][0][1]
for every element in the array.
Currently I'm creating a new array using nested while loops but this approach ... |
I'm new at groovy, and this is my first time writing a database connection script. It may seem like example code, but it is more like test code. It works as posted, and I'm planning to use this as a model for a larger business application, so I want to make sure I do it right.
Are there any groovy features that it coul... |
There is a context menu that comes up when a user right-clicks on a node in a TreeView. They are then presented with the choice to either add what is called a "RWB" or an "AQ" node to the tree. Both of these types of nodes have several settings in them, all of which are identical, save for one: AQ nodes have their 'Ana... |
I need to write a method to ensure that all of the nodes of a BST (Binary Search Tree) are valid. For a node to be valid, 2 things must hold:
The left child must be less than the current node's value
The right child must be greater than the current node's value.
I decided to write a helper method that checks an indiv... |
Google's Guava library has a great RateLimiter, but I also needed a way to limit on an irregular basis, such as if an API I'm using has been throttled. I basically built a wrapper around Guava's RateLimiter, only using the simple acquire() method from it.
import java.util.concurrent.ExecutionException;
import java.u... |
Yesterday I posted a request for a code review. After reviewing the code and the reviews, and after some sleep, I decided I can do better. In fact I logged on with the intent of deleting the question just as the first review was posted; so I was stuck with it.
This is pretty much the same program, but it is the result ... |
This is a fun piece. I have this block of code here:
if (minutes >= 60 && hours < 24) {
return hours + " hours ago";
} else if (hours >= 24 && days <= 30) {
return days + " days ago";
} else if (minutes <= -60 && hours > -24) {
return -hours + " hours from now";
} else if (hours <= -... |
I have been working on a mechanism to queue up strings coming into a system via a USART and have implemented it as a singly linked list. I have done my best to profile the code and its memory usage at runtime depending on the amount of data fed to the data structure, but can anyone see anything "wrong" or less than des... |
I made some refactorings in my classes. The original code is in this question.
In that question I receive the suggestion to create a Factory for the class BallEntity. I myself forgot that BallEntity is just a kind o 'factory' or 'builder' for a "Ball Entity". Just because Entities in an Entity/Component/System framewo... |
I created a function which reads CSV file and displays those values in a graphical form using Highcharts.
Although it works, I have to read the CSV file twice because first:
I need to get all the dates for the date values
I need to read it again through a function based on the filtered values
Here's the snippet of t... |
I recently tried a basic C++ implementation of a Trie, and was looking for some feedback on my code style/choices. In particular I was wondering if I'd made the right choice spitting the program up into header files and using classes instead of structs.
Inside the main.cpp there is a very basic string permutation funct... |
I've given the Rod-Cutting Problem a go with a non-recursive approach that use a cache instead, with a bottom up approach. For anyone who hasn't heard about the Rod-Cutting problem, it's defined as follows:
Serling Enterprises buys long steel rods and cuts them into shorter
rods, which it then sells. Each cut is fre... |
After optimising my code it still seems pretty brute force and I am looking for ideas to fundamentally improve it.
I have tried improving performance by:
Avoiding creating substrings as much as possible - using while loop to compare string instead.
Intelligently anticipating ends ie. start + shift + max < str.length... |
I want to know if this would be considered a proper way to validate a form or if there is an easier way that I'm not aware of.
I think I was reading somewhere that you are not supposed to use isNaN with AJAX but this seems to work for me. Can I just leave as is since it works or is there a better structure/system that ... |
I have some code that's part of my music-js library, and most of it is very organized, using object-oriented design for my AudioAnalyser and Visualizer classes (this code has been updated since publishing but I haven't pushed the changes for several months). There's one static function though, for generating the HTML a... |
What is wrong with this pattern which emulates AsyncTask functionality?:
// on the UI thread
final CountDownLatch latch = new CountDownLatch(1);
onPreexecuteWrapper();
new Thread(new Runnable() {
doInBackgroundWrapper();
latch.countDown();
}
}).start();
new Thread(new Runnable() {
@Override
... |
In most of the range query-update questions, we are asked to update some range of the array with some constant_value which can be done using the segment-tree approach. For more optimizations we can use the segment-tree with lazy propagation approach.
But in this question, we are asked to update given range with some... |
I have have attempted to use generics and constraints to create functions that retrieve and save data from a number of similar objects. Each of these objects describe their own properties. When I use these methods for a particular Type I don't understand why I have to specify new() in the constraint and also create a n... |
This is the new version of the dictionary program which I uploaded for reviewing here.
I would be grateful if the program could be reviewed for all the points mentioned in the above link.
#include<iostream>
#include<fstream>
#include<sstream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<string>
#includ... |
I'm new to Clojure and decided to read the book, "Mazes for Programmers". My first task, without reading any of the book, was to think of how I would create a maze. This is my first result and I'd like good, honest and even scathing critiques:
(defrecord Cell [visited? valid-dirs open-dirs])
(defrecord Maze [cells])
(... |
I have written the code below for inserting an element at the position specified by the user.
I have seen the code in multiple books, and they have always used two pointers in the function that inserts the node at specified position. However, in my code I have used only single pointer.
My code works fine, but I want to... |
I would like to understand how to get rid of all the loops I am using in this code.
I have a dataframe of 20 rows. I am simply counting the number of occurrences that the variables rs and occ appear together.
Here is the data:
d = structure(list(householdid.x = c("101366", "101366", "102481",
... |
Problem
I have a stream composed of 2 columns and 1000 lines:
Column 1: contains the patterns that I want to find
Column 2: contains the values corresponding the the patterns in Column1
I want to search for the patterns in column 1, extract their corresponding values in column 2 and save them in vectors. I actually h... |
Are the words isomorphs? (Code-Golf)
This is my non-golfed, readable and linear (quasi-linear?) in complexity take of the above problem. For completeness I include the description:
Two words are isomorphs if they have the same pattern of letter
repetitions. For example, both ESTATE and DUELED have pattern abcdca
EST... |
The solution was to be assessed, not just on completing the task but also on code quality and design, presence of testing, robustness, maintainability etc.
Problem Statement
Scenario
Basic sales tax is applicable at a rate of 10% on all goods – except
books, food and medical products, which are exempt. Import duty i... |
I have a view that looks like this:
@transaction.commit_on_success
def view(request):
do_stuff(...)
if condition(...):
result = do_other_stuff(...)
transaction.commit()
send_email(result)
return HttpResponse(...)
Assume everything with (...) can touch the database.
There are curre... |
Given [1,2,3], I wrote the following to get [[1],[2],[3]]:
ghci> map return [1,2,3] :: [[Int]]
[[1],[2],[3]]
Is this usage of return idiomatic in Haskell? I'm asking since I could've also used pure instead.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.