instruction stringlengths 71 71.9k |
|---|
The problem in question is a coding challenge from Hackerrank:
Problem Statement
You are given an integer N. Find the digits in this number that
exactly divide N (division that leaves 0 as remainder) and display
their count. For N=24, there are 2 digits (2 & 4). Both of these
digits exactly divide 24. So our ans... |
This program is a payroll using calculate two types of employee. Two overloaded functions for two type of employee (hourly and salaried). There must be one pass-by-value, one pass-by-reference, and two pass-by-reference using pointer. All the variable must be local. There are 3 files of this project.
Interface
clas... |
I am creating a class object which must inherit from numpy ndarrays. I perform an isinstance check and an array.shape check with the __new__ method. Is it alright to have it here, or should it be elsewhere? I saw suggestions to create an exceptions class to accompany it, but it doesn't seem necessary... maybe prefer... |
I'm working on a C# implementation of a tree class.
The tree will be used wherever I need to store data in a tree format. (Application Menu, File Infos etc.). Therefore, the tree should support a lot of different use cases.
I think my implementation is ok… but I'm not sure. I never implemented a tree before and I also ... |
I have a simple function that takes an Integer n and return a string representing the array from 1..n.
nthLine :: Integer -> String
nthLine n = intercalate " " $ map show [1..n]
The main function takes input n from the user and prints the nthLine out to screen:
getInteger :: String -> Integer # This seems redunda... |
I made this mini life simulation thing. I got the idea from the Eloquent JavaScript textbook, and just kinda ran with it. I've been programming for a little less than year and this is probably the largest thing I've made to date, so I'm looking for a little feedback.
If there's anything you see that can be improved, pl... |
I am creating simple web api/ SPA application using EntityFramework, IUnitOfWork, Repository pattern, Unity DI along with Asp.net Identity.
Unity configuration
public static void RegisterTypes(IUnityContainer container)
{
// TODO: Register your types here
container.RegisterType<DataConte... |
Here is a search implementation for my tree. It searches each node in a breadth-first manner first, but it goes deeper in a depth-first manner, in the event it needs to go deeper. I know there may be multiple identical items in the tree (well, not my current use of it, but I still need to presume that), so it just re... |
I'm designing a login portal that has one angularjs page that displays/processes data queried from a database. I'm relying on a few php pages (a loginpage.php [verifies credentials/loads session variables], a check.php [page that is included in all php pages, verifies session variables are 'okay'], and a getter.php [qu... |
You are given 3 strings: text, pre_text and post_text. Let L be a
substring of text. For each substring L of text, we define
pattern_score as follows:
pre_text_pattern_score = highest n, such that first n characters of L are equal to the last n characters of pre_text and occur in the same
exact order.
post_t... |
I'm developing an iOS Application in Swift that uses Google Cloud Endpoints as its backend. For now, I've just written the code for the user to login with his Gmail account and I've refactored it as much as possible but the callback chain is making me nervous.
The reason I'm worried is because firstly, I'm fairly new t... |
I feel the best way to learn is practice. I have written a simple Blackjack game in Python which supports multiple-players and functionality like Hit, Stand, Surrender, Split and Double_Down. I need some help to review my code, in order to remove any redundant code, simplify the implementation, and improve the code qua... |
I watched bunch of videos about swing and GUI in general and created my first component (correct me if it is not one).
JPanel class:
package gui.pane;
import javax.swing.*;
import javax.swing.event.EventListenerList;
import java.awt.*;
import java.text.DateFormatSymbols;
import java.util.ArrayList;
import java.util.C... |
I have this visual mod for a javax.swing.JProgressBar:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.Toolkit;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JProgre... |
As one of my first C programs I want to read in a matrix and compute its determinant. I don't pose limits on the size of the matrix and this makes things more complicated.
Version 0
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define ROW_LENGTH 8
#define CHUNK 32
typedef struct {
... |
Question:
Smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
I tackle the problem with reference to how I solved #3, which is using the prime_division method in the Prime class. I have created an array of prime_divisions for 2..20.
The array looks like this:
[[2, 1], [3, 1], [2, 2],... |
I've got a base class GraphUIControl which is inherited by 4 child classes:
BubbleGraphUIControl
BatchGraphUIControl
LineGraphUIControl
StackedGraphUIControl
I sometimes put all my GraphUIControl in the same List<GraphUIControl> for some obscure reasons.
I wanted to order my list (first by Graph type, then by name) s... |
I want to know if there is any redundancy in the code or if it is missing something. I ran it with several different choices and it works fine but I still want to know are there any more subtle implementations in parts or in full.
import java.io.*;
class data{
String name;
int roll;
int age;
public data(String a,int b... |
I am a beginner to PHP programming. I wanted to make a 2D array that would store the values of a table into the array. Below is the Frankenstein code I created (every time I wanted to achieve a task I researched a solution, so this is a bunch of solutions plus my own doing put together).
I would be really grateful if ... |
I've been building a simple C# server-client chat-style app as a test of my C#. I've picked up code from a few tutorials, and extended what's there to come up with my own server spec.
In this post (the second will be the client), I'd like to get some feedback on the server. To me, the code seems bulky and as if it coul... |
I've been experimenting with some old code that needs refactoring in places and was testing if there was any improvement to iis threads etc by uploading file asynchronously (Server Side). I'm using jQuery file upload client side.
The original code
[HttpPost]
public ActionResult UploadDocument( HttpPostedFileBase upload... |
I've written a stable implementation of insertion sort, that sorts an array in ascending order.
Please let me know of any improvements/optimisations that can be made.
import java.util.List;
public class InsertionSort {
public static void start(List<Integer> arrayToSort){
for(int i = arrayToSort.size() - 1;... |
Here's an implementation of selection sort, that sorts an array in ascending order.
Please let me know of any improvements/optimisations that can be done.
import java.util.List;
public class SelectionSort {
public static void start(List<Integer> arrayToSort){
for(int i = 0; i < arrayToSort.size(); i++) { ... |
First and second post on the same subject. This is such a great way to learn.
Once again I'm open to suggestions. I have implemented almost all of the suggestions from before, which have resulted in the code looking like this:
import java.util.Set;
import java.util.HashSet;
import java.util.Arrays;
import java.util.re... |
Question:
Difference between the Sum of squares from 1 to 100 and the square of sums of 1 to 100.
Answer in Ruby:
range.inject(:+) ** 2 - range.map{|x| x ** 2}.inject(:+)
This one seems pretty straightforward but welcome any improvements to make it more elegant!
|
Problem 1:
Sum the even numbers for the first n fibonacci numbers
Solution:
def fib(k):
"""Compute kth fibonacci number.
>>> fib(1)
0
>>> fib(2)
1
>>> fib(11)
55
"""
def recursive_fib(prev, curr, k):
if k - 1 == 0:
return curr
else:
return... |
I'm trying to write a function explodeBy:
explodeBy :: Int -> [Int] -> [Int]
explodeBy n arr = foldr (\x acc-> (take n.repeat) x ++ acc ) [] arr
This works as follows:
λ> explodeBy 2 [1,2,3]
[1,1,2,2,3,3]
The above uses list concatenation, so I tried writing a more efficient version:
explodeBy2 n arr = foldr (\x acc... |
Question:
For a 1000-digit number, find the 13 adjacent digits which gives out the largest product.
My code goes like this:
series = '731...752963450' # the 1000 digit, simplified here.
# Set up variables.
adjacent_count = 13
pointer = 0
candidates = [], products_array = []
pointer_end = series.length - (adjacen... |
Question:
Add all prime numbers smaller than 2,000,000.
The first method is done by deriving own is_prime? method:
# First Method
def is_prime(n)
if n <= 3
return n > 1
elsif (n % 2 == 0 || n % 3 == 0)
return false
else
(5..Math.sqrt(n).ceil).step(6) do |i|
if (n % i... |
I'm combining two lists of dicts, based on the value of the key 'time'.
If have two lists, for example:
a=[{'time': '25 APR', 'total': 10, 'high': 10},
{'time': '26 APR', 'total': 5, 'high': 5}]
b=[{'time': '24 APR', 'total': 10, 'high': 10},
{'time': '26 APR', 'total': 15, 'high': 5}]
These lists contain val... |
This is a follow-up to this question.
While discussing some details about the code I posted there, I came upon a problem with thread-safety. After searching and trying different things, I reached a potential solution that I now present here. This worked without any problems during my tests, though since thread-safety i... |
Why is this code "bad"? In all of the selection sort codes I am learning from, they do it much differently. I will learn the proper code from the book, but I would love to know why this particular code is bad.
public class Main {
public static void main(String[] args) {
int[] array = {8, 3, 5, 7, 9, 2, 4, 6... |
My first FizzBuzz question (well, I asked, then deleted, one previously), and my very first VB.NET question.
Module Module1
Function FizzBuzzify(ByVal Value As Integer) As String
If Value Mod 5 = 0 And Value Mod 3 = 0 Then
Return "FizzBuzz"
End If
If Value Mod 3 = 0 Then
... |
Continuing with my VB.NET experience, I wrote a quick guess-the-number game. Any improvement suggestions?
Module GuessTheNumber
Sub Main()
Do
PlayGame()
Loop Until Not ExitGame()
Console.ReadLine()
End Sub
Private Sub PlayGame()
Dim minNumber As Integer = 1
... |
For fun, I decided to implement the quickest Quicksort I could. This is what I came up with. How can I make it better?
I know that it's slower for sorted and already reversed lists (through testing), but I'm not certain why. What I do know is that this algorithm reverses the list past the pivot, if the list was sorted/... |
I'm relatively new to Java and decided to make a Memory Match game.
Card.java:
import javax.swing.JButton;
@SuppressWarnings("serial")
public class Card extends JButton{
private int id;
private boolean matched = false;
public void setId(int id){
this.id = id;
}
public int getId(){
... |
I'm trying to develop a program that stores currency values. In my particular application I only care about two decimal of precision (cents) but have read it's a good idea (for accuracy when dealing with interest rates) to store 4 digits.
I didn't notice a "currency" class in either boost or C++14 (perhaps I overlooked... |
Does this data structure make sense? It's essentially a vector of pointers, intended to point to larger objects. In effect, it gives the benefit of a linked list, with an \$O(1)\$ lookup at the cost of maintaining an array of pointers to each element.
What edge cases am I missing, and what's the formal name of this da... |
Project Euler problem 78:
Let \$p(n)\$ represent the number of different ways in which \$n\$ coins can be separated into piles. For example, five coins can be separated into piles in exactly seven different ways, so \$p(5)=7\$.
Find the least value of \$n\$ for which \$p(n)\$ is divisible by one million.
I used Euler... |
I am trying to multithread a for loop, and this works so far. How can it be improved? Have I done anything incorrectly?
The work is broken up into blocks and the block variable is the amount of objects to process per thread.
Test.class
public class Test extends MultiThreaded {
public static void main(String args[]... |
I'm trying to learn to program on my own with the help of books and the Internet and thought I'd start a project (a sub-project for a project).
I want to build a dictionary that allows multiple keys for one value:
d = mkdict()
d['what', 'ever'] = 'testing'
d['what'] is d['ever'] # True
I thought it would be good to ge... |
Question:
Given a 20x20 Grid of integers, find the greatest product of four adjacent numbers. (up, down, diagonal, reverse diagonal).
08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08
49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00
81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65
52 ... |
Disclaimer: It's literally the second time I write in Haskell.
The purpose of this module is to provide some basic operations with IP addresses (and networks).
At the moment I only implemented the successor operation, that returns a next address in the range if it exists.
Eg: for 192.168.1.1 in 192.168.1.0/24 it would ... |
I'm a complete newbie to Elixir, but I managed to bang together this working example of Ascii85 for a project I'm working on in my spare time.
I find some awkward repetition in here which I have tried to replace with iteration but it just made the code harder to read. There is also some lop-sided behaviour which I'm no... |
This PHP User System was built with MySQLi and I also used Composer. I'm planning to improve this, and add more stuff and release it as a sort of a module for Composer.
User.php (Controller File in the src/Controller) folder.
<?php
namespace Application\Controllers;
use Http\Request;
use Http\Response;
use Application... |
The source of the problem is here.
Given an array of integer elements, return the maximum difference of any pair of
numbers such that the larger number of the pair occurs at a higher index
than the smaller.
Here is my implementation in Java.
package algo.mindiff;
public class Main {
// http://www.careercup.... |
Please review this solution for matching parens for correctness and nesting.
def matchParens(pstring):
plist = [l for l in pstring]
newlist = []
if plist[0] == ')' or plist.count('(') != plist.count(')') or plist[-1::] == '(':
return False
while len(plist) > 0:
head, *tail = plist
... |
I think my Table class may be doing too much. I feel as though I should perhaps create a separate Input class that deals with editing the table's rows.
My main problem is knowing when to create a new class. Is it true that the table is doing too much? Which things should be made into other classes, and why?
Btw, Step i... |
If a triplet of segments A, B and C are triangle triplets if and only
if
A + B > C
A + C > B
B + C > A
Is there a better implementation for this problem?
#include<vector>
#include<iostream>
void findTriangleTriplets( std::vector<int>& vec_input, std::vector<std::vector<int>>& triplets)
{
int size = vec_input.... |
Please let me know if there is a shorter way to do it again without any kind of loops. Recursion only.
static bool isSortedArray (int[] ar, int length)
{
if (length == 0)
return true;
bool temp = isSortedArray(ar, length - 1);
if (temp && ar[length - 1] <= ar[length])
return true;
else
... |
I'm learning Rust now and created a program to solve the task General Fizzbuzz on Rosetta Code.
For example, given:
20
3 Fizz
5 Buzz
7 Baxx
where the first line indicates the upper bound and every line after that indicates the divisor and the corresponding word, the program should return:
1
2
Fizz
4
Buzz
Fizz
Baxx
8
F... |
This is a follow up question to PyDOS shell simulation.
You might remember PyDOS from my other post. I have now updated it and it's better than ever! Post any ideas below that could make it better.
import time
import os
import sys
import random
def splash():
print ()
print ("PyDOS")
print ()
print ("Versio... |
I wrote a small script to get the probability of a given text to be spam. I downloaded some ham (good content) and spam (bad content) text from the internet. The spam corpus is a 1.8 MB txt file, and the ham corpus a 3.6 MB txt file.
My method is pretty naive: I count how many times each word appears in the ham and spa... |
I'm writing an animal shelter program, which keeps a database of different classes of animals (dog, cat, monkey). Functions that create the form and add the animals are very similar (difference is two questions and the rest is the same). Is it possible to divide this functions into parts so that the program code is not... |
I wrote a script with utilities for calculating the entropy of iterables and included a Tk GUI that shows a quick overview over a text's properties in real-time. (on GitHub)
I tried to follow PEP 8 as good as possible, but I'm not sure about other things, specificially:
I think my docstrings are sometimes overly redun... |
Here is yet another piece of Rubberduck code, this time the nasty ProcedureNotUsedInspection class, whose role is to identify all procedures that are never called anywhere, and to issue a ProcedureNotUsedInspectionResult for each one.
using System.Collections.Generic;
using System.Linq;
using Rubberduck.Parsing;
using ... |
I implemented an O(N^2) algorithmic solution but not sure it is better than my previous implementation Find Triangle Triplets from a list of given numbers
in case of performance. I adapted almost all suggestions from answer except a structure to keep the triangle triplets.The reasons to ignore the suggestion are foll... |
The below I have put together as an experiment, I have profiles on my site that are password protected. I would still like them to be crawled by google.
The script is taken from here and basically does a reverse dns lookup to verify if a googlebot is real or fake. I am then using this logic to allow google entry to my... |
I just finished my linked list library in C and I am trying to find out what should be improved. The functions provided by the library are members of the main data structure (very important).
The entire project can be found here.
Here is the source:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "c... |
This is a sanitizing function. Is this function secure enough?
public function clean( $input, $fordb = true ) {
global $db;
//is it an array?
if( is_array( $input ) ) {
//yes it is! let's clean each item individually.
foreach( $input as $key => $val... |
This code calculates the distance between angles, particularly for n-tuples of angles. One example where this situation occurs is as follows:
I'm using a 2 arms, one 6 degree of freedom and the other 7 dof with revolute (rotating) joints. The position of the arm can be accurately represented as an n-d point representin... |
I'm trying to create a simple HTTP client. In order to make one that is standard compliant, I must be able to extract user information from a URI and convert it to base64 and send it via an authentication header to the server. I created this demo program to test my progress on this function I've made. Does this program... |
I am creating a simple program with multiple buttons. Is this way of checking which button was pressed is ok? Is it better to use switch..case.. statement?
public class KennelGUI extends JFrame implements ActionListener{
private String filename; // holds the name of the file
private Kennel kennel; // holds the ... |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace Project2
{
class Program
{
static void Main(string[] args)
{
int[] ageForPeople = new int[10000];
int[] DistrictForCensus = new ... |
I've written a MySQL class that handles sanitization of different data types. The reason I used this (and not prepared statements) is because this can be more dynamic.
Prepared statmenets only supports four data-types:
Integer
Double
String
Blob
This limits functionality and it doesn't allow you for example to add ... |
Shamir's Secret Sharing scheme essentially splits a secret into n parts, at least k of which are needed to recover it. I'm using that to encrypt/decrypt arbitrary files (it's part of a college project).
Here's a rough idea of what I'm doing:
Take a file, and read N bytes. Treat those bytes as an integer, and encrypt i... |
The problem is that I have executed the program for the last hour and it hasn't returned a value till now for input 1022. How can I make the program a bit faster? How can I increase the efficiency of program? Is there a faster algorithm?
I have Intel Core2 Duo (2.93GHz).
#include <stdio.h>
int main() {
unsigned lon... |
There are 3 window groups to add users and the application uses MVC 4. Here's my approach to add security attributes to my controllers and pass user's role to the view in order to enable/disable controls. I'm looking for ways to approve the code.
Webauthorization.cs (the logic to check user's role & if not in any role ... |
I've compiled a simple Linux pipeline and using my C style and modularization that I will use for my own operating system. Do you have something to say about this code (partly taken from SO)? For example, are all my imports necessary? How can I improve error handling?
#include <sys/types.h>
#include <errno.h>
#includ... |
I have created this bash script for Compile And Run c++ code, car++.sh.
As I'm new to bash scripting, I'm not sure about good bash programming practices.
Please review it to see if you could find any anomaly.
#!/bin/bash
found=false;
output=;
o_is_set=false;
#retrieve output_filename from arguments as provided by use... |
I have written a simple implementation of Sieve of Erasthotenes (in C, MSVC flavour), which I believe is correct (source below). Is there a way to make it faster and more readable?
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <intrin.h>
typedef unsigned long long bitmap_entry_t;
#define NUMBERS_TO... |
I have been playing around with an adjacency list implementation of a graph class, on which I'd like to be able to run a build and test several graph algorithms. The code I have below works and I have been able to implement BFS, DFS, Dijkstra and Prim's algorithms, but I'm not very satisfied with it and would very much... |
I have written a program in C to do the following:
Read a matrix (in file format, first line you have the size, then next are the entries). This is done by the "input" function.
Find the strongly connected components using the kosaraju algorithm (the one that uses the transpose). Done by the "SCCmatrix":
+) Step 1: DF... |
I'm trying to optimize the following method. Any suggestions on how this can be done better? The shipping cost is based on weight and the total cost of products. Following are the conditions for calculating cost.
When order is under $100, and all items under 10 lb, then shipping is $5 flat.
When order is $100 or more,... |
I have a class that contains defines 'magic' numbers at compile time such as basic array sizes, fixed ip address, etc. so that I have one place to edit if changes are required.
In this nested class I need to define tuples of maximum and minimum values that correspond to each of 4 bands of an IR camera. I'd like to use... |
See this this question for background. This is a live filter where results are filtered as you type. I've taken into account Kerri's answer and expanded on her recommendation. I've added a message that appears if no results are found, and a display for how many results are being displayed out of the original set. You c... |
Using an OR/M I map a lot of rows from database to array of objects (~300k). In these objects some properties are marked with special attribute [Signed]. Row-by-row I combine them in string, calculate salted MD5 of string and compare to hash I received from database.
Everything was working pretty okay for a long time, ... |
To help prepare myself for my final exam, I wrote a simple Game of Life. I want to expand it to have each sub-population represented by a character, but before I do that, I want to make it more efficient; because right now it's running at about 1 fps, which is way too slow (I'd like at least 3 fps). What I want from a ... |
The purpose of a rhythmic task controller is to accept a task and execute all the queued tasks in a cycle or "rhythm" defined by the client code. A task returns true or false depending on whether or not it is "finished". A finished task should be removed from the controller's control and won't be executed again while a... |
This is my solution to Project Euler
Problem 52 - Permuted Multiples. In the problem I'm searching for the smallest value of x such that x, 2x, 3x, 4x, 5x, and 6x use the same digits.
x = 125874
while True:
x += 1
if sorted(set(str(x))) == sorted(set(str(x * 2))) == \
sorted(set(str(x * 3))) == sorted(s... |
I am attempting to create an efficient algorithm to pull all of the similar elements between two lists. The problem is two fold. First, I can not seem to find any similar algorithms online. Second, there should be a more efficient way.
By 'similar', I mean a predesigned way to find all similar elements between two list... |
Particularly on the CSS page, in the #question_list id, you'll see I've put a transparent border. This is obviously pointless, but without that border, my footer moves up and down when the proceeding questions come in, due to their size. Any suggestions on what I can do to remove that border and have my footer stay put... |
I made this function to act sort of like jQuery's $.ajax. I intend to use it in small projects where I do not use jQuery (I don't want to load a whole framework just to facilitate http requests).
Edit: New script incorporating Bob Lauer's suggestions
"use strict";
function OM(obj){
return new ObjectManipulator(obj... |
It is a continuation of my previous question:
Find non duplicateTriangle Triplets from a list of given numbers
After I realized triplet structure using less space than std:vector<int> and there is a simple way to remove duplicates from the triplets list by modifying loops index I rewrote the code again. On top of that ... |
I'm looking for code-review, optimizations and best practices. This code is a Java adaptation of code on geeksforgeeks.org. Please verify if space complexity is \$O(n)\$ where n is number of bits, and aux complexity is \$O(1)\$, since no temporary space was needed. Whatever space was needed was used for return value no... |
I was working on some TT code generation to get rid of mundane C# codings in VS2013 Express Edition, and after researching online, created the following helper methods to facilitate Type declarations.
I am able to use it successfully in my code generation but wonder if they can be improved further or if there's any sce... |
I have recently started using React and wish to know if my code adheres to the React coding style, whether I am following the same approach towards solving any problem and is there any way I can make the code better.
var React = require('react');
var Bootstrap = require('react-bootstrap');
var xhr = require('superagent... |
In the process of writing scripts to work with CSVs and other files of the like I found myself in the need of a way to navigate and select files for various purposes. I wrote the following function for one of the scripts I needed to finish quickly and now I'm trying to get it into a more reusable form
def select_file()... |
Below is the representation and user interface fib_sequence for generating a Fibonacci sequence:
empty_rlist = None
#Representation - start
#Constructor
def rlist(first, rest):
return (first, rest)
#Selector
def first(s):
return s[0]
def rest(s):
return s[1]
#Representation - end
def fib_sequence(k):
... |
To write a Java class that reads through a text file of drawing commands and draws the appropriate shapes onto JFrames, I have input instructions as follows:
FRAME width height // sets up a new frame with given width and height (both integers)
COLOR red green blue // sets the current “pen color” to the color with the g... |
I solved the Fibonacci Golf problem on checkio.org:
The Fibonacci numbers or Fibonacci sequence are the numbers in the
following integer sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21...
This is not the only interesting integer sequence however; there are
many various sequences like the Fibonacci numbers, where each elemen... |
I have a project in my mind for quite some time, and it requires me to create dynamic objects.
Usually, casting an array to object does the trick (e.g.: (object)array('test'=>5)). But sometimes, we still want the magic methods to fire up. For that, I have developed a class.
It supports the magic methods __construct, __... |
I've seen everybody claims the nested ternary to be an evil even when an operation couldn't be written with switch-case; and here's even more, my code could be easily written with switch-case statement.
/// <summary>
/// Control sequence character
/// </summary>
private readonly string CSI = "\u001b";
public string Co... |
I wanted to see graphically what my programme was doing so I wrote this automatic flowchart generator:
class Object
def log(previous_method)
if not DEBUGGING
return
end
repr = if self.class == Enumerator then self.to_a else self end
if [Array, String].include?(repr.class... |
The problem I am referring to is here
So basically it's about shifting an array of ints 1 position to the left and relocating the lost first int in the start of the array to the last position at the right:
\$\mathrm{shiftLeft}(\{6, 2, 5, 3\}) → \{2, 5, 3, 6\}\$
\$\mathrm{shiftLeft}(\{1, 2\}) → \{2, 1\}\$
\$\mathrm{sh... |
I am trying to optimize execution time of this function which detects cycle in a directed graph:
g = {
1: [2, 3],
2: [3]
}
cur_path = set()
def isCyclic(g, vertex):
global cur_path
cur_path.add(vertex)
for neighboor in g.get(vertex, []):
if neighboor in cur_path:
return True
... |
I am very happy because I solved this problem with very little code:
"""
100 people are standing in a circle with gun in their hands.
1 kills 2, 3 kills 4, 5 kills 6 and so on till we are
left with only one person. Who will be the last person alive?
Write code to implement this ##efficiently.## <-[ Pyt... |
This is the second part of a multi-part review. The first part, the server for this client, can be found here.
I've been building a simple C# server-client chat-style app as a test of my C#. I've picked up code from a few tutorials, and extended what's there to come up with my own spec.
In this second part, I'd like to... |
I've written an answer to HackerRank's Angry Professor problem. Please let me know if there's a quicker/better way of solving this as I think I wrote quite a bit of code for this problem (answer has to be in 1 class btw). Also, any improvements on my code in Java 8 are welcome too.
Problem statement (as written on Hack... |
I wrote a mixin to declaratively get a Bacon.js event stream. So instead of onChange={this.handleChange}, you can do changeStream={this.handleStream}, and this.handleStream will be passed an onChange Bacon.js event stream. My big concern is that I have to override React.createElement in order to make it work. I'm wo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.