instruction stringlengths 71 71.9k |
|---|
Previous question: C# Logging System
I have took your answers on board and added the following changes to my LogManager.cs class:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sahara.Sahara.Core.Logging
{
class LogMana... |
I have written a basic slideshow program that uses pygame to manage the display screen. It cycles through all pictures files in the directory and sub-directories. There is a user configuration section for the start directory, sub-directories to ignore, image file type, display time, full screen or window display and ad... |
I tried to resolve this task:
The integers 14 and 15, are contiguous (1 the difference between them,
noticeable) and have the same number of divisors.
14 ----> 1, 2, 7, 14 (4 divisors)
15 ----> 1, 3, 5, 15 (4 divisors)
The next pair of contiguous integers with this property is 21 and 22.
21 -----> 1, 3, 7, 21 (4 di... |
Here is a first difference function I threw together for a quick check in another program:
use std::ops::Sub;
fn first_difference<T>(input: &Vec<T>) -> Vec<T::Output>
where T: Sub<Output = T> + Clone {
let vec_len = input.len();
input.iter().take(vec_len-1).enumerate().map(|(ind, val)| {
val.... |
I have developed a command line application which prompts the user to initially select an oven and then requests that they cook a pizza. The oven affects the pizzas cooking time. The pizzas information will be printed to the command line as well as the altered cooking time.
I wanted to use the best design principles I ... |
The function redsqrt(n) prints out the most reduced form of the square root of n. It calls on another function perfsq(n), which produces a list of perfect squares less than or equal to n.
from math import sqrt
def perfsq(n):
# Returns list of perfect squares less than or equal to n
l = [1]
i, x = 0, 3
... |
I'm a little unhappy with the look of this "flexible" way of dealing with errors from an API in Ruby:
class ApiError < StandardError
def initialize(response)
message = response.is_a?(String) ? response
: !(response.respond_to? 'body') ? 'Error'
: response.body.is_a?(Hash) ? response.body['... |
This is my second day into C++ and I wanted to get a small review from someone experienced with the language. I'm coming from Python so some stuff seems kind of weird. My plan is to build a little "web store" with this.
#include <string>
#include <vector>
#include <iostream>
#include <initializer_list>
enum class Item... |
I used this code to give -h(help) options to my bash script. It's working fine and I wanted to get the code reviewed.
while true; do
if [ "$1" != "-l" ] && [ "$1" != "-a" ] && [ "$1" != "-h" ] && [ "$1" != "" ];
then
output=$(curl -k -s -u "$username:$password" -H "X-Requested-With: Curl... |
I just built an audio player in Angular 2 using a player component and a player service. It's all working fine, I just feel like there is a much better way to do this.
Should the audio object be in the service or the component? I'm skeptical because I'm using three different observables and I don't think that is the be... |
I've been updating a little text-based game of mine to have the text roll out over a time period to give the appearance that it's being typed. I'm doing this by using non-blocking output with ncurses.
The text to be output is passed to a function called TimedPrint, along with arguments for the screen to print it on, th... |
so I created a database manager and wanted to know if I could improove it in any way? Thanks.
DatabaseManager.cs:
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sahara.Core.Database
{
class DatabaseManager
... |
I took an entire line of input in the form of a string, and tokenized the string into substrings and obtained the first string as the first name and the second as the last name. This program as it stands is very basic and limited however my primary focus was on the creation of generic functions to do all the heavy lift... |
I am trying to use this VBA code to pass a SQL stored procedure multiple values from an excel sheet.
In order to have the procedure run multiple times and insert multiple sets of information into the database, I copied and pasted the parameter section of the code each time I wanted to insert new data and hard coded whi... |
I have a browserify module I've made for resizing two divs I have beside each other. The idea is that I have two panes with a bar between them which I can grab and drag to resize the panes. As one pane gets bigger the other gets smaller. It's not really that important for the code review that this is a browserify modul... |
For a genetic algorithm I'm writing, I need to sub-sequence a list, but I need it to be lazy so I can compose it with other lazy functions. If I introduce strictness into the chain, I risk potentially massive slow-downs since each step in the chain requires a full traversal of the population.
Amazingly, such a function... |
I'm attempting to write a (hopefully) efficient way of "expanding" a 2d array into a 1d array. Let me illustrate what I mean:
Given the 2d array
{{1, 2},
{3, 4}}
and a block width of 2 and a block height of 2, we can "expand" into a 1d array
{1, 1, 2, 2, 1, 1, 2, 2, 3, 3, 4, 4, 3, 3, 4, 4}
Notice, if newlines are a... |
From Rosetta Code:
The Archimedean spiral is a spiral named after the Greek mathematician Archimedes. It can be described by the equation:
$$r=a+b\theta$$
with real numbers \$a\$ and \$b\$.
Here is my attempt to draw it in Python (using Pillow):
"""This module creates an Archimdean Spiral."""
from math import co... |
After reading a certain question on the Stack Overflow website, I tried to write a solution to the problem just for fun. I'm, however, left with the nagging feeling there is a beautiful one-liner that can be used instead.
The question's premises:
Create a function that will receive a string. The function will count ea... |
I'm doing a Euler challenge that is stating to find the smallest positive number that is divisible (without a remainder) by all numbers from 1 to 20. So I did it however, I don't like the fact that I have to guess up to which number the while loop have to go (var s.... s < 303000000) and I guess there are too many vari... |
This question is a follow-up question from here, where I implement the method from @vnp.
I have tested my code and it works, but the 3 steps processing seems a bit long to me. I also tried to write a few if/else, which seems a bit cluttering (e.g. code like newList.nextNode = newList.nextNode.nextNode if newList.nextNo... |
I have a few of files, and total size of them is more than 5 GB. Each line of the files is a IP address, looks like:
127.0.0.1 reset success
...
127.0.0.2 reset success
how can i find Top10 frequently IP in 25s within 500M memory?
Here is my code,but it takes probably 64s and use more than 1G memory.
package main;
i... |
The goal of this code is to print the entity tree of a VHDL project. There are a readme and very minimal tests on the github repo.
I am trying to refactor the code to use generators in order to familiarize myself with yield, and to think in terms of iterators, not raw data structures. Here is my current attempt at doin... |
I am trying to tackle two fairly massive concepts through JavaScript and jQuery, the first being object-oriented programming and the second being how to build robust modular plugins with an OOP approach. So far I've learned it's hard.
Here is an example plugin I built, that I somewhat based my much larger project on; ... |
What do you think about this?
#include <alloca.h>
#include <setjmp.h>
#include <cassert>
#include <functional>
template <::std::size_t N = 4096>
class coroutine
{
jmp_buf env_in_;
jmp_buf env_out_;
bool running_{};
char stack_[N];
public:
coroutine() = default;
auto running() const noexcept
{
... |
I have some Managed Metadata in SharePoint which is in the following format:
Managed Metadata Service
People
Job Title
And I have a list of people, each of whom have a name and a job title, called MyTestList.
What I needed to do was display these people in a TreeView, sorted by their job titles, where some... |
I work with an embedded target that contains a list of commands and registers that may change from one device to another. So I need to build my commands list from metadata received from that particular target.
Unfortunately, the communication with the target is slow and the amount of commands is high. So I cannot buil... |
I want to reduce my repetitive code used to validate inputs values. For that I'm using:
a class associated to the input
a condition to validate the input value
an event handler
First I declare the classes I'm using:
var inputNotNull = '.js-mandatory-notnull',
input2Words = '.js-mandatory-2words',
inputNumb = ... |
I'm currently making a server in Java, as database stuff I'm using HikariCP (because AFAIK, it's the best library). I try to do it as good as possible so I hope some of you can review my classes.
First, the DatabaseManager.java class:
package PKG.storage;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari... |
Okay I've just finished writing a nice tiny C program to have an ASCII spinner (works on Windows and POSIX). I'm quite new to C, so any suggestions would be great. This is designed to be a small function in my other programs, so please point out anything that could cause problems when been integrated into a larger prog... |
I have a text analytics process that I complete for work. This process mines text for different Twitter accounts and finds patterns in the tweets. The actual machine learning pipeline is much more complicated than what's shown below, but this will have to suffice as my minimum reproducible example. In reality, there ar... |
I've implemented the prime sieve of Eratosthenes in Haskell using a mutable array of unboxed Bools instead of the usual pure and immutable datastructures.
My main concern with this code is speed. For large upper bounds, it runs approximately 70% slower than C code implementing the same algorithm.
Memory is already opti... |
itertools.cycle is cool, but it has an internal "storage" that uses up memory. And I wanted to practice "tampering" with built-in methods of classes, which is a new field for me. I tried to implement a class which mostly behaves like a list, but when we try to iterate over it (with for loop, for example), it would jump... |
Left rotate array (a), k times, n is size of array.
I know, we can calculate n, but prototype is mentioned in respective question.
#include <vector>
#include <iostream>
using namespace std;
vector<int> array_left_rotation(vector<int> a, int n, int k) {
vector<int> a1(n);
int np = -1;
for(int i = 0 ;i<... |
I have this view class for constant time rotations of a std::vector:
#include <iostream>
#include <string>
#include <vector>
template<typename T>
class vector_view {
public:
vector_view(std::vector<T>& vec) : vec{&vec}, offset{0} {}
const T& operator[](int index) const {
return (*vec)[(index + offset)... |
I am learning design patterns and I have implemented the abstract factory using generics C#.NET. Is this implementation correct or not? Or is there any SOLID principle violation?
using System;
namespace GenericAbstractFactory
{
public enum vehicles { car, bicycle, truck }
interface IFourWheeler
{
v... |
I have this piece of code, which raises an exception if there are no numbers from 3 services. I really don't like how it looks at the moment.
no_numbers = False
if use_verizon_sms:
if not Api.check_avalible_credits():
no_numbers = True
elif use_verizon:
if not buy_verizon_number():
no_numbers = True
else:
... |
Everyday I manually check that that my systems were backed up. I use the windows file system through the Explorer gui and check that the backup files were modified on the previous day or later.
This script walks the file system backup directory and compares the files modified since the start of the previous day to a li... |
I'm writing simple jQuery script for updating one field on another field's change. It's working, but I'm trying to write good code and use best practices. Can you please tell me what my mistakes and 'bad' things in this code?
Maybe I should use getTotalUserScore() in updateTotalUserScore(), not in $('.js-question-scor... |
Is there a better way to do this?
This function takes, as an argument, a natural number, n, which is between 1 and 52 inclusive and returns a list containing the point value associated with that number as an integer. The aces are the numbers 1,14,27,40 in the respective suits and they worth either 1 or 11 points. The r... |
I am currently implementing a virtual machine that runs a programming language similar to assembly. The difference is that an instruction in this language can have any number of operands. and the machine should not give an error. whatever the operand is inside the memory, the machine should make sense out of it. If the... |
Here is a recursive implementation of the Subset sum problem:
using System;
namespace Exercise
{
class SubsetSum
{
static void Main(string[] args)
{
set = new int[] { 2, 3, 1, -1};
PrintSet(set, "Initial Set.");
sum = 4;
Console.WriteLine("Wanted sum = {0}", sum);... |
I made a very simple Minesweeper using C# and WPF. My method for checking the adjacent mines for buttons is pretty long and could use some improvements, so how would I make it shorter and more "reasonable" so that it would not take so many code lines?
MiniMine.cs
namespace boardgame
{
class MiniMine : boardGame
... |
Normally, in order to have a polymorphic collection, we store pointers to a base class:
std::vector<base*> v; // or std::vector<std::unique_ptr<base>>
v.push_back(new derived{}); // problem: value is stored in a galaxy far far away
There are a couple of issues with this approach:
The std::vector<T> instan... |
This is a student module marks calculator that I was asked to write for a uni revision session in year 2.
Is this a good example of modern C++ code? Is there anything I can improve on or need to change to become a better programmer?
#include <iostream>
#include <cstdlib>
float student_results[5][2];
unsigned int inpu... |
I'm creating a virtual mapping software that essentially breaks coordinates into Areas. An Area is comprised of a defined list of boundary coordinates (coordinates that make the outer rim of the area, which connect to one another).
With this software, I need to randomly select points in EACH area that reside INSIDE of ... |
According to Rosetta Code:
The Chaos Game is a method of generating the attractor of an iterated
function system (IFS). One of the best-known and simplest examples
creates a fractal, using a polygon and an initial point selected at
random.
Task
Play the Chaos Game using the corners of an equilateral triangle
as the re... |
Let's say the model for a razor view has the following name:
Model.Receipt
and there are a couple of places where you do
@Model.Receipt.ID
@Model.Receipt.BillToCustomer
etc.
but you decide to shorten it by declaring the following code block:
@{ var receipt = Model.Receipt;} and now you use this receipt variable instead... |
SUNCE MEH BEEN WRUTEN CODEZ IN MUNY DIFFRNT PROGRAMMING LANGUAGES, MEH THOUGHTZ THAT ME TRY TO WRITE CODEZ IN AN ESOTERIC LANGUAGE. MEH CODEZ CALCULUTS A FAWCTORIAL OF UH USR INPUTTED NUMBAH IN LOLCODE, LOL.
SOME OF MEH QUSTIONS:
IZ MEH CODEZS A IDMITIC LOLCAT PROGUM?
IZ THERE A GOODER WAY OF WRUTING MEH factorial FUN... |
I am a total novice to Python and have been testing my skills recently. I found this particular challenge and wanted to give it a shot. I made this code and it functions well, but very slowly. I was looking for feedback on how to optimize in Python, as well as general Python best practices!
Main.py
from PIL import Imag... |
I've done a small one page project with slider (owlcarousel) & CSS3 animations .
Could you please look at HTML, CSS & JS and check for possible improvements? Thanks in advance.
Here's a page
$(document).ready(function() {
$('.menu-link,.btn-slider').smoothScroll({
speed: 1000,
of... |
I have the following code:
public abstract class BaseViewModel<PrimaryKey, ModelType>
{
//Some base fields
public static List<T> Convert<T>(IEnumerable<ModelType> collection)
where T : BaseViewModel<PrimaryKey, ModelType>, new()
{
var list = new List<T>();
if (collection != null)
... |
It's my implementation. Can I get some opinions on it?
import random
import os
import time
class Game:
def __init__(self, turns, w, h):
self.board = []
for x in range(0, h):
self.board.append([])
for y in range(0, w):
self.board[x].append(random.random())
self.turns = turns... |
Here is the simplest iterative implementation of Subset sum problem that I could come up with1, as a follow up to this recursive implementation of the same problem:
using System;
using System.Linq;
namespace Exercise
{
class SubsetSumBinaryNumber
{
static void Main(string[] args)
{
int[] arr = { 2, 3, ... |
I have a WinForms project that uses the Passive View MVP pattern. In the Presenter of one of my Views I have a function that gets questions and from its Model. But I want to make sure these collections are not empty so that I can inform the user when they are. Right now my code seems very ugly and I wonder if anyone ha... |
(Originally posted on Stack Overflow)
I need to run through a number of bespoke files (I'm unsure if they are unicode / ascii or binary so have attached a snapshot through notepad++). I'd like to count the number of instances of a simple string.
I've managed to get this working using the CreateObject("ADODB.Stream") m... |
Is there a way to refactor the following Python code so that the number of lines in generation of the dictionary can be reduced?
data = frame['data'].split(';')
cat_data = {
'xbee_address': '\x00' + frame['source_addr'],
'state': data[0],
'flow_rate': data[1],
'operating_hours': data[2],
'operati... |
I have written a function in python with three loops which is time consuming. Is it possible to do the same operation in less time with some other way.
Here are my code and sample data you can run at your end
#Expand files to minute-level
def expand_b34(data):
final_list = []
df_columns = list(data.columns.toli... |
I have a workbook that some very non-technical people will be entering data into. In the past, I've had them type over formulas and otherwise screw up the data, so I've locked everything except where they're supposed to enter data, then I've password protected the workbook and worksheet. Unfortunately, Microsoft, in th... |
I've written a backend for a chat app but I'm not sure, if I'm following all the SOLID principles and if my code is clean enough.
IModel interface for my db entities:
interface IModel
{
/**
* get a specific field from the model.
* @param string $fieldName name of the field to return
* @return mixed;
... |
I recently got rejected from interview after I send them this site. They said it is too contrived, and I used Redux which was unnecessary. I really would like to know what is it specifically.
I tried to follow best practices pattern and create dumb components + 1 main layout that manage all functions and state from sto... |
There is a matrix of \$m\$ rows and \$n\$ columns where each row is filled gradually. Given the first row of the matrix we can generate the elements in the subsequent rows using the formula:
$$\begin{align}
a_{i,j} =&\ a_{i-1,j} \oplus a_{i-1,j+1}\quad\forall j:0\le j\le n-2 \\
a_{i,n-1} =&\ a_{i-1,n-1} \oplus a_{i-1,0... |
Recently, the following code was written to help automate some processes that are typically executed while working with a Mercurial database. What is shown below is basically a first draft of the program and was quickly written to test out the idea of creating a GUI tool for others to use.
Question: Are there any obvio... |
I am starting to write code for a keyboard in iOS. It's pretty much hard-coded and I need suggestions on how I can make it more professional style and more efficient.
//row 1
UIButton *row1Btn1=(UIButton *)[_lettersRow1View viewWithTag:11];
UIButton *row1Btn2=(UIButton *)[_lettersRow1View viewWithTag:12];
UIButton *ro... |
In the UI I have a single search text box into which users can type a query. The query will split the string and compare each word to each configured column in the database and return the matches.
The following code works, but I don't know if there is a better way that I'm missing.
/// <summary>
/// Returns a list of u... |
I have a python AWS lambda function that takes JSON records, checks them to see if they have required keys, and then inserts into MySQL db. The function gets invoked whenever a new record comes into the stream def handler.
I'm looking for feedback on the class I've created, as well as implementing better exception han... |
Noobie here. I applied for a job as a Jr. engineer and they gave me this task. After they read through my solution they rejected my application because the code was hard to follow. I'd like to get an idea of what they meant by that and how I can improve the approach I took. The full assignment is below.
Write a progra... |
Here's an approach i came up with for checking IOS versions.
#define __PROCESS_INFO ([NSProcessInfo processInfo])
#define CURRENT_IOS ([__PROCESS_INFO operatingSystemVersion])
#define IOS(x) ((NSOperatingSystemVersion){[x integerValue], 0, 0})
#define IOS9 ((NSOperatingSystemVersion){9, 0, 0})... |
I've been glancing at Game of Life for quite a while, but been reluctant towards graphical packages like pygame. But today I finally got over myself and did it.
Did you know that there the "problem" computationally only depends on one condition? I didn't, and followed the conditions of the game at first.
At first I use... |
This code pulls JSON from a server and delivers some data like imageURL, titleString and videoURL. Then it places them in a UICollectionView and displays them.
import UIKit
import Alamofire
class vcWatch: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
@IBOutlet weak var myActivityIndicator: ... |
I responded to this question about designing around interdependant methods with the strategy pattern.
Afterwards I started thinking about the functional additions to java 8 and wondered if I was being an old foggy stuck in the past and if maybe there was a better way with all these fancy new tricks.
So I started hammer... |
I am new to Go. I am trying to implement a simple watchdog. It calls a function once after a certain delay has elapsed; kicking it resets the delay. Kicking it after the function has already been called restarts it.
type watchdog struct {
interval time.Duration
timer *time.Timer
}
func NewWatchdog(interval tim... |
I need to compute the summation of:
$$\left\lfloor\frac{\text{sum of triplets}}{\text{product of triplets}}\right\rfloor$$
from integers of an array.
Input:
5
1 2 1 7 3
Output:
6
Explanation:
The following triplets exists in the given array:
1 2 1
1 2 7
1 2 3
1 1 7
1 1 3
1 7 3
2 1 7
2 1 3
2 7 3
1 7 3
Considering th... |
Given n and k, I need to find Euler's totient exactly k times where n and k are very large numbers. Can anyone help with an optimized solution for a large number?
#include <iostream>
using namespace std;
int gcd(int a, int b)
{
if (a == 0)
return b;
return gcd(b%a, a);
}
int phi(unsigned int n)
{
... |
(See the previous iteration.)
What does this program do?
This program gives you a command line interface for managing your personal telephone book. The program supports three actions:
Adding a telephone book entry.
Removing entries by their IDs.
Listing the entries.
Synopsis
For adding an entry, type:
./TelephoneBook... |
I'm working on my first jQuery plugin for a lightweight dropdown. This dropdown behaves just like a ordinary <select>.
Before implementing new features I'd like to know if my current approach is clean and efficient (I care about readability and performance).
/**
* Dropdown plugin.
*
* @license MIT (https://opensour... |
I wrote a script which logs memory usage of a process (pid in file), and reacts in case a limit is reached. I run the script nightly. In my case, the process concerned propably has a memory leak and locks up the whole system after a couple of days. Hence, the script should reboot the system if excess memory is used. Lo... |
I recently coded the Dutch national flag problem in Java and wrote some tests.
The array in zero-indexed.
Please take a look at how I verify that elements of the output array are in the right order. It's the method verifyDutch
The Dutch national flag problem
public static void dutchFlag(int[] input, int mid) {
if ... |
I'm implementing an iterator which takes a single value and which you can advance for n times with a dereferencing yielding the single value - but before or after that range of n 'positions' you can't dereference. So it's as though you filled a length-n std::vector with a single value and were taking a const iterator o... |
I've implemented a Game of Life Kata with the aim to get to know Consul's K/V store. Although not the main purpose of the exercise, it would be nice if somebody reviewed some of the bash code in the Kata, as my experience with bash is not as extended as I would like. My main concern is about writing idiomatic bash (ie.... |
The code below is an attempt to mimic std::vector from the C++ standard library in the C language.
The implementation is purely macros, in the C99 dialect, and requires the non-standard __typeof__ keyword.
I am interested to learn of both coding mistakes and design mistakes.
The project resides on SourceForge, in case ... |
I am a beginner in Zend Framework 3 and I want to hear your opinions about the code that I wrote. I don't know how exactly I can connect forms, and validators together that the code will be quite nice and readable.
Register method
public function registerAction()
{
$form = $this->form;
$viewModel =... |
I've always loved making games and using SFML, and up until a few days ago, I've had to re-write code over and over again. So I decided to write a game engine so I can reuse my code.
I've never done something like this before. I've read about it, and I watched a few videos. I'd love if you could look around, give me so... |
I have just completed an implementation a like button for an Instagram-like app, but now that I am looking at it I feel that there is something off. Maybe it is my formatting or maybe I am not quite conforming to the MVC pattern I am not sure. I am not very experienced, so I was hoping someone with more knowledge would... |
I have been working my way through the problems in the book Cracking the Coding Interview. The instructions were to maintain an animal shelter that operates on a first in, first out basis (i.e. it is a queue). People must adopt the "oldest" (based on arrival time) of all animals at the shelter, or if they would prefer... |
I'm trying to figure out how my code could be improved. I solved a HackerRank problem from the Cracking the Coding Interview section, and am thinking that it should be able to be solved a simpler than what I did.
The problem is as follows:
Strings: Making Anagrams
Alice is taking a cryptography class and finding anagr... |
I have a tab delimited file which contains about 2207 rows with 4 columns of floats or int types:
Id pos value1 value2
01 1123 0.76483 0.9001
02 1124 0.20 0.9800
Another file is to be compared with which contains about 27041 rows with also 4 columns:
name Id pos1 pos2
s13e 01 ... |
I am currently working in a project (I have simplified it for the sake of question) that requires a container to store students and retrieve them as fast as possible or access them with \$O(1)\$ if possible. I will also be deleting students from any place but always adding them at the end of the queue.
I have three st... |
This code will return a list of the prime factors of n, and the prime factors are repeated so that the product of the list is equal to n.
import math
def product(iterable):
"""
Returns product of all elements in iterable
"""
p = 1
for x in iterable:
p *= x
return p
def generate_pri... |
Consider the following piece of code.
public static String[] choosePatterns(int total, int toChoose, int numOfPatterns1) {
String[] patterns = new String[numOfPatterns1];
int x = 0;
StringBuilder data = new StringBuilder("");
List<Integer> indices = IntStream.range(1, toChoose + 1).mapToObj(i -> Integer... |
I took a stab at solving this problem from Hackerrank in Javascript, and would like your valuable feedback as to time/space complexity and just about any additional improvements.
Problem URL: https://www.hackerrank.com/challenges/cut-the-sticks
My JS implementation:
function main() {
var n = parseInt(readLine... |
Given a set of items with a weight and a value, this problem gives the subset of items which maximize value so that their combined weights is less or equal than a given maximum weight. This solution runs in \$O(w\cdot n)\$ where \$n\$ is the number of items and \$w\$ is the max weight.
#[derive(Debug, Clone)]
struct It... |
I have only been self teaching myself programming on and off for about 5 months. The purpose of me writing this class is to incorporate the knowledge that I have gathered since I started.
using System;
using System.Collections;
using System.Linq;
namespace GenericDataStructures
{
public sealed class ArrayList<T>: I... |
The objective is given a list of items, remove the last occurrence of a specified item from the list using only user-defined functions except for very basic built-in ones like car, cdr, =, - etc. For example, if we've been given the list (A B A C), using our procedure to remove the last occurrence of A from the list sh... |
This post elaborates on NBA*: Very efficient bidirectional heuristic search algorithm in Java.
I have made the following changes:
Added an explicit type for representing digraph paths: DirectedGraphPath.
If the target node is unreachable from the source node, a TargetUnreachableException is thrown instead of returnin... |
I was trying to create a function to delete the node at index i from its current position and insert it after node at index j from a std::vector<Node> nodes. These container is logically a circular container of nodes, that is there's no actual first or last node, i.e. after nodes.back() comes nodes[0].
I really need th... |
I've been doing some 3D graphics in OpenGL lately and I needed a way to work with 4x4 matrices. My implementation supports the following operations:
Matrix-matrix addition.
Matrix-matrix subtraction.
Matrix-matrix multiplication.
Transformation matrix creation.
View matrix creation.
Perspective projection matrix creat... |
I'm new to php and OOP, and for learning I started writing an application that would help me and my flatmates to manage our expenses and debts to one another.
The full source is available at https://bitbucket.org/nicocool84/coloc-web/src. I tried to use the MVC(S) architecture without using a framework.
The project tre... |
I am using Mongoose ODM and NodeJS to implement CRUDL operations on MongoDB for further use with REST API. Initially, I've implemented functions using Promises but then switched back to callback style.
My questions are:
Should I stick to traditional callbacks or to the default Promises? In this context, I got back to ... |
Python lacks dynamic unpacking. Example: You want to unpack a list, let's say coordinates, but don't know whether it contains 3 items or just 2.
x, y, z = [1,2,3] works only if len([x,y,z]) == len([1,2,3]).
x, y, z = [1,2] results in an error. You could add try and except blocks but that could be complicated.
The best ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.