instruction stringlengths 71 71.9k |
|---|
I'm looking to improve it in brevity, readability, and simplicity. Basically, I'm just looking for a more elegant solution. What improvements can I make?
i=0
while true; do
OUTPUT="$(docker inspect --format='{{json .State.Health.Status}}' su-apache)"
if [ $OUTPUT = '"healthy"' ]; then
echo
break
... |
I was wondering if there is any way to make this code smaller/condensed. It is for a school project which says it has to be as small as it can be and I am not sure whether it can go any smaller.
num1 = float(input("Give first number "))#Get first number
num2 = float(input("Give second number ")) #Get second number
ans ... |
I am using the following function to make a specific filter passing the $scope.searchParams in this way:
<tbody ng-repeat="user in users | customFilter:searchParams "> ...
$scope.updateSearch = function() {
var searchParams = {},
loginArr = [],
nameArr = [],
statusArr = [],
accountsArr = [... |
I'm aware I am probably reinventing the wheel somewhat here, but I am trying to teach myself simple bash coding by completing simple tasks such as parsing files.
To that end I am looking to learn what elephants in the room I could be missing or if there are better ways to use the core functionality of bash without inst... |
This code load a 40MB txt into a dictionary. It runs in about 40 seconds (sometimes 20, no idea why). Is there a way to make it run under 4 seconds, or hopefully in 1 second?
Sub ScriptDic()
Dim FileNum As Integer
Dim DataLine As String
Dim tmp As Variant
Dim Dict As Object
Dim duplicatecount As Object
Dim key As Stri... |
I've created the following app in Python 3.5. The app uses pyowm and will take a location and return weather information. I've also built a GUI with tkinter for it.
Keen to find out some tips to improve my coding style.
import tkinter as tk
import pyowm
import datetime, time
class WeatherInfo(tk.Tk):
def __init_... |
I have been working my way through the exercises in the book Cracking the Coding Interview. I wanted to get feedback for the following exercise.
Write a method to replace all spaces in a string with '%20'. You may assume that the string has sufficient space at the end to hold the additional characters and that you a... |
I made this code for take some data from a .txt file. The text file is a large list of data from temperature with a format that is repetitive and have some lines at the beginning with the station reference. I took the first ten lines but only one time, then I jump to line 12 to take the headers and then I have a mark t... |
What would you improve at the following code, except:
The problems I'm already aware of, marked as TODO
Line width of at most 120 characters (I've run flake8 over it and it's fine)
Using decorators (I know about them, they don't fulfill my requirements in terms of how new commands should be written)
I'm using Python ... |
I have solved the problem and it gives me the right output when the BigInteger has the smaller value, however it kept running for more than 20 minutes with the larger value without printing out an answer. So I'm thinking that there should be a faster algorithm for this program.
The problem states:
The prime factors o... |
As junior java programmer I am working with Euler project and I would like to create a general purpose class which generates all the combinations from the length and number of choosen elements. The class returns a list of boolean arrays with length of length. Each array has choosen true value which highlight the chosen... |
I try to implement the encryption by Columnar transposition.
Input: key_secret and Text_to_encrypt, both of them are in lower.
Output: encrypted_text.
The code works fine but I have some questions:
it warns: "Function 'begin' could not be resolved", Function 'end' could not be resolved, Function 'copy_if' could not be... |
I have this code which migrates HTML elements to the word chunks by bracketing each element. Here, chunks is the list of word chunks to be processed and dom is to access the given HTML source. This returns a list of processed word chunks.
Could you suggest any improvements to this :
def _migrate_html(self, chunks, dom)... |
I have this code to translate text using the Google Translate mobile site. Currently, text size is limited by the request method. Everything else seems to works just fine.
I am also about to post this on PyPi but I don't know how I should name the package, the file and the function.
Basically today you must do:
import ... |
Inspired by Monday's Reddit daily programmer challenge, I wrote a function to check whether two strings are anagrams. It doesn't take the same input as the challenge, though, since I don't want to handle user input (yet).
For the lazy ones, the task is to write a function that checks whether the letters in the first w... |
This is a function to detect cycles in a back-trace. For example a cycle ('b', 'c', 'd') proceeded with 'a' could be:
>>> __cycles_detection(['a', 'b', 'c', 'd', 'b', 'c', 'd', 'b', 'c', 'd'])
(('b', 'c', 'd'),)
Args - funs (List[str]): functions list
Returns - list: the different cycles present in the back-trace
Ca... |
The idea of this code is to poll the server every 15 seconds to check for and update the notifications indicator. However, I'm not convinced I've done it right, as sometimes it seems to take an unusual amount of time to propagate across tabs and some users have reported that notifications "get stuck" and don't update a... |
I started learning factory pattern, and also implemented factory method pattern.
My factory-method pattern classes are as follows:
There are two major parts, an interface "Document.java" and and abstract class DocumentCreator.java which has an abstract method createDocument.
Classes XMLDocumentCreator and ExcelDocumen... |
In an Azure Function, I have a c# program that processes tab delimited data into JSON entries. I'd like to improve it in terms of performance and the connection management.
I want to remove personal data from each line.* As each line gets prepped for turning into JSON I perform this function for two values.** I need to... |
All the usual stuff. Style, substance, algorithm please! I'm vaguely considering plugging it into a bot, hence the lacklustre catching of exceptions right now.
import requests
import sys
def get_num_syllables(value):
try:
res = requests.get("http://www.thefreedictionary.com/" + value)
except requests.... |
I wrote this code to write the log file every 5 seconds to avoid excessive disk I/O (which can cause HDD temperature to increase or SSD to wear off):
var fs = require('fs');
var logText = '';
function log(){
fs.appendFile('c:/log.txt', logText, (err) => {
if (err) throw err;
logText = '';
});
}... |
I am attempting one of the questions from Cracking the Coding Interview:
"Design a chess game using object oriented principles."
The solutions are in Java and below is my attempt to create something similar in C++. This has brought up a few issues and gaps in my understanding. The below code compiles and gives me the d... |
Let me start off by saying that the question specifically implies using std::list<int> and not anything else AND you are allowed to iterate over the list only once. Taking this into account, we assume the target sum value to be 10.
The task is:
You are given a list of integers (std::list<'int'>). Iterating over the li... |
What would be a cleaner way to write the following?
// Check if add user was attempted
if ($params['submit']) {
// Verify all fields are filled in
if (Utilities::checkAllFieldsNotEmpty($params)) {
// Make sure username is not taken
if (Admin::checkUsername($params['username'])) {
// ... |
I wrote a little class that will calculate 6 business days from today. The reason it's in a class is because it will be used as a part of a bigger program.
I would like a way to refactor this class and make it a little more object oriented along with a little prettier.
from datetime import datetime, timedelta
class B... |
I need to optimize the below code, as much as possible in:
using less resources as possible
being as fast as possible
What the code does is simple, it splits the string by words and only if a word is equal or bigger than 40 characters it will add spaces every X characters to the word that was too big:
<?php
$text = ... |
Inspired by this question, I went on with the following version. My goal was to focus on pure functions, to avoid mutable variables and to be strictly functional.
I have ignored the computer player part - as it will not change the overall design.
An issue may be that an unchanged player survives from one game state to ... |
I wanted to learn some new language so I developed a really simple vb.net "console application" (was that the right type?) that takes text input, looks at it and multiplies it if it's even and then reads each result into a msgbox.
test.txt = 1 2 3 4 5 6 7 8 9
result should be an array {1 4 3 8 5 12 7 16 9}
This would... |
I've wrote a little iPad app with Xamarin.Forms. What I'm trying to do here is send some support tickets via a request to my server. I'm also keeping the "Failed" tickets in a collection so that I can try to send them in an other thread at app start. Can I improve my code or is it hopeless?
public void SendFailedTi... |
I'm writing a Minesweeper clone. I needed a function that returns everything located at a certain tile, and ended up with an atrocious mess. I'd like help making it cleaner and more idiomatic.
The main state of the board is represented by a Field record:
(defrecord Field [dimensions ; Pair: [width height] in cells
... |
I have a class, and it does one thing, It adds numerals to the numerals array.
In doing so it uses a number of private methods and has ended up looking a little bit sickening...
brace yourself...
require './lib/number_interpreter'
require './lib/numeral_adders/m_adder'
require './lib/numeral_adders/cm_adder'
require '.... |
This function generates a unique id for my files, which will be stored in the database to reference them. It returns the id if unique, if not, it generates a new one. My separate file server can then use these ids to locate and retrieve a file.
I'm planning on storing thousands upon maybe millions of files uploaded by ... |
I'm using QScintilla in my project. There's no good FindQScintilla.cmake out there, so I'm writing one myself. However, I don't really know what I'm doing. This is my attempt; it works, but I don't know how it'll work in reality:
find_path(QSCINTILLA_INCLUDE_DIR
NAMES Qsci qsciglobal.h
PATHS "${Qt5Core_INCLUDE_D... |
After reading about the Shunting-yard algorithm, I decided to try to make a expression parser, before trying to make a actual language parser, using it. The way i translated the algorithm into C++ code seems pretty compact, so there is really not much code to post:
Shunting-yard algorithm(in C++):
#include <iostream>
... |
I am writing a subroutine for unsigned integer division in Assembly. I will call the subroutine DIVU.
Inputs: R1 will be the dividend. The divisor will be in R0.
Outputs: The quotient is going to be in RO and the remained in R1.
Basically, I am trying to make something like this:
R1 / R0 = R0remainderR1
If R0=0, I wan... |
This is a follow up to my last code review:
URLify a string using Python
This problem has been reviewed in other languages, but I tried to solve this without looking at those answers.
I am hoping that I achieved \$O(n)\$ time and \$O(1)\$ space as was explained in my last review. I would also appreciate any tips on im... |
I'm currently working with Win32 and OpenGL a little bit and I needed a way to get the pointers of the OpenGL functions that aren't included in the Windows gl/GL.h header file. Rather than spending hours going through the OpenGL specification and manually typing out each OpenGL function definition in a header file, I c... |
I have many (4000+) CSVs of stock data (Date, Open, High, Low, Close) which I import into individual Pandas dataframes to perform analysis. I am new to Python and want to calculate a rolling 12month beta for each stock, I found a post to calculate rolling beta (Python pandas calculate rolling stock beta using rolling a... |
I'm new to jQuery, but I have a fair bit of experience with JavaScript, mainly using Angular.
What I'm wanting to do is have implement a horizontal list of tabs, where clicking each button will display a corresponding div, and hide the others.
Here's how I'm doing it:
$(document).ready(function(){
$(".tab-group").... |
Project now on Github: https://github.com/IanCaio/TempI
I just finished a working version of a small Unity indicator in C, that is supposed to take the output of the application "sensors" (sudo apt-get install sensors required) and uses it to monitor the temperature of the CPU.
It creates one indicator that has a small... |
This code implements quick sort and takes advantage of passing the list by reference. I'm looking for performance and general best practices.
import random
def quicksort(array, l=0, r=-1):
# array is list to sort, array is going to be passed by reference, this is new to me, try not to suck
# l is the left boun... |
Here's is the code I'd like reviewed:
module Main where
import Control.Monad ( when )
import System.Exit ( exitSuccess )
import Idris.AbsSyntax
import Idris.Error
import Idris.CmdOptions
import Idris.Info
import Idris.Info.Show
import Idris.Package
import Idris.Main
import Util.System ( setupBundledCC )
processShow... |
I got an idea to make a Roman/Arabic number converter, and I would like to hear your thoughts, where I could improve it, if there are Python specific things that I missed, so on and so forth.
# Decodes roman numerals
def get_arabic_numbers(t):
# Hold the numbers in the list
l = list()
# The format
form... |
This is the first of (hopefully) several posts as I reimplement an ancient (and unfortunately long lost) Excel VBA Tetris clone. The main workhorse class in the game engine is the display driver, which uses a rectangular area of a Worksheet to emulate a monitor. The display is sprite based, so the class holds a Dictio... |
I recently asked this question on Stack Overflow, but now that I have a working example, I would like to have it checked.
I set up the layout like this:
I am going off the idea that parents can talk directly to their children, but children should use an interface to talk to parents (docs). The docs where not clear, th... |
I wrote a password manager with the goal of being able to recover your passwords without connecting to an external resource. I used Electrum's recoverable bitcoin wallet for inspiration. When you create a profile in the password manager, a random 12 word phrase is generated, hashed, encrypted with the profile password ... |
I have this code which first checks for blank cell in Column B, and then blank cells in Column F. If the results is Yes-No, then it prints the phonetic into F.
Can someone review the code, please? I am also wondering if there is a way to set the starting point to be Column B (therefore, Cells(i,1)=B1) and possibility r... |
I wrote a simple online logistic regression, calibrated using gradient descent to compare the speed of an OCaml implementation vs the same Python script, executed with Pypy. It turned out that the OCaml implementation was slightly faster than the one run with Pypy (by about 10%). Now I would like to optimize my code ev... |
This is my solution to my SO question. My requirements are:
use links inside of the angular app
when following a link with the same path (i.e., differing in the search only), do not add it to the browser history
.run(function($rootScope, $location) {
var replacing;
$rootScope.$on("$locationChangeStart", fu... |
I made this game which should imitate a spaceship and obstacles (planets). Move spaceship and try to hit everything.
I will add some others features and functionality (better images or whatever).
I have several question.
My IDE (IntelliJ) gives me some warning and I try to remove them. One of them is "access can be pac... |
Originally I had ChildUserControl inside ParentUserControl inside MainWindow with this view-models (here only constructors):
public MainViewModel(IParentViewModel pvm) {}
public ParentViewModel(IChildViewModel cvm) {}
public ChildViewModel(IMessenger m) {}
And straightforward DI initialization in ViewModelLocator:
v... |
So I am trying to write, essentially from a blank slate, a program that plays Grand Chess. In short, it is a chess variant that is played with two extra pieces, on a 10x10 board, no castling, and optional promotion on the 8th and 9th ranks, mandatory on the last. Finally, you may not promote to a piece unless it has be... |
I'd like to create a function that can concatenate vectors or strings. It must
Keep correct order
Be optimal
This is the solution I came up with:
template<typename V>
V concatenate( V&& v )
{
return v;
}
template<typename V1, typename V2, typename... Rest>
V1 concatenate( V1 v1, V2&& v2, Rest&&... rest)
{
v1.ins... |
I'm using this class for producer-consumer setup in C++:
#pragma once
#include <queue>
#include <mutex>
#include <condition_variable>
#include <memory>
#include <atomic>
template <typename T> class SafeQueue
{
public:
SafeQueue() :
_shutdown(false)
{
}
void Enqueue(T item)
{
std::uni... |
I have a spreed sheet and its something like 550+ columns and I need to pull URLs from it. Previously I was using LinqToExcel when the sheet was less than 255 columns a recent update has produced this monstrosity, so I have moved on to interop with excel to parse the data.
Needless to say I have a list of a string I w... |
I currently have this code to generate a discrete signal with random amplitudes, but a fixed frequency:
import matplotlib.pyplot as plt
import numpy as np
# constants
t_len = 0.5
freq = 10.0
dt = 0.001
# set the see for reproducible results
rng = np.random.RandomState(0)
# create the random values to interpolate bet... |
Like most of the folks here, I'm learning Haskell, so I figured an interesting exercise would be to build a matching engine that I could use to build a financial exchange. I'm wondering primarily if I used monad transformers here idiomatically, but all other feedback is appreciated as well.
In some cases I felt like us... |
A \$Z^m\$ number system includes integers in the interval \$[0, m)\$ when \$m > 0\$ or \$(m, 0]\$ when \$m < 0\$. The code defines a trait Mod to represent numbers in this system and the +, -, and * operator for it.
use std::ops::Add;
use std::ops::Mul;
use std::ops::Sub;
struct Mod<T: Modulo<T>> {
modulo: T,
... |
Is there a way I could somehow have all this classes condensed into one, while keeping the code as clean as possible?
They are all doing essentially the same thing, just for the different number type. I don't know how to "generalize" TryParse() without using switch or if tree which doesn't seem very clean to me.
Base c... |
The purpose of this code to is check the 3 float switches in the laminator chamber for water. The float switches vote with the majority winning. A momentary switch must be pressed for the section of code (//// START FILL LAMINATOR FROM 70GALLON RES ///) to be active.
We can also take water from the reservoir using a di... |
I created this program as an exercise for me to learn ruby. It is a random name generator with a set of rules defined to generate pretty decent and usually pronouncable names. Ruby isn't exactly my favourite language, but I needed to learn it. The names produced consist of both latin letters and a few non-latin symbols... |
A \$Z^m\$ number system includes integers in the interval \$[0, m)\$ when \$m > 0\$ or \$(m, 0]\$ when \$m < 0\$. The code defines a trait Mod to represent numbers in this system and the +, -, and * operator for it.
use std::ops::Add;
use std::ops::Mul;
use std::ops::Sub;
use std::ops::Rem;
struct Mod<T>
where T... |
I am looking for assistance with the code at the last section referenced as "Logic to calculate allocation". I'm looking to conduct various SumIfs divided by CountIfs for a range cells that span about 30k rows and over 20 columns. I've tested it for just one column and it provided the results I expected but the time wa... |
After some advice, which method do you think is better to use when searching a dictionary for the matching value(s)?
Method One
Console.WriteLine("ENTER A PERSON/NUMBER TO SEARCH FOR");
string input = Console.ReadLine().ToUpper();
bool found = false;
if (myPhoneBook.ContainsKey(input)) // used with a persons name and ... |
I was looking for a way to navigate through a dataframe in R using just the console that displays every n lines. There are a few functions you can find at StackOverflow that attempt to answer this but none are quite what I want. So I made my own function but it has a lot of if statements. How can I refactor my code to ... |
I have a wrapper class:
[Serializable]
// (465 references)
public class Value<T>
{
private T value;
[NonSerialized]
private List<IValueListener<T>> listeners = new List<IValueListener<T>>();
// (232 references)
public Value(T value)
{
this.value = value;
}
// (274 references)
... |
My second attempt with vb.net - I tried taking the advice from yesterday's question into consideration, but I did not try using LINQ.
You know the drill:
A programming challenge that prints the numbers from 1 to 100, where
multiples of three print "Fizz," multiples of five print "Buzz," and
multiples of both three... |
I have implemented a thread safe filtering queue. The queue allows any objects, of the specified type to be added. A thread interested to take an object must specify which object it is interested in via Predicate<T>. A particularity of this implementation is that in my use case, the threads might not be allowed to remo... |
This is just for fun so you will see tons of print statements for trouble shooting. I was hoping on slimming this down some and gain new ideas on what I have. This was a challenge question in a class I'm not in. I know the code i wrote is nightmare-ish anything to slim it down would be nice.
import java.util.*;
publ... |
In one of my applications I make requests to a server. However, that server may at some point start making requests to my application as well. The server also allows polling, this means that I am able to make a request to a URL on the server and it only returns after some time if it does not have any content available ... |
At the moment, I'm trying to get some experience writing C++, Win32 and OpenGL, so I decided to implement a "Hello World" of sorts. However, instead of printing Hello World! to the console, I render a colorful triangle.
#include <Windows.h>
#include <gl/GL.h>
#include <gl/GLU.h>
#include <gl/glext.h>
#include <gl/wglex... |
This is a solution to exercise 1.4 from Cracking the Coding Interview written using Python 3.
Given a string, write a function to check if it is a permutation of a palindrome.
Example: 'Tact Coa'
Output: True (permutations: "taco cat", "atco cta", etc.)
I wanted to get feedback on making my code clearer and more pyth... |
Here's a PHP PDO wrapper class that I wrote, along with example usage. This class features 2 primary methods for interacting with a database: Query(), which returns a result set, and Execute(), which doesn't. The class and its public methods are PascalCase, protected/private properties and methods camelCase. I am inter... |
I'd originally not copied the result vector to vec which I figured and corrected. Iis there a better way to implement the merge sort other than the approach I've taken?
template<typename T> void merge(std::vector<T> &vec, int left, int mid, int right )
{
int i=left;
int j=mid+1;
int k=0;
int size = (rig... |
I am new to Haskell, and have been reading Learn You a Haskell for Great Good!.
I've rewritten a problem that I recently solved in JavaScript in Haskell to practice what I have been reading.
A little bit of a back story with out rambling on too much; I wanted to create a circle using bezier curve drawing commands. Simi... |
I'm a student in college, and while I have coded a lot, I still feel like I've only scraped the surface. I have learned a lot of things over the years, but very few of my professors ever did code reviews and I feel like I may have some bad habits that I may be overlooking, one that was pointed out to me was that I didn... |
I wrote the following script in the hopes of streamlining the finding and reading of multiple manual pages. Since I am always looking up different utilities' manual pages I thought this would a good learning aid.
#!/bin/bash
while true
do
echo
echo "1) /bin"
echo "2) /sbin"
echo "3) /usr/bin/"
echo... |
Problem
A single line should be separated by Environment.NewLine so that each row has a length of columns (expect for the last one that may be shorter).
Below is my solution:
public static string Wrap(this string singleLineString, int columns)
{
if (singleLineString == null)
throw new Argum... |
I've made this function for to get a deep copy (recursive copy) of objects.
=> Sub-objects aren't references to the sub-objects of the original object. Instead they are objects on their own.
Here's my code ...
Attention: Most of it are test data and an additional test-function.
// ----- Test data -------------------... |
I've tried asking about the performance on the HackerRank discussion forum, it didn't work out.
The task is to write a program with three operations:
1 x Push the element x onto the stack.
2 Delete the element present at the top of the stack.
3 Print the maximum element in the stack.
The first input ... |
Would appreciate any suggestions or improvements, I'm sure there are many. Especially so on the way I've avoided multiple hits by the missiles; shifting the asteroid into a separate group to enable the animation to continue without registering more hits and hence addition to the score.
P.S As it stands my game has a sh... |
For many console applications it is handy to be able to receive input and output at the same time from multiple threads.
This is supposed to allow receiving input commands from multiple threads, while simultaneously outputting.
Console.h
#pragma once
#include <iostream>
#include <string>
#include <queue>
#include <mut... |
I want to find average of an array of objects based on their key values using the new functional programming style. I found my way around array reduce and solved my problem, but not sure if this is the best way to do it.
Please take a look at my code and see if this is the way to use reduce for my purpose.
Let's say ... |
I wrote a little Javascript rock/paper/scissors/lizard/spock game and when the user clicks the button to make their choice from the five options, I choose the computer's randomly and then compare the two to find a winner and output the result. It works, but I have the feeling that the findWinner function can be a lot ... |
I'm new to Scala and learn it by solving some Project Euler problems. Here is the solution to problem 42 from Project Euler.
The task is to read words from file, then sum ordinal numbers of each character (e.g. sky =19+11+25=55). One need to count all words for which this sum is a triangular number (satisfying \$\frac{... |
Just finished an assignment in Python where one part was to write a function to find the correct rotation in a encryption similar to a Caesar Cipher..
As mentioned it's already finished and works as intended. The course is an introduction to Python, but I do have experience with other languages since previously.
I was ... |
I have a set of data which represents a set of nodes, each node is associated with a value (represented by a color in the image). What I want to achieve is selectively changing those values.
The mesh represents a porous system (say a rock for example) model. The pressure in my system is specified at the nodes. I want t... |
I am curious as to what improvements to my code can be suggested.
package concepts;
import java.util.Iterator;
import java.util.NoSuchElementException;
public class LinkedList<M> implements Iterable<LinkedListNode<M>> {
public static class LinkedListIterator<O> implements Iterator<LinkedListNode<O>> {
pr... |
I am job-searching and putting together some code samples. Just wondering how it looks.
Here is an example of some code, from a custom WordPress theme, that works and is in production:
Homepage Template
<?php
/*
Template Name: Homepage
Requirements: Advanced Custom Fields plugin
*/
?>
<?php get_header(); ?>
<section... |
Is there a better way to do this?
const data = [{id: 1, name: 'item1'}, {id: 2, name: 'item2'}]
const a = []
data.forEach(x => { a[x.id] = x.name })
return a // ['1': 'item1', '2': 'item2']
|
I'm using Sequelise with node.js, and I have a feeling the paradigm I'm using to modify objects is not working well, as my code is getting messy rather quickly.
The function User.createOrMerge is designed to be called after a successful social auth (Google, Facebook etc.), with kwargs being the social auth token to che... |
Related, but in C++
I have written a program that generates scrambling algorithms for and times a solving session of a 3x3 Rubik's cube.
Requirements for scramble and timer
The same face cannot be turned twice in a row.
The same family of faces (U/D, R/L, or F/B) cannot be turned three times in a row.
An "average" con... |
Thus code uses a mergesort-like algorithm to perform an outer join (in the database sense) on two sequences. (It's derived from the ActiveState recipe mentioned in the docstring.)
The actual algorithm is completely obscured by the extra code required to handle the possibility that either of the main iterators might th... |
The code below has many Lists<> but I'm not sure how to modify it. The only thing here that is an algorithm is the Fisher Yates shuffle algorithm. I am trying to put in good use an algorithm or just code better said to do this. It seems a bunch of code just used in repetition.
My question is, is there a way to make thi... |
Problem (inspired by Project Euler 29):
Consider all integer combinations of ab for X ≤ a ≤ Y
and X ≤ b ≤ Y
Return a sequence of distinct terms in numerical order
Input is a list of 2 integers separated by a space (" "), representing the lower and upper bounds (X Y). Input is read from txt file.
Output is a numeri... |
Here is a swift port of UIView subclass that I use often in my apps. It allows me to easily set gradients in place of the backgroundColor property, and also makes it very easy to create views that have one, two, or three rounded corners.
I'm not super familiar with the mechanics behind core graphics and drawRect, so ma... |
This code basically generates a random number of bubbles that animate from bottom of the screen to the top and repeats. When the mouse is in a certain distance (proximity) of the bubbles it scales those bubble and changes their background color. This Demo can explain better, how it works.
Now the problem is that whene... |
Question 5 for Project Euler is finding the smallest multiple of 1 - 20. My solution is not even close to most of the solutions I've researched. Any feedback, good or bad, is greatly appreciated as I've been self teaching how to code on and off the past year and a half.
function smallestMultiple()
{
var smallest = 0;... |
I have a need for a container that behaves like an unordered_map, but has a fixed capacity, and an eviction policy where the least recently inserted key-value pair is chosen to be evicted when an insertion is performed at capacity.
I've implemented this by creating a container which combines a regular unordered_map wit... |
The code below is my solution in python 3 to exercise 1.5 in Cracking the Coding Interview. I would appreciate feedback on both the algorithm (improvements to space and time complexity) and/or coding style. I think the time and space complexity of the code below is \$O(n^{2})\$ and \$O(n)\$ respectively.
The exercis... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.