instruction stringlengths 71 71.9k |
|---|
We were asked to make a triangular number pattern in C++ with minimum loops:
____1_____
___2__3____
__4__5__6__
7__8__9__10
Code:
#include <iostream>
using namespace std;
int main() {
int n=0, r=0, i=0;
cout << "No. of rows: ";
cin >> r;
for( n=1; n<=r; n++) {
for( i=1; i<=r-n; i++) {
... |
Here is a naive implementation of a kernel density regression algorithm in Julia.
The code works, but there is quite a bit of room for improvement though. First, there is not an optimal bandwidth selection implemented and second; it's really slow. Nevertheless, it took me a while to implement and I am really looking f... |
I have a method in Python that is extremely slow:
def patternRecognition(self):
patRecStartTime = time.time()
plotPatAr = []
patFound = 0
for eachPattern in self.patternAr:
sim1 = 100.00 - abs(self.percentChange(eachPattern[0], self.patForRec[0]))
if sim1 > 50:
sim2 = 100.0... |
I created a class which is some kind of thread pool. The difference is that it holds foreign threads. This means that the threads are created somewhere else and are then held by calling holdThread. Then another thread can call executeOne or executeAll to execute a specific function. At the end the threads can be releas... |
Edit - here is my modified code: http://jsfiddle.net/#&togetherjs=GzytydCsRh
Can someone take a look and give me some feedback? It seems a bit long still but that is the first time I used functions.
I am reading a bunch of CSV files and using glob to concatenate them all together into separate dataframes. I eventuall... |
This is a Python implementation of a stream cipher encryption algorithm. This implementation originates from the one displayed on the TI-Basic wikidot cryptography page.
I am well aware that this code breaks the holy 80 character limit, so any suggestion on how to make the code more succinct would be appreciated. My ma... |
An improved version Sieve32FastV2 is available.
The classical solutions for the Sieve of Eratosthenes fall into 2 camps: one uses a bool[], which is fast but very memory bloated; the other uses a BitArray, which is more sluggish but uses far less memory. Refusing to accept that those are the only 2 possibilities, I’ve... |
I wanted to use an async-cache to store URLs of images that I have to display in a list. The image URL is fetched (REST call) using a unique UUID associated with each item of the list. I store this URL locally and then use it to show images in the future.
I came up with the following async-cache to make my life easier.... |
So recently I made a large project of mine open source: Khronos. I will be dissecting parts of it so that I can have it reviewed more easily here and so that the project as a whole will be improved. The first part I want to have reviewed is the CMake file involved with kicking off the building process of the project.... |
I'm writing a function that receives an array and returns an object with the count of unique values, pretty much like other questions here or in StackExchange. Except that in my case, this array may contain a nested array, like:
var array = [1, 2, 'a', 'b', [3, 'c', 1], 'd', 2, 'b'];
Here is my code:
function findUniq... |
This is a follow up of this post.
Changes:
I tried harder to make my code readable yet concise.
All Point instances are immutable and unique.
New, useful features have been added (like reflection, rotation, translation, etc.)
This class depends upon this class. Line will follow soon. For the time being assume that Ou... |
Here is a partial example of a text tokenizer. I'm looking for ways to improve one particular line in this code:
implicit class textFile(val fileName: String) {
def toDict() = {
io.Source.fromFile(fileName).getLines.flatMap(_.split("\\\\r?\\\\n")).toList
}
}
def filterComments(m: List[String]) : ... |
As part of processing card payments, before even attempting to process, I need to check and validate the card number to make sure it's valid. For this, I've encapsulated this validation in a record called TCardNumber. It does the trick for what it needs to do, tested with a Visa card and an Amex card. Since this is a s... |
This is a recursive algorithm implementation of Eulerian tour search.
I guess there is no way to make it more efficient (except rewriting with loops instead of recursion). Any advice on style?
def sub(visited, _cur, graph):
if not graph:
return visited + [_cur]
for i, edge in enumerate(graph):
c... |
I have written a class containing methods to factor a polynomial equation using the p over q method. The method returns a string that is the factored equation.
Here is the class (can also be found here):
public class RPF {
private RPF(){}
public static String solve(int... a){
if(a.length <= 2){
... |
I'm working on a generic repository using EF 6 code first and trying to following the Unit of Work pattern. Unity is being used to inject my repositories, and I'm trying to get everything supporting Async.
Here is my EF configuration + context:
public class CustomDbConfiguration : DbConfiguration
{
public CustomDb... |
Well, I've used some of the feedback from my last posting to improve how I wrote this program. Mainly using the void parameter in main, initializing my int array to zero without using a for-loop, and better naming of variables. If there are some issues that are going on with my code, or there's some things I can do bet... |
For my second major project in C, I decided to write an implementation of the Vigenère cipher in C.
My program uses command line options (optarg) and can read from both a file or from a string specified with the -s option. It does both encryption as well as decryption of text and also has error handling and I've list... |
I'm relatively new to programming, and I've been wondering about a problem such as this. How can I think about decomposing the code into its constituent functions? I went the simplest route I could, just putting the formula in its own function. I believe this makes the code more readable, but there's also a part of me ... |
I would like to write a function in C that turns all negative values into zeros then shifts the positive numbers to the beginning of the array, maintaining the order of the positive integers in the array.
void shift_positives(int values[], int num_values) {
int i;
int last_zero = 0;
int j;
for (j = 0; j... |
I am looking to improve my code structure. In this code it is opening all the links with ?pid= in the url. However, the structure of the code can be improved.
for a in self.soup.find_all(href=True):
href = a['href']
if not href or len(href) <= 1:
continue
if href[0] == '/':
href ... |
I use this document as a basis for my mini-library:
Motivation
The std::rand friends are discouraged in C++14, so we want:
A direct replacement to the std::rand friends. Despite of the security issues, std::rand is considered both handy and useful as a
global uniform random number generator.
To expose the most wide... |
Write a function that takes in two sorted lists and outputs a sorted
list that is their union
Could anyone help me to improve this code and make it more user-friendly? We are not supposed to use any built-in Python functions, but rather develop our own efficient algorithms.
def answer(list1, list2):
len1 = len... |
I'm not sure whether my code looks good or not:
var app = angular.module('Todolist', ['ngResource', 'xeditable']);
app.run(function(editableOptions) {
editableOptions.theme = 'bs3';
});
app.controller('TasksCtrl', [
'$scope', 'Task', function($scope, Task) {
$scope.user = gon.current_user
$scope.updateT... |
This is a code I wrote to find all URL within a PDF file and replace the one that matches the ID that I passed as a parameter.
It works as intended, but as I am a beginner on Java, I am sure there are some best practices that I am not following.
I am using the PDFBox library.
Here's the code:
Main.java
public class Mai... |
I wrote some code to put stamps on all pages of a PDF file with the name and company passed as parameters. It works as intended, but as I am a beginner in Java, I am sure there are some best practices that I am not following.
I'm using the iText library.
Main.java:
public class Main {
public static void main(String[] ... |
I created a C# console program to loop through a specific folder in Outlook to look for a specific email subject. When I run it on my computer (multi-core CPU), it didn't use up 100% of the CPU resources. But when I test it on the server (single-core CPU), it uses up 100% of the server's CPU resources.
What can I do to... |
I've written some method for sorting asc and desc numbers in array. All I want to know is this good logic, and is there a space for improving this code?
-(NSArray *)sortHanded:(NSArray *)inputArray ascending:(BOOL)ascending {
NSMutableArray *inputMutableArray = [inputArray mutableCopy];
NSMutableArray *sortedAr... |
I have implemented Latent Dirichlet Allocation in Julia. Since the code is rather long, I copied the essential part here but the complete code can be found on GitHub.
#=
LDA.jl
Adham Beyki, odinay@gmail.com
=#
##########################################
###### Latent Dirichlet Allocation ######
#######################... |
This is a contest problem. The entire description is here.
In resume:
The question gives a point simulating a light explosion that always has a negative x coordinate, a set of pairs line segments on the y axis are given simulating walls and a set of points with positive x coordinate representing possible positions for ... |
My code was made as an practice for CodeChef. Here's the brief from that page:
Relational Operators are operators which check the relationship between two values.
Given two numerical values A and B you need to help chef in finding the relationship between them that is:
First one is greater than second or
First o... |
The code works fine, but the speed stays at a consistent eight frames per second.
Today I fixed some pieces and got four more frames per second.
I figured out that the typecasting (int) and Math.floor() consume around 50 fps.
Is there anything I can do to improve the performance of this code?
public void render(){
... |
Here's a function that sorts an array of objects with a dateProp by the date. First it uses moment to convert the Date object to a unix timestamp.
var _ = require('lodash')
var moment = require('moment')
util.orderByDate = function (arr, dateProp) {
if (!dateProp) return arr
return _.chain(arr)
.map(function (it... |
I built one of these long ago, and it got lost when I reformatted my SSD (sad day) so here is the new version.
It is very multithreaded, spawning numCores - 1 threads to calculate n chunks. When one thread finishes, another is spawned until all chunks have been assigned.
It's quite quick and accurate, though the imageS... |
As plain r5rs is lacking in useful string processing utilities, such as string-split and string-join (I'm using MIT/GNU Scheme), I decided to implement my own. My procedure, string-join, works just fine, but I would like my code to be critiqued by seasoned Schemers, and also find out if there are other, more efficient... |
A little while ago in The 2nd Monitor, me and @Phrancis were talking about Python and debugging, and the topic of function decorators came up with this message:
Ethan Bierlein: You could even build a debug decorator. Give me a sec.
So, I built a small, simple debugging decorator, which would just print out the argume... |
I wrote FizzBuzz. My aim is to use C# Code Standards correctly, and write flexible code. How can I improve my solution according to code standards? How can it be better in general?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsAp... |
I have 5 or 6 ID's and I need to compress .hover jQuery into smaller amounts. I tried this answer, but due to how he needed only 1 "group" inside the .hover function, it makes mine not work because I need a way to have 2 "groups" inside the function.
$(document).ready(function(){
$("#menuicon").click(function(){
... |
So I wrote this for my Mandelbrot Generator, to collect and use input from the user, and I made it dynamic enough to be useful anywhere.
I'm really interested in all critiques of it, as I'm going to be using it a lot now.
The idea is to allow the user to easily show messages on the console, that require input. Once val... |
With C++ templates, I've implemented a template list type with cons, reverse, merge, sort, filter, map, fold; and higher order template functions with currying. The C++ compiler can also work as an interpreter of a (convoluted) purely functional programming language, which is the C++ template metalanguage.
This main fu... |
Here is the implementation of interface Dictionary using chained hash table class HashTableChained.
Despite item 22* saying
Favour static member classes over non static
in Effective Java, I used non static member class DListNode in class DblyLinkList, because any instance of the DListNode class MUST be associated wit... |
We are using images from Wikimedia commons for some of Cardshifter's game artwork. I selected some art for each card to make a .jpg file to use in the game clients, and added a URL to the original file as a comment for reference. This is what one card looks like: (with our DSL made from Groovy)
// https://en.wikipedia.... |
I thought I'd give it a shot. What I came up with is from a culmination of my last two submissions, incorporating most of the feedback from this community, including better naming of variables, initialization, and making my program a bit more user-friendly. I'm not sure which optimizations I can make or if there are an... |
How can I improve this code and avoid crutch? Can I use a case operator?
public bool Crutch;
public void Resize(SizeChangedEventArgs input)
{
if (input.NewSize.Width < 450 && Crutch)
{
if (!ServiceLocator.Current.GetInstance<MultiViewModel>().EightBoxesCommandIsEnabled)
{
... |
I'm working with Codeigniter most of the time (about one and a half year now) and I came across many form validation code flows. Here are my best two selected shots which I created for a client recently.
I only care about model and controller, views do not need to be reviewed.
Features of both code:
Validation for for... |
I started to teach myself Haskell recently. Here is some code I wrote to convert a roman numeral into an arabic numeral:
import Control.Arrow ((>>>))
import Data.Maybe (fromJust)
fromRoman :: String -> Int
fromRoman = translateFromRoman >>> applyNegationRule >>> sum
translateFromRoman :: String -> [Int]
translateFrom... |
I'm new to JS and am trying to write a perfectly clean source code. I'm using gulp to concatenate and minify my files, as well as removing comments. So the end result will always be the same in production environment: a single line without spaces. But for a dev environment, I'm trying to achieve clean code.
I'm buildin... |
This script shows the number of contracts for persons. Table Contract has more than 82008 records and Candidate has about 7978.
Could you please suggest improvements for this script?
select ISNULL(CON.ContractCount, 0)
, CAN.PersoonName
, ... /* some fields from table Candidate (more than 25) */
from Candid... |
This code is part of an application page, which lets user select existing or add new members, For email and Username it needs to call web services to see if they already exists then validate respectively according to business logic.
I believe this code has a lot of potential to be improved. Please note this is part of ... |
I wrote a Haskell program to solve the N-queens problem by bruteforce. It works and I find it reasonably readable
But it is pretty slow:
5 seconds for one solution of 8 queens.
1 minute for one solution for 9 queens.
Crash for 10 queens. I fear that allFalseOneTrue gives memory problems as it uses permutations.
I wo... |
Currently, I have a big for..loop with many if..else inside the loop. I just wonder is there any design pattern or other approach to reduce the long code inside the for..loop. Thank in advance.
foreach ($workingTimes as $hour => $minutes) {
foreach ($minutes as $shift) {
$isBookable = $this->isBookabe($hour... |
This code inserts data into the database successfully. I was concerned about whether it is a considered good practise to go about inserting data into the database in this way. Is there something I am not considering?
function insertTest(){
global $db;
$field_names = array("id", "first_name", "last_name", "... |
I have this code that I am using to delete all records from an entity. The question is can it be done better or is already the best?
func deleteIncidents() {
let appDel: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let context: NSManagedObjectContext = appDel.managedObjectContex... |
I have created a directive for common form fields shared across all the forms in a large AngularJS app I am re-factoring.
The app has lots of forms for various data models (user, owners, victims, suppliers, etc). A lot of the forms for these data models contain an address section which is the same format throughout th... |
I have finished my first project using ASP.NET MVC. I did not have to wait long to realise I have essentially violated all possible codes of good programming. Well, experience comes with practice.
One of the styles I completely missed was Dependency Injection Principle. It was far too late I could re-write the project ... |
This is working, but I want to know if is this a place where IEnumerable can be used?
public static int LongerThanStingCompair(string s, int n)
{
int counter = 0;
// splits based on nextLine break
var sCount = s.Split('\n');
// Cast to list
sCount.ToList();
foreach (... |
I was reviewing some WPF code I've written in C# last year.
The scenario is the following:
I've got a usercontrol that show usermessages and it's docked in the bottom of the application's workspace
I've got a ConcurrentQueue that receives message via a IMessageMediator (from Catel, but's irrilevant how data are pushed... |
So here's my attempt at the September community challenge, making an elevator handling system. I'm not really very familiar with OOP, so I'm particularly looking to get feedback on that part of the script even if you're unfamiliar with Python. I'm fairly certain there's times I've mishandled abstraction and what class ... |
I developed a Kuku Kube game for iOS. Each time I choose a correct different color tile, it will increase a number of tile quantity 2x2 3x3...10x10. How to optimise the code each time the tile increase that auto fit on ip4 to ip6 Plus? I think it can not use auto layout to set for the size.
- (void)setSizeforTile {
... |
A recent Mandelbrot question (Hi @EBrown) in C# inspired me to build my own using the Java 8 parallel streams to implement the parallelism that's useful for computing each pixel value.
The intention is to incorporate this in to a graphical interface that allows you to navigate and zoom in on the Mandelbrot set.
To do t... |
The application listens for OP_RETURN messages on the Bitcoin blockchain and prints them to standard output. OP_RETURN is a custom transaction locking script that can store data, but nothing beyond that. It's used for experimental use cases such as proofofexistence.com and coinprism.com.
I would like some critical f... |
I've been given the following task:
Given N rectangles with edges parallel to axis, calculate the area of the union of all rectangles. The input and output are files specified in program arguments. Input is represented by N lines with 4 numbers separated by spaces, defining 2 opposite vertices of the rectangle. Output... |
This code defines functions to cipher text with both mono-alphetic (Caesar) ciphers and poly-alphabetic ciphers. I also define a shortcut for rot13. I like this code and I think it is easy to read, but code is never perfect so I ask you for improvements.
import Data.Char (toLower)
alphabet :: String
alphabet = ['a'..'... |
This works fine so far, but I am looking for some advice as to how to better write this. My goal is to learn and incorporate current/latest C++ practices, and become a better programmer overall.
#include "HTTPRequest.h"
/*
This function initalized Winsock
*/
bool HTTPRequest::InitWinsock()
{
WSADATA WsaDat;
... |
I am trying to design a DSL for writing C. Here is my code as a GitHub gist (Github does not allow me to have slashes in the filenames so I have used underscores instead). It depends on packages free and process.
My goal is to make the DSL low level enough that one can reasonably predict the output code, and convenient... |
This is a follow-up to this question.
I've refactored my previous debugging decorator, and added a couple new features, and changed a few things. Here's a complete list of things that have changed:
There is only one decorator, Debug, and it now supports functions, and class methods.
Each debug message is prefixed wit... |
I want to arrange async server-client communication with websockets and vanilla flux architecture. There is an excellent article about "Async Server-Side Communication with the Flux Architecture". I gonna implement it analogue with SockJS and ES6 promises:
ActionCreator.js - it's the same but moved to ES6
import * as c... |
I am trying to build a tree similar to this one :
1
/ \
2 3
/|\
4 5 6
/
7
With that tree, I must be able to get all ancestors for each leaf.
In this example, this would be :
7 -> [4, 2, 1]
6 -> [2, 1]
5 -> [2, 1]
3 -> [1]
To build that tree, I can only use an unknown number of pairs of parent-c... |
This animation makes my fans spin up after several seconds, and it seems to have a sub-par framerate. I am trying to understand why, and optimize its performance.
Codepen
The animation function (this is the main part of the code):
function animate() {
t++
ctx.clearRect(0, 0, c.width, c.height);
for (var i ... |
I'm looking for a way to optimize this piece of code in Python.
all_users holds all the Twitter users and friends_ids is an array of IDs.
g = Graph(directed=True)
all_users = users.find({}, { 'id_str' : 1, 'friends_ids' : 1}) # This is from MongoDb
names = []
edges = []
print 'Processing first 1000 batch'
for idx, us... |
How can I maybe do some loop that will compress the amount of JavaScript/jQuery I need to use. I have a function s3episodesChange() linked to a <select> tag. This <select> tag has a few different selectable values that change style properties of various different <button> tags.
All it is doing is showing the appropriat... |
I wrote this working code to create a linked list of a given length and print each node's values.
#include <stdlib.h> //NULL
#include <stdio.h> //printf
typedef struct Node {
int val;
struct Node* next;
} node;
node* make_ll(int len){
node* head = malloc(sizeof(node));
node* cur = head;
for (int ... |
This is (the significant) part of an implementation of a logging mechanism for recording events in a real-time control system. The basic requirements are:
No dynamic memory on either side (producers or consumer),
Lock-free
variable length event entries
strictly sequential timestamps
multi-processor safe
tolerant of o... |
I have made a program in Python to do a filter of log files from a server. What I would like is some guidance on how this code could be optimized, streamlined or 'short-handed' so my 'pythonic' programming becomes better. I don't program for work, I do it on a requirement basis so I'm not good by any means.
Requiremen... |
This converts from character representation of integers to their decimal value:
def chrtodec(str):
dec = 0
base = ord('0')
for chr in str:
dec = dec * 10 + ord(chr) - base
return dec
For example: "123" -> 123
|
Similar to my recently asked question: Style-changing handler for an HTML drop-down box How can I compress down JS and almost automate it?
I tried changing up the old questions answer a bit but never could get it working as i'm very new to JS I mainly do PHP.
So I just need the following JS compressed and automated as ... |
@chux pointed out that my attempted solution contained several problems. Since I screwed that up so badly, I figure that I should put my revised solution up for review.
#include <stdio.h>
#include <time.h>
/**
* The current year (number of years since 1900)
*/
static int this_year(void) {
time_t now = time(NULL... |
I wrote a numbers-to-words converter for English, then tried to adapt the code to work for French.
I'm wondering mainly whether any simplifications are possible.
In English
English is relatively straightforward:
english :: Int -> String
english n
| n == 0 = "zero"
| n < 0 = "negative " ++ (english (-n))
| ... |
I need to dynamically call a stored procedures from my repository, and here is a my implementation:
public void ExecProcedure(string name, Dictionary<string, string> param = null)
{
List<object> sqlParametesList = new List<object>();
try
{
if (param !... |
Sonar complains that I have too many return statements. How can I reduce the return statement count nicely?
public int compare(Sku o1, Sku o2) {
if (o1 == null) {
return (o2 == null) ? 0 : 1;
} else if (o2 == null) {
return -1;
}
if (o1.getSkuNumber() == null) {
return o2.getSku... |
I want to arrange async server-client communication with websockets and vanilla flux architecture. There is an excellent article about "Async Server-Side Communication with the Flux Architecture". I gonna implement it analogue with SockJS and ES6 promises:
TodoActionCreator.js
import { dispatchAsync } from '../AppDispa... |
I am building a wrapper around the sharp image library.
The usage revolves around chaining tasks. But I wish to execute it by just passing in a config.
An example of what I am currently doing:
var execute = function ( obj, task ) {
var methodName = task[0];
var passedValue = task[1];
return obj[ methodNam... |
An array is bitonic if it is composed of an increasing sequence of integers followed immediately by a decreasing sequence of integers. Write a program that, given a bitonic array of N distinct integer values, determines whether a given integer is in the array.
I have divided the problem in two sub-problems:
Find the... |
Is there any way I can make this FizzBuzz better?
toFizz :: Int -> String
toFizz x =
case (mod x 3, mod x 5) of
(0, 0) -> "FizzBuzz"
(0, _) -> "Fizz"
(_, 0) -> "Buzz"
(_) -> show x
main :: IO()
main =
mapM_ (print . toFizz) [1..100]
|
This question is related to my question on Stack Overflow earlier today. After getting suggestions on using the PreparedStatement from Java I changed my code a little.
EDIT: In my original question on Stack Overflow I attempted to process
the query in a very messy way, see this short excerpt:
String sqlQuerry = "IN... |
Here is my attempt at solving Project Euler problem 3. It works for test numbers up to 9 digits long, but overflows when I input the real 12-digit behemoth.
I've looked at other methods of solution, but I wanted to challenge myself to code one that doesn't search with unnecessary numbers - only primes - and never any o... |
I have an application in which a user makes a change, and when they click Save they will be prompted to confirm, and the appropriate REST call will be made if they agree. The intial call to Save() returns a promise that is fulfilled if the call returned successfully, or rejected if there was an error or the user cancel... |
I have made some adjustments to some code that you can see on this thread:
Read daily files and concatenate them
I would like to make some further refinements and make sure I am on the right track organize some of my files better. I added some functions and made some other changes to prevent errors and make my code eas... |
I have a large text file (~2GB) full of data. The data (sample below) gives an x, y, z coordinate, and a corresponding result on each line (there is other stuff but I don't care about it). The single large text file is too large to be useful, so I want to split it into several smaller files. However, I want each file... |
Lately I've been working on adding Scenarios to my city building game. I wanted to create custom terrains for some of the different scenarios (such as a chain of islands, or a volcano). I decided that the simplest solution was to try to use topographic images to create an array of integers that could then be converte... |
I'm coding a basic video upload system for a client. The uploaded videos will live on the page using the HTML5 video element.
Essentially what I've done is call the following PHP script asynchronously from the upload page when the video is uploaded (the upload page, meanwhile, displays a message that their video is con... |
I wrote this for an SO question on formatting numbers to specific quantities of significant figures (after all, reinventing-the-wheel), anyway, all critiques welcome.
It's pretty easy to use, FormatSignificantFigures(0.123, 2) should return 0.12; FormatSignificantFigures(0.123, 5) should return 0.12300; FormatSignifica... |
I created a bunch of small and mostly internal WPF applications for my company - usually for some file manipulation etc. For these programs, I would like to start collecting user info - who uses them, how often, most importantly - which version is used.
It's partly for my personal skill development, but I also want to ... |
I am trying to learn how to design and implement a layered Java web application with a presentation layer, service layer and the DAO layer. I have used the Struts 1.3 framework with Java JDK 1.6 for the below explained sample project.
Questions:
How GOOD or BAD is the below implementation of the layered web applicatio... |
I created a form that formats phone numbers, allows only allowable keys to be pressed, and converts a lettered entry into its corresponding phone keypad number. Is there some cleanup or better coding that can be done? There is no business need for international phone numbers as it is a local business.
function pageLoad... |
Here is a little game modeled after adventure that I have been working on. The code initializes a set of lists. It sets a current location randomly generated. The user is tasked with either incrementing the index or de-incrementing the index (moving up and down the avenue). At each location there is a store which they ... |
I'm pretty new, but I'm always looking for different/better ways to solve these problems as it helps me understand it better and hopefully will make me better programmer. Feel free to point out any mistakes or industry "dont's" as well.
#include <cstdio>
using namespace std;
//Function Prototypes
void deleteDupes(char... |
You have n items, each one of those has a certain value, represented here as an integer.
How do you give to two persons the most similar value?
No comment from me here as my code already contains much documentation.
from itertools import combinations, chain
import doctest
def all_subsets(lst):
"""
Returns ... |
I've become interested prime factorization since solving Project Euler problem 3 (finding the largest prime factor of 600851475143). Learning here that initializing lists with many elements to later prune them is the computational equivalent of swimming with bricks, I challenged myself to code a function that returns a... |
This project is pretty much like a 2D gravity simulator. You click and it creates a circle that attracts other circles. The result of a collision is a bigger circle that is a sum of the masses. If you don't know what I'm talking about, here's a gif:
The game was made using CreateJS, but you don't need to know CreateJS... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.