instruction stringlengths 71 71.9k |
|---|
I have created an automated macro which takes vehicle crash data from a .csv file and automatically creates a pivot table and charts and compares it to the previous year. The code is approximately 1400 lines long and the data of the uploaded .csv can be anywhere between 2 to 100 MB .csv files with more than 100,000 row... |
The code is about displaying membership information of all clients from a database. This is for homework and I'm just curious if more can be done to improve this. Feel free to alter it, but please include some reasons for your alterations.
import sys
import re
def menu():
print("---------------Tracking Jobs and Re... |
A recent question, inspired me to think about how far we've come, and how much easier tasks are in current, modern languages like C# and Java, compared to the low-level languages we were stuck with years ago.
Based on that, I decided to post some code for doing the same task, but in a language that (at least in most pe... |
As a beginning project, I decided to code something that plays the game Chopsticks in Python 3. I'm using the Minimax algorithm, and exploring the tree using simple recursion. One of the main problems is performance. I can only search through about five moves deep; anything more takes too long. How can I improve my per... |
Given a stack with N elements and a query Q, we need to find all elements of stack for which Q returns a specific value.
Time complexity should be less than \$O(N)\$.
Let's preprocess an element when we add it to cache.
The query will be represented by a static class, which has two members:
getGroup - a function which... |
I have a lottery simulator on my website that simulates you playing the lottery every week until your death and tells you how much you would have won or lost. It can take a custom number of balls and rewards scheme, as I made it after Camelot changed the rules for the UK national lottery to give people an idea of how t... |
Could anyone comment on what could be done better and if I made any mistakes?
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
typedef pair<pair<int, int>, int> Edge; //a, b, length
// A---------B
// length
vector<Edge> prims_algo(vector<vector<int>> graph, int number_of_nodes){
... |
I'm a beginner and it is my first project in Python 2.7.
My goal is writing a script that I can run with two or three arguments.
If run with two arguments like python currency.py RUB USD then the output will be current RUB rate by USD base: .015169.
If run with three arguments like python currency.py 1000 RUB USD then... |
I'm studying design patterns, and to demonstrate a singleton, I've implemented a primitive database connection pool.
ConnectionPool.java
package com.levent.connpool;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class ConnectionPool {
private final static int MAX... |
I've created a voting system that's similar to Stack Exchange's in a Ruby on Rails web app. It's working great - as far as I can tell, all the edge cases are caught. This is the action to cast a vote.
There are some conditions I've had to satisfy:
must not allow duplicate voting, even from console requests
one vote p... |
I have implemented an \$\mathcal{O}(N2^{N/2})\$ algorithm for subset sum problem described in Wikipedia.
That is what I have:
SubsetSumFinder.java:
package net.coderodde.combinatorics;
import java.util.List;
/**
* This interface defines the API for a subset sum algorithm.
*
* @author Rodion "rodde" Efremov
* @ve... |
In the last few days I've played around with Go a little and took the language tour. The last exercise (text here) requires you to crawl a graph that simulates a set of Web pages with links, using goroutines, channels and locking primitives to do it in a concurrent fashion without ever going to the same page twice. I a... |
I've written this code to calculate the Sylvester sequence, which is defined as $$s_n = s_{n-1}(s_{n-1}-1)+1$$ where \$s_0=2\$.
def sylvester_term(n):
""" Returns the maximum number of we will consider in a wps of dimension n
>>> sylvester_term(2)
7
>>> sylvester_term(3)
43
"""
if n == 0:
... |
From the related questions here, I've found this and this answers, both of which suggest Replacing Conditional with Polymorphism, are probably what I'm looking for. However, I'm not sure if polymorphism would be a good choice for my particular case. Below are the relevant code snippets (sorry they're incomplete).
publi... |
I've been working on this game for a couple weeks now as a purely personal project to help myself learn Java. I'd like to know if I'm on the right track with my project.
Items I'd like specific feedback on:
GridBagLayout - I think I'm working this out okay?
Classes - Do I need to break parts of this up into other pi... |
In my Java 8 application there are 3 different classes but each of them contains one similar method, which is dedicated to parallelization of the business logic execution. It's important to note, two of these three methods are called from another static methods, while the last one from instance-based method. Below, I p... |
I've come from a PHP background and I'm really trying to unlearn the bad habits I acquired from not doing things properly with PHP through my own lack of understanding..
I'm looking to advance my understanding and implementation of OOP principles. Below I have a simple email notifier class. I have a few ideas of how I ... |
I wrote this algorithm a while ago, and decided to revisit it and polish it up.
It basically works by comparing each number with all the other numbers once, so comparing the first number to all except itself, the second to all numbers after itself etc, to avoid double comparison. I'm sure it has an official name, but ... |
I recently learned about Linq's deferred execution and a little clearer understanding of IEnumerable. I came back to some code that I had written and decided to change with Linq extension methods. (The method is a helper function for some custom Excel functions that I use.)
Overall the code kind of feels wrong readabil... |
The following functions/routines are an automation of an end of day receipt emailing process that formerly would take up to an hour, but now takes less than a minute.
Things to note: I changed the name of some of a variable or two in order to protect the identity of the company that this is being used for. THe vast ma... |
I am writing a series of unit tests in Python 3.5 unittest, which run the exact same test methods on different datasets. The purpose is to validate proper behavior of each tested function over a range of inputs at different extremes of the likely numerical range of use (large values, small values, badly scaled values,... |
This is my implementation of Dijkstra's algorithm. Could you tell me what am I doing wrong and what should be fixed? I was not sure how to keep track of the shortest outgoing edge from a node and I store -1 if there weren't any edges found yet. I am not sure if it is okay.
#include <iostream>
#include <vector>
#include... |
This code takes a selection of numbers between 1 to 9 which could be 1,2,3,4,5,6,7,8,9 or 1,2,4 or 4,5,8,9, etc.
Looks for every possible combination and compares them to a dice roll of two dice
e.g. If the dice roll is 7 then can it be found in a list which contains
1,2,3,4,5,6,7,8,9 - (Yes, 7 and 5+2 and 3+4 etc)
O... |
I'm new to programming, and I would appreciate any constructive criticism on my code and if there may be a more efficient way to code this.
import java.util.Scanner;
/**
* This program will decide what mechanism a reaction will undergo given information about the reactants.
* I will also include a mechanism to give a... |
I try to write a function which calculates the check digit for shipping label based on the algorithm provided by GS1
http://www.gs1.org/how-calculate-check-digit-manually
Version 1: my first try
public static int GetGTINCheckDigitV1(string code)
{
int sum = 0;
for (int i = 0; i < code.Length; i++)
{
... |
This code is part of a larger code that generates an Arithmetic Quiz, although the code I have show below just saves the score that the user got on the test and their name. When saving the code it checks if the user has taken the quiz before. If the user has taken the quiz before it saves it as 'Older Score' or 'Oldest... |
My code works with small binary tree but with big ones (around 10000 nodes) it takes 15 sec to process.
For small binary tree I'm always getting correct answer and it is fast.
How can I make my program faster for big binary tree?
(x, y) is a neighbour pair when the depth of x and y is the same, the
node color of x a... |
I'm trying to write a Exception Handling class in Python so that I can re-use. If you have any ideas on how I can improve this to output more detailed information I would appreciate it:
class EHandle:
@staticmethod
def printit():
exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(... |
Here is a non-predictive recursive descent parser I wrote for the following grammar:
E : E1 '*' E
| E1 '/' E
| E1 '+' E
| E1 '-' E
| E1
;
E1 : NUM
| '(' E ')'
;
It can be run against the token stream
func main() {
// (m) * (m / (m))
valid := Parse([]Token{
{Value: "("},
{Type: ... |
I wrote code to determine if a string is a palindrome of a permutation. This exercise was taken from Cracking the Coding Interview. I'm looking for any tips on improving it.
#include <iostream>
#include <string>
/*
* Determine if a string is a palindrome of a permutation.
* For simplicity, assume each string conta... |
Here's a small function to check if the property starts with [ or { and parse the value from a sting into JSON or an array. Properties might be a string or intiger also.
import { mapValues } from 'lodash'
export function resolveValues (data) {
return mapValues(data, item => {
if (item.match(/^\[/) || item.match(... |
I’ve written this bash backup script. It uses the --link-dest option of rsync; that way, the user have access to the backed data at any time stamped with relatively affordable data overhead. Any duplicated data should be hard linked; the overhead mostly come from the directory structure.
It’s mostly based on this very ... |
I'm trying to learn to use the C++ Standard Library and some of the modern C++11 features. Can someone review my counting sort algorithm below and critique my style/algorithm/use of the STL? Thank you!
#include <algorithm>
#include <chrono>
#include <iostream>
#include <iterator>
#include <random>
#include <vector>
co... |
This code uses the YouTube API for crawling through a YouTube channel, parsing responses and syncing the channel videos with a local directory.
Can this be optimised or improved?
import subprocess
import os
import urllib.request as urlreq
import urllib.parse as urlparse
import simplejson as json
playlistIds = []
title... |
This is a piece from the complete program.
What it does is parses mathematical expressions of the form (+(*3,x),5) to 3*x + 5 and store it in an object of class Formula. Add,Mul, Div, Exp, X, Integer and Symbols are derived from Formula class. Recursive strategy has been used to parse formulae with greater complexity.
... |
The "parser state" of a module in rubberduck can be one of several values:
//note: ordering of the members is important
public enum ParserState
{
/// <summary>
/// Parse was requested but hasn't started yet.
/// </summary>
Pending,
/// <summary>
/// Project references are being loaded into parse... |
Consider I download my data into this data structures:
public class AThingDTO
{
int AID { get; set; }
string AName { get; set;}
Dictionary<int, BThingDTO> BThingsColl { get; set;}
}
public class BThingDTO
{
int BID { get; set; }
string BName { get; set;}
int AID { get; set; }
List<CThingDTO> CThi... |
My intent is to use this object to cache data from web responses. The cache object should only be valid for the current data.
var myCache = {
Cache: { Date: '', Data: [] },
AddData: function(Name, Data){
myCache.CheckCache();
myCache.Cache.Data[Name] = Data;
},
... |
I would like to ask information to those of you that you are much more experienced than me as I am learning. I would like to create an administrative panel where the only possible option is to be logged in to the admin. Your wisest thing which is to carry out safely login?
Let me explain, I created a MySQL database tab... |
The following class holds an array with products that are generated from a Json file. This is what the json file looks like
[
{
"id": "A101",
"description": "Screwdriver",
"category": "1",
"price": "9.75"
},
{
"id": "A102",
"description": "Electric screwdriver",
"category": "1",
"p... |
Being a newbie into AngularJS, I have overlooked the importance of client side logging until some non-reproducible client-side errors occurred and I realized that they were not logged.
My web application is developed using MVC 5 and AngularJS and my intention is to have a good client side logging that sends errors and ... |
I'm a beginner trying to create a dice game according to the specification given below. This is an improved version of my program based on the feedback given by users on my original question. Again, rather than asking other people to correct my code, I would much prefer to be given hints or general principles as to how... |
I have this method in my rails app:
def find_or_create_session(fbid)
@sessions = Session.all
if @sessions.find_by facebook_id: fbid
@session = @sessions.find_by facebook_id: fbid
if ((Time.now - @session.last_exchange).fdiv(60)).to_i > 5
@session = Session.create(facebook_id: fbid, context: ... |
Is there any way I could tidy this code and make it look better and more appealing?
import csv
math_class = input ("Which math class would you like to see the results of?")
while math_class not in ['1','2','3']:
math_class = input ("Which math class would you like to see the results of?")
sort = input ("How would y... |
I am writing a class that has a few std::string as a member. I can't find clear guidelines on how use them in a safe way. Are std::string any different then int when we are talking about class members? Do I initialize the strings in the correct way? (How) can I improve the constructor?
#include <string>
#include <iostr... |
I am writing a program to simulate some parts of the popular game Hearthstone by Blizzard Entertainment in Java. The first thing that happens in any game is the selection of the character each player will play as, called the "hero." I decided to use JOptionPane to create dialog boxes for this selection for the two play... |
I implemented a function removeDuplicates which takes 1 parameter, a std::string, and returns a std::string without the duplicate characters.
Example I/O might look like this:
removeDuplicates("hello"); //--> "helo"
removeDuplicates("this is easy"); //--> "this eay"
Here is the function:
std::string removeDuplicates(c... |
private static byte[] GenerateData(long size)
{
var result = new byte[size];
new Random().NextBytes(result);
return result;
}
Is it good, robust and efficient solution?
I use my method like this
[TestMethod]
public void WriteAndRead16MBbyZeroOffsetTest()
{
var length = 1024 * 1024 * 16; // 16mb
... |
I want to be able to find a solution to run the following code in a much faster fashion (ideally something like dataframe.apply(func) which has the fastest speed, just behind iterating rows/cols- and there, there is already a 3x speed decrease). The problem is twofold: how to set this up AND save stuff in other places... |
I am trying to write a script to read a CSV file containing 1 million domain names, look up these domain names and store the results in another CSV file. I am trying the following code, but the number of records I am able to parse with time is quite less. I want to optimize the performance of this to be able to parse m... |
I'm consuming some messages from a rabbit queue. Within the consumer/processor I need to invalidate a varnish cache and requeue the message if the purge failed.
I'm using a local purge proxy.
The consumer is a Dropwizard microservice but I'm using a BasicHttpClient because JerseyClient doesn't allow me (AFAIK) to set ... |
Continuing my TDD from exercism.
Write a program that given a phrase can count the occurrences of each word in that phrase.
For example for the input "olly olly in come free"
olly: 2
in: 1
come: 1
free: 1
import java.util.Map;
import java.util.HashMap;
/**
* Counts the word in a given string. Ignores any punctuat... |
I am studying algorithms and I had to solve this algorithm:
Consider the following problem. You have a car such that if you fill it up to full tank, you can travel with it up to 400 kilometers without refilling it. And you need to get from point A to point B, and the distance between them is 950 kilometers. Of course, ... |
I have JSON data which can be an object/array of recursively nested object or array. The value of an array can not be null, but a value in an object can be null. And I would like to return all combinations of these keys and values through depth-first search.
For example:
var data = {
"title": {
"original": "Hitc... |
I currently have a table with over 250 columns, in which ~10-15 columns have column names that have a specific prefix, namely EQP_.
Assume that you do not want to type the names of these columns, but still want only a result set containing those columns.
Some possible solutions I thought of:
Using a common_table_expre... |
I have developed a realtime text web app using socket.io that continuously displays text on the web page. When I run my code below with multiple clients connecting the memory usage for the V8 javascript process on the server continues to grow and garbage collection doesn't appear to happen. Is it something with my code... |
I should implement p0-Pollard with C++14 and a good algorithm. How may I improve my code?
#include <iostream>
#include <assert.h>
template <typename T>
T gcd(T a, T b){
// printf("step1\n");
if(a<0) a=-a;
if(b<0) b=-b;
T c = 1;// -> decltype(a+b);
while((a%2 == 0)&&(b%2 == 0)){
// printf("st... |
I solved the following problem:
Let's consider the following situation. You've invited a lot of children to a celebration party, and you want to entertain them and also teach them something in the process. You are going to hire a few teachers and divide the children into groups and assign a teacher to each of the grou... |
I am looking on how I can improve my writing style and/or how to simplify how I write my code.
# USER: TCG
# Tic Tac Toe (User vs Computer)
import random
def place(num,x):
# Returns all the moves made
for i in range(len(x)):
if x[i] == num:
pos = x.index(num)
return x[(pos + 1)... |
I am using the "Advent of Code" series to help with my PowerShell education. The Day 6 puzzle has a 1000 × 1000 grid of lights. After processing instructions to turn on, turn off, or toggle rectangles of lights in the grid, how many lights are on at the end?
I am confident that this script will produce the right answer... |
This is my first Bash script and I decided to use what I've learned so far to help manage stray processes while I develop in my *nix environs.
I've tested the script extensively and it seems to work (there may be some things I have not caught yet).
If I could get some critiques/tips on the script that would be great.... |
I'm new to C++ and made this basic Tic-Tac-Toe game from scratch. I would like to know if there are simpler or more efficient ways of doing the things that are covered in the code. As I said, I'm new to all this and would like to try and take advantage of all of my resources that are available instead of sticking to we... |
This is my first time working with networks and multithreading in C, and would like to know how to make improvements.
I wanted to make a client program that handles reading and writing to the server in two distinct threads to improve performance. I also wanted to have the user wait 3 seconds before allowing the user to... |
I've been playing about with runtime compilation to allow me to get/set runtime property values in C#, and so far I have come up with a class.
This allows me to write code like the following which works well and is much faster than standard reflection:
TypeWrapper wrapper = new TypeWrapper(target);
wrapper.Set("Value"... |
I have a scenario where I need to chain nest XmlElements, and I got a working solution using a recursive function, but I can't help but feel that it can be made better.
Here's my code so far:
function AppendChild
{
param
(
[string[]]$string,
$obj,
[System.Xml.XmlDocument]$XML
)
... |
Apple's System Management Controller uses FPE2 and SP78 as floating-point formats.
While writing a Java library that that interfaces with the SMC, I ported someone's C function to convert read a FPE2-formatted byte array as a float.
public static float strtof(byte[] bytes, int size, int e) {
int total = 0;
// ... |
This is a problem from programming contest. The original problem can be found here on hackerearth.com.
In the first line there is one integer T denoting the number of test
cases. Description of T test cases follow. Each one have two integers
N and K given in the first line denoting the number of variables and
th... |
I'm learning JavaScript and as a start I'm trying to create a calculator.
window.onload = function() {
var numbers = document.getElementsByTagName('span');
var result = document.querySelectorAll('.result')[0];
var clear = document.getElementsByClassName('clear')[0];
for (var i = 0; i < numbers.length; i += ... |
I just wanted to get some criticism on my programming to make me better. I made a game in Unity, just a simple question and answer game.
Demo
using UnityEngine;
using UnityEngine.UI;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using UnityEditor.VersionControl;
using System.Threading;
... |
(See the previous and initial iteration.)
I have this second version of my LaTeX code. I made it less dry by removing the duplicate keyword definitions shared by the two algorithms being typeset. Also, in the previous version, in the argument of main While loop, OPEN was typeset instead of desired OPEN.
See what I have... |
This is some code I've cobbled together that reads a delimited file. If the user is able to tell us some stuff about the file, it uses the supplied information. Otherwise, it tries to work stuff out itself. Then it pushes what it thinks are the first two rows of data back to the user to see if it's read the file correc... |
I have written a simple yaml based config parser in Python. The idea is that it will get passed around in other scripts after being initialized with a config file within a main function.
I am interested if this code is OK with regards to the following
general best coding practices
interface design
test design
should... |
I have recently solved the following Project Euler problem:
In the 20×20 grid below, four numbers along a diagonal line have been marked in red [here bold].
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 ... |
I implemented A* Search with Array Lists following the pseudocode here.
I have been working with different algorithms on my own, and now, I am trying to optimize them so that I can run them with less code. The actual algorithm I wrote does not use a lot of code, but the setup does (creating the grid and setting the val... |
I have an array like this:
var arr = [
{
revision: 19,
text: 'hello',
details: [
{
id: 5
}
]
},
{
revision: 19,
text: 'hello',
details: [
{
id: 6
}
]
},
{
... |
This code starts a new thread for login and reacts according to the JSON result returned by the server.
I think this code has too many conditionals, exception handlers, and nested functions.
public void Login() {
mButton.setClickable(false);
mButton.setText("Loading...");
final String username = mUserName.g... |
I was recently given a coding test to complete for a potential client. It was a FizzBuzz-type of thing with a two-hour time limit. I had a request to write basic FizzBuzz, then add a special case, then add a report. I didn't get an interview, and they didn't return any feedback so I don't know why. Can you take a look ... |
I'm working on an API that has a lot of controller functions like this:
def create = Action.async { implicit request =>
if (request.body.asJson.isEmpty) {
Future.successful(BadRequest("Missing body"))
}
else {
val body = request.body.asJson.get.as[JsObject]
val companyID = (body \ "... |
I have two functions with loops that behave nearly identically, but with some key differences. As a consequence, most (but not all!) of the code in the functions is repeated. I can accept this repetition, but I would prefer to have the repeated code in a single place, so that I do not need to remember to change both if... |
I am doing a php project with the codeigniter framework. In my controller, I have a function that does the following.
Uploads an image to the server
Add a row to the database. The data would be retrieved from the form that calls the controller.
The best approach might be to put these two things in separate functions,... |
I've written some code for console variables. They support different types e.g. integer, string, vector, float, etc.
Is there a better way to do this? Like with an interface and a class for each different type? (I'm not sure how I would do that.) I also have to create a register function for each type of variable: f... |
I am currently building a small conversational bot, and I am struggling with the architecture. I use Facebook Messenger combined with Wit.ai's API and a Shopify store API. My rails app is the interface between those three APIs.
First, the rails app receives a message from Facebook. It transfers it to Wit, which sends b... |
I have written a draggable parent class using a module pattern:
var draggable = {};
(function(){
var initialMouseX = undefined;
var initialMouseY = undefined;
var startX = undefined;
var startY = undefined;
var draggedObject = undefined;
var startDragX = undefined;
var startDragY = undefined;
var eventHandler =... |
Here's my class for providing a singleton instance of a Redis connection. What do you think?
from redis import StrictRedis
import os
class RedisConnection(object):
REDIS_URL = os.environ['REDIS_URL']
def __init__(self):
self._redis = StrictRedis.from_url(self.REDIS_URL)
def redis(self):
... |
I just wanted to know how can I code more efficiently with my project.
I'm pretty sure that all these nested "if's" can be done easier and with less code.
I made a TicTacToe game with 3 difficulty levels. Easy, Medium and Hard. The Easy level you have 3X3 table, Medium: 4X4 table & Hard: 5X5 table. As you can see I ma... |
I have the following interface
public interface IDocumentController : IController
{
bool Handles(string path);
DocumentView New(string fileName);
DocumentView Open(string path);
//...
string FilePath { get; set; }
}
I have an abstract base class for all IDocumentController types that implements the... |
The code below is the core of a Genetic Algorithm (NSGA-II to be precise, without crowding-distance calculation), but I've taken out all the GA-specific parts and made a generic example. I think I've carried over most of the principles/'constraints' from the original algorithm, but I might have missed something.
As you... |
I'm trying to solve the problem of a whiteboard receiving registrations before, during and after its own initialization. As each registration needs a bit of handling which can happen only after the whiteboard is fully initialized, I need to delay that handling, until initialization has completed. All of this needs to b... |
I am trying to create a binary search tree class in Java and am wondering how I did. I am fairly confident on most of the methods, but fear I may have messed up the delete method. I know I am reinventing the wheel, but am just creating this for practice. I know that I also should have made the class generic, but again ... |
I have written a program in which user enters total number of conditions (cases) and then that many number of inputs to print chessboard.
For example:
3
21
*
.
12
*.
35
*.*.*
.*.*.
*.*.*
Here is my code:
def main():
no_of_case = input()
for i in range(no_of_case):
user_input = input() ... |
I am taking an online training course on Python, and am at the following question:
Write a function called median that takes a list as an input and
returns the median value of the list.
For example: median([1,1,2]) should return 1.
The list can be of any size and the numbers are not guaranteed to be
in any par... |
I've been developing a forum as my first OOP project, I've successfully built a login/registration and other functionality typical in forums.
I'm looking for some guidance in terms of where to take the build and other common functions that will need integrating.
users.php
<?php
class USER
{
private $db;
function... |
I have started learning recursion and search algorithms, especially DFS and BFS. In this program, I have tried to make an implementation of a maze-solving algorithm using DFS. The program is working functionally, but as a beginner I am fully aware there are many possible areas of improvement.
If not in a specific way, ... |
I want to improve my slider class as much as possible. Is this acceptable code for a slider?
I've tried to comment as much as I can. If you want to find out more about the Component class, check out my repository: dxLib.
slider.h:
#pragma once
#include "Component.h"
begin_UI // Namespace define
class Textbox;
class Ri... |
Given a set of time intervals, I have to find the total time elapsed in the union of the intervals.
Test Cases:
int[][] test = {{10, 14}, {4, 18}, {19, 20}, {19, 20}, {13, 20}};
int[][] test2 = {{1, 3}, {3, 6}};
answer(test) == 16
answer(test2) == 5
Both of the tests pass, but I get a "time limit exceeded". How can I ... |
I'm working on a little AI to simulate ants (very basic). The full code can be found on Github. This function (in Ants.py) takes a list of Tuples containing coordinates and tells whether or not the ant is over one of them.
def Got_Food(self,all_foods):
foods = []
x,y = self.location[0],self.location[1]
c_x,... |
I made a single player slither.io game. Here are the features:
You can speed up by holding down the mouse button.
You can eat food and grow both in length and width.
Only 100 food will spawn maximum (eat to generate more)
What suggestions both in game logic and in code structure do you guys have?
(there is only one c... |
Is there a way to write this if tree more elegantly?
if (position.x < 0) {
position.x = 0;
}
if (position.y < 0) {
position.y = 0;
}
if (position.x > 4800) {
position.x = 4800;
}
if (position.y > 4800) {
position.y = 4800;
}
|
I do programing with core php & i don't want to like use any cms or mvc framework. if any handy ideas then welcome it.
index.php file
<?php
/** INCLUDE BSIC CONFIGURATION FILE */
strip_php_extension();
/** GET REQUEST NAME */
$request_uri = trim(filter_input(INPUT_GET, 'uri_req'),'/');
/** CALL REQUESTED PAGE *... |
So I solved Fractional Knapsack problem:
There are n items in a store. For i =1,2, . . . , n, item i has weight wi > 0 and worth vi > 0. Thief can carry a maximum weight of W pounds in a knapsack. In this version of a problem the items can be broken into smaller piece, so the thief may decide to carry only a fraction ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.