instruction stringlengths 71 71.9k |
|---|
I want to improve the code, in which you can enter a grey bitmap and it will return you a colored one.
function ChangeBaseGrey(bitmap, color)
{
var canvas = document.getElementById("imagesColored");
var ctx = canvas.getContext("2d");
var dataBitmap = bitmap.data;
var r0 = (color >> 16) & 0xff,
g0 = (color >> 8) & ... |
I want to improve my multithreading competence and tried to build a compact doublebuffered way to separate two threads where one is only displaying the state and the other one updates the state. So I am here to hear whether I done it "right" and what to improve.
#include <thread>
#include <mutex>
#include <iostream>
#i... |
Follow up to Removing code smell from Room Booking code
This program organises cruises in which it sets up the ship with cabins/rooms. It also does reservations with customer information and the cost for available cabins/rooms.
This is my main class # program:
class Program
{
static void Main(string[] args)
... |
I'm writing a script that deals reads UTF-8-encoded XML files and writes parts of those files into a tempfile for further processing.
Sometimes, the input files will have a few malformed characters. If it's just "a few" occurrences, I want those glossed over, but if the file is majorly corrupted, I want to see an error... |
Here is my take on (a lighter version of) Java's BigDecimal. I originally wrote this as a replacement for BigDecimal in order to improve performance during serialisation and data manipulation.
public class SimpleDecimal implements Comparable<SimpleDecimal> {
private long value = 0L;
private int fractiona... |
I have been looking at this method for a long time and I have finally refactored it into something that I believe is much more readable. I am not totally happy with it though so I would like to get other opinions about it. There are a great many questions about complex if-else structures here on Code Review, so I am ... |
PLEASE NOTE:
The code below has "commented out" code; however, no code is actually commented out!! Check my GitHub link below. I did that solely to highlight the relevant code sections. Code in my MainActivity and BaseCalculatorActivity, for example, are tightly linked to Android. Those are irrelevant to the alternativ... |
As I mentioned in Node.JS fs.rename can not move files in right way. And it should be solved with stream piping. Please verify this code and answer questions in comments:
var fs = require("fs");
var moveFile = function(sourceFile, destFile, callback) {
var sourceStream = fs.createReadStream(sourceFile);
sourceStream.... |
I am new to Angular and feel that I'm doing mistakes and reinventing the wheel. Could you please review my code and share your ideas about how it can be improved. Demo
The problem is very common. I have a list of items (countries) that can be loaded inside a directive controller. I have an Id of selected item (selected... |
I am trying to change static to dhcp in the /etc/network/interfaces file and vice versa using Python.
def setMode(mode,port,interfaces):
#If the port's mode is not configured in the interface file, add a line for it, and return
if "iface "+port+" inet " not in interfaces:
newLine="\niface "+port+" inet ... |
This is my code for doing a roll back with multiple MySQLI prepared statement.
I want to know if anything is wrong with the code.
$newRegistrationDataArray = array(
"date" => $date,
"name" => $name,
"address" => $address,
"country" => $country,
"occupation" => $occupation,
"emailAddress" => $em... |
I have a content management system for an iOS app built with Rails. Right now there are three different types of content. The first two are just strings uploaded into a textfield by the user. One is Twitter handles and hashtags, the other is URLs. The second type is photos.
The user can upload as many individual instan... |
I'm creating a WordPress theme in HTML 5 which is relatively new to me. I've read up on it and I read things that seem to contradict one another or differing opinions. One of the big things is where and when to use the <header> tag. I've heard 3 different things:
Anywhere that contains <nav>
Only once around your logo... |
Here is my code where I have 3 functions that do simple arithmetic:
#include <stdio.h>
/* The following Code Contains 3 functions
* that compute simple arithmetic such as
* computing the sum of 3 integers and divison
* of three floating integers.
*/
void getSum(int x, int y, int z);
double doDiv(float one, float... |
I wanted to allow components of my program to communicate without the components knowing about each other, thus keeping coupling low. So I devised some template classes that implement the observer pattern and allow classes to send messages of any type, providing they inherit from a message interface base class, and a m... |
I'm trying to parse words from a badly garbled text file that contains many repeats. It's about 100k characters in length and was formed from joining many substrings in alphabetical order.
I'm curious about other methods for finding words without using whitespace.
def unique_words(string):
words = dict()
p1 = ... |
I have a function which I am calling an infinite number of times (or until a condition is met). The problem with this recursive function is that on a higher level, it is called by a worker thread which pushes and pops to a deque. In the meantime, I am iterating through a file with the main thread which is a lot quicker... |
This is a version I made:
#include <stdio.h>
#include <stdbool.h>
#define MAX_STACK_SIZE 255
typedef struct
{
int array[MAX_STACK_SIZE];
unsigned int count;
unsigned int max;
} Stack;
void initialize(Stack*);
void push(Stack*, int value);
int* pop(Stack*);
bool isEmpty(Stack*);
bool isFull(Stack*);
int ... |
I am new to jQuery and currently practicing. I wrote a little piece of code to show and hide a navigation on click and change the text of the button when the navigation is opened and closed.
I am fresh in this area, therefore I would very much value getting some feedback about the code. For example, are there any ways... |
I just need to know if it's decent or not.
Project home
import glob
import tornado
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
import tornado.websocket
class server(tornado.websocket.WebSocketHandler):
def on_message(self, message):
self.modDirectory = 'modules/... |
I wanted to get better acquainted with variadic templates, so I decide to try to implement a function like D's writeln(), just for fun.
void writeln()
{
std::cout << "\n";
}
template<typename T, typename ...Args>
void writeln(T firstArg, Args... extraArgs)
{
std::cout << firstArg;
writeln(std::forward<Args... |
The following question was taken from Absolute Java 5th ed. by Walter Savitch:
A government research lab has concluded that an artificial sweetener commonly used in diet soda pop will cause death in laboratory mice. A friend of yours is desperate to lose weight but cannot give up soda pop. Your friend wants to know ho... |
I made a class that encapsulates the common pattern of keeping an array contiguous when an element is removed by swapping the last element into its place.
A few specific things I'm wondering about:
Is it unsafe for non-POD types (because of the memcpy)?
Is there a more efficient way to add a new object (so it doesn't ... |
Here is a problem came from codingbat:
Given 2 strings, a and b, return the number of the positions where
they contain the same length 2 substring. So "xxcaazz" and "xxbaaz"
yields 3, since the "xx", "aa", and "az" substrings appear in the
same place in both strings.
There are several answers but it may hard t... |
This is a follow up to my previous question, now that I've read up more about modern C++ (specifically C++11) and the answers in the question. I'm using MSVC/Visual Studio 2012 Update 4.
Specific things I'm wondering about:
Am I doing the Exception right? I asked on SO regarding an access problem I had, but I also wan... |
I want to implement a method which, given some camelcased or underscored String, will return a list of separate words that make up this String.
Examples:
ISomeCamelCasedString -> {I, Some, Camel, Cased, String}
UNDERSCORED_STRING -> {UNDERSCORED, STRING}
camelCased_and_UNDERSCORED -> {camel, Cased, and, UNDERSCORED}... |
I'm trying to read certain values from an object. What would be the best practice to do so?
$jira_object = json_decode(trim($jira_value->data));
$this->_displayName = $jira_object->user->displayName;
$this->_issueID = $jira_object->issue->id;
$this->_issueKey = $jira_object->issue->key;
$this->_issueFieldSummary = $ji... |
I'm a Python noob. This is the code I'm using:
for i in argv[2:]: # argv[1] isn't required by s.py
if ' ' in i:
argv[argv.index(i)] = '"%s"' % i
args = ' '.join(argv[2:])
os.system('s.py '+args)
Is there a more elegant way to do this?
|
I've written a script that will allow me to enter a serial number for each received product, in-line in a table. First you enter the amount received, which increases the size of the <select> to that amount. Then you can enter new serial numbers through the s/n text box, submitting with TAB or Return.
Additionally, sele... |
The following question was taken from Absolute Java 5th ed. by Walter Savitch:
Write a program that starts with a line of text and then outputs that line of text with the first occurrence of "hate" changed to "love" . For example, a possible sample output might be:
The line of text to be changed is:
I hate you.
... |
I get a CSV dump of all employee records from our payroll system once a week. The CSV has something like 28K records. The key between the two systems is the employeeID.
I import this in to PS and run a query to look up every employee in AD based on their employeeID and pull down the DN for that user. I store this as $M... |
I've recently started working on a java project, and the main purpose of it is to get better at Java.
I've decided to make an IRC bot for twitch. But after some hours of progress I already see my Bot class growing. And that leads me to believe that I'm learning bad habits or I'm just doing it all wrong.
So I would love... |
I have an object that represents a PDF file. In the constructor, I pull out various information about the file name and make it available via properties:
public class Invoice
{
//public properties
public string FullPath {get { return this.fullPath;} }
public string FileNameWithoutExtension { get { return t... |
The code below is converting: data from one format to another
# input sample
{
productText: [
{
"language": "en",
"version": "1",
"sequence": 1,
"text": "blah",
"textType": "ROMANCE"
}
]
}
# output sample
{
productText: [
{
sequence: 1,
textType: "ROMANCE"
... |
The code gives correct output. How do I calculate time complexity for code like this?
The program finds all the combinations of items and sees if the combination gives the max profit. If the last item can't be added or there are no more items left, it checks to see if this value of knapsack is maximum or not.
import ja... |
1
/ \
2 3
/ \ \
4 5 8
/ \
6 7
Width of a tree is maximum of widths of all levels.
For the above tree:
width of level 1 is 1
width of level 2 is 2
width of level 3 is 3
width of level 4 is 2
So the maximum width of the tree is 3.
This code is attributed to GeeksF... |
I'm currently working on optimizing a Barnes-Hut implementation (connected to a previous post I did) and I need help to optimize it further.
After some testing, the main problem appears to be in the Insertion algorithm, which takes roughly 3-10 times as long as the second longest part of the program.
The basis of the p... |
My factory is using method injection because I thought this was the best way to make it so far. Besides, I doubt it is a good thing after having to call on its Create method from within a dependent object.
The only way I might think of whilst continuing to use the parameterized factory Create method, is to inject the d... |
I have been using the TryXXX and GetXXX pattern lately to give clients a choice whether to trap an exception or to read a boolean. An example of this concept would be System.Integer.TryParse and System.Integer.Parse.
It is my understanding that you should get two benefits from this:
using an if statement in calling c... |
I'm coding a Reversi game, with an artificial intelligence using the MinMax as the search algorithm. My concern is that (most) search algorithms needs to store a lot of instances of "states", in my case, board states. What I want is to represent a BoardState with 64 SlotState (Empty, White Disk or Black Disk), with the... |
When a property is essentially a boolean value for whether or not an attribute exists or is set a certain way, is it more appropriate to create an object that does not list the option attribute in its __init__() call, or is it better to simply create the object with the 'falsiest' version of that attribute?
Consider th... |
This is not related to a Minecraft clone.
I am currently writing a turn-based strategy game like Final Fantasy Tactics. The game is played on floating voxel-style islands, which are generated from heightmap images (will soon be dynamically generated using system.drawing). I already wrote the world generator (15 minute ... |
I'm trying to find all possible product of two 3-digit numbers. When I work with small ranges, I'm able to get an output almost instantly but when the ranges are big, it seems to take really long time. I ran the code below and still didn't get an output past 15 minutes. Is there any way to to shorten the time to get th... |
I'm not sure if it would be better to make the envelope into an extension of the Rectangle constructor.
The physics seem a bit dodgy, it works well most of the time, but sometimes the boxes overlap and sometimes the bouncing doesn't work properly.
var envelopeHeight = 100;
var fallRange = 8.5;
var fallMidpoint = 75;... |
As my title states I'm just looking for a little input on how I can improve one of my side projects when I'm not doing my CS assignments. All my program is, is a primitive randomizer for Battlefield 4 classes and weapons (because I can never choose what to play). But since I am still new to java (second semester in) I ... |
This is probably going to be my final question regarding controllers. I feel like I have a good enough understanding of them now and am able to write them cleanly.
I've recently adapted a less error prone way of communicating with the corresponding View. But I would still like to know if there is anything I could furth... |
As Stack Snippets are live on Code Review now, I wanted to do something quick in it as part of rolfl's challenge on meta. And when you make things quick, they probably get dirty. And when things get dirty, you refactor. And when you don't know how to refactor, you post it up for review.
So, as many of my previous quest... |
This my first real program in python. I welcome harsh criticism. I tried to make it as efficient as possible. Trying to balance speed and readability as well. My program takes a file of text and parses and counts the frequency of the length of each word.
An important specification I left out is I'm using 2.7 or earl... |
I have an input[type=range] element which is customized using CSS to look more modern.
I'm unhappy with my CSS because of the need to use position:relative on the wrapping element and position:absolute on an invisible range input.
I'm wondering if I made this logic unnecessarily convoluted. Is there a way to achieve t... |
I am trying to implement Java's floatToIntBits() and intBitsToFloat() methods in C++. The latter method is the inverse of the former method, and the purpose of the former one is to pack a 32-bit floating point number into a portable 32-bit integer format. More specifically, my replacement function float2ul() for floatT... |
Follow up of - Which is a better implementation of a stack data structure (based on an array)?
Please review my stack implementation from before. I've made it dynamically sized if needed and made a few tweaks.
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
typedef struct
{
int *elementData;
unsig... |
I wrote the following script and php code for long-polling architecture by googling references, I would like to know if this is long-polling or short-polling, ...because I am not sure:
bc_test.js
jQuery(function($) {
var data = [];
function pullNotification() {
var params = {};
new RPC.Call({
'met... |
The following question was taken from Absolute Java 5th ed. by Walter Savitch:
Bicyclists can calculate their speed if the gear size and cadence is known. Gear size refers to the effective diameter of the wheel. Gear size multiplied by pi (3.14) gives the distance traveled with one turn of the pedals. Cadence refers... |
I was asked to do a technical test with the following specification, but my solution was rejected and I was not selected for the available position (Junior to "normal" level, with 4 days of time to finish the test). Could you point out which areas need improvement in my solution?
In software company X, engineers work ... |
I am new to jQuery and needed a solution for the following problem:
There are 3 images in a row and when the user clicks on one of them all three pictures are hiding and instead another image shows up (depending on the click). So while the markup and CSS is quite simple and only a quick draft the jQuery was the main is... |
I have two ViewModels with the one referencing the other:
public class GiveViewModel
{
[Required]
public int GivenLifelines { get; set; }
public string ToUser { get; set; }
public string FromUser { get; set; }
}
public class UserDetailsViewModel
{
public GameDetail gameDetail { get; set; }
pub... |
Is my layout of the if/else statement reasonable?
It feels clumsy to me to spread the termination condition over the first three lines of the function. Can I squeeze it into one or two lines? Would it help if I used the ternary operator? How can I make the JavaScript more idiomatic (while still using recursion)? Any o... |
Currently I'm using this code:
<?php
/*
Clean, Simple, Minimal.
*/
$pages = array('home', 'login', 'register', 'logout', 'test');
if (isset($_GET['p']))
{
$page = $_GET['p'];
if (in_array($page, $pages))
{
include('pages/' . $page . '.php');
}
}
else {
echo 'Hi';
}
?>
I want this to be as... |
Given a chess coordinate as a string (e.g. "a1") I'd like to transform it into a 2-D array (so, for "a1" I'd like to get [1,1]).
Here's what I came up with:
def safe_pawns(pawns)
pawns.inject([]){|res, pwn| res << [pwn.split('')[0].index(/[a-h]/) + 1, pwn.split('')[1].to_i]}
end
Can anyone suggest a refactoring p... |
I have the ubiquitous "validate and save" scenario, wherein the Save() method performs various validity checks and proceeds to save the data. The solution works just fine, but I am interested to know how elegantly and correctly this code can be refactored.
First, the domain:
public class Car
{
public int Id { get; ... |
I need to get the average of multiple averages calculated basing on data contained on a sql database.
To do that, I'm using this code:
$a = mysqli_fetch_assoc(mysqli_query($connessione,"SELECT AVG(voto) AS mediaa FROM values WHERE type ='a'"));
$b = mysqli_fetch_assoc(mysqli_query($connessione,"SELECT AVG(voto) AS med... |
I am writing an X application with Xlib in C, and this code is for error handling and error printing.
How to make it simpler and clearer without using a large amount of fprintf?
int XB3DS_Warn_Code (int Warn_Code)
{
switch(Warn_Code)
{
case WARN_Failed_To_Connect_To_Display:
fprintf(stdout, "[ WARNING ]... |
I have this code, but I think it is too clumsy. It feels like a 12 point turn, is there a way to optimize it?
Please note that this generates new rows from existing rows.
//Create New Dataset
DataSet myDataSet = new DataSet();
DataTable myDataTable = myDataSet.Tables.Add("Temp");
myDataTable.Columns.Add("ID");
myDataTa... |
I saw this codegolf challenge and I set out to try and write a solution for it. I'm nowhere near an expert codegolfer (or programmer), but it was an interesting exercise.
Now I'm wondering how to improve my code, as it feels really bulky (especially compared to some of the answers to the challenge). Note that I'm not l... |
How could I improve this code?
public class DALUser
{
SqlConnection conn;
SqlCommand cmd;
public void ExecuteSp(string Spname, Dictionary<dynamic, dynamic> Params)
{
try
{
initialize();
cmd = new SqlCommand();
... |
I have 20+ key set. Keyset is like:
Key[0] = { "PossibleKey0", "PossibleKey0Another", "AnotherPossibleKey0" }
Key[1] = { ....
There is an encryption which needs to be broken, it will receive 20+ keys, one after another. So it applies decryption one-by-one.
So key[0] has 3 different possible keys, same for key[1], key[... |
Unfortunately, I can't use the Tomcat session for storing the key/value pairs for each user (restricted because it's an IVR domain-based project).
But I need the same functionality like a Tomcat session.
For every user I can get a unique id (call Id). So it's like the Tomcat sessionId.
I have developed the following c... |
I am developing a mysqli database wrapper. I've made an effort to make this as fast as possible and easy to use.
However, now I want to start adding callbacks (for fetch), and make this mysqli-only dependent (still using get_result).
trait dbExtras // connection-independent tools
{
public function echoQuery()
{... |
I am trying to account for the errors in double arithmetic in a C# program I am writing, and came up with this first solution that seems to work well for most cases:
double errorMargins = returnDouble * Double.Parse(Unit_Class_Library.Properties.Resources.AcceptedDeviationConstant);
double roundedValue = 0;
... |
I'd like a general review of my version of Conway's Game of Life. Right now, it's very simple, and doesn't lead to anything interesting yet, as the "seed" generation is randomly generated and small; so it tends to die off rather fast.
import Data.Char
import Data.List
import qualified Display as D
import qualified Data... |
Here's what I got:
[TestFixture]
public class CompositionRootTests {
[Test]
public void FormsShouldBeBoundToViewsThroughConventionBinding() {
GivenIHaveANewKernel();
WhenBindingFormsToViews();
// Then
kernel.Get<IMainView>().Should().BeOfType<MainForm>();
}
[Test]
p... |
This is quite basic but useful to test various (9) different models using one set of data. I have tried to make it clear and use the PEP8 formatting.
I am currently creating a version that can read CSV files to make it even faster. I'd like any suggestions on how I could improve my code or any hints as to what I coul... |
What I am working on has sets of window controls. Controls are constantly being either destroyed, or created.
void ChangeControl() {
// remove all controls, existing, or not
hwnd = GetDlgItem(hWnd, IDC_BTN_FOOA);
DestroyWindow(hwnd);
hwnd = GetDlgItem(hWnd, IDC_BTN_FOOB);
DestroyWindow(hwnd);
hwnd = GetDlgItem(hWn... |
I'm a C#/Java full-time developer who is trying to pick up C++ purely for educational reasons. I've tried to solve a pretty simple ACM ICPC problem and would love to hear all kinds of criticisms on how to write acceptable modern C++ code. (Seriously, tell me that my code is a joke, as long as you can tell me how to mak... |
I wrote the following Concern module. Is it good practice to perform all the calculations in the included scope? How can it be improved?
module Pagination
module Helper
extend ActiveSupport::Concern
included do
class << self
def paged(params, custom_per_page = nil, custom_page = nil)
... |
Today I created a script in Excel that migrates data from a specific Word document and copies a portion of it to a cell in Excel (the date to be specific).
The file input is
Last name, First Name, Grade - (Rank) (Completed On YYYY-MM-DD HH:mm:ss)
and each person is on a new "paragraph" (aka line) in Word.
Sub Search... |
This is the code for my first CS1 project, I hope to be posting my code here to track my progress of learning the language of C++. I shouldn't be too shabby, since I know C considerably well and have reviewed C++ code here before.
Write a program that allows the user to enter a time in seconds and
then outputs how ... |
The program reads in an operation, and then numbers, and does stuff to them based on that.
Exercise number 1 at this linl
For example, ./this_file sum 1 2 3 would yield 6
I'm fairly certain I don't need all the #includes, but I had added them at some point to deal with a problem, some ideas I kept others I didn't.
I've... |
I started anew and completely refactored the way I implemented Pokemon type evaluator.
Also, first use of a lambda expression (Case of using it, but still don't fully grasp how it's working). I'm wondering if this is a bit more complex than it needs to be, but otherwise I think these are some significant improvements.
... |
Background
As this related question describes, there does not appear to be a canonical way to validate XML files against an XSD then subsequently transform them using an XSL template with file paths determined from a catalog resolver.
The XSL templates can be XSLT 1.0 or XSLT 2.0, the latter requiring Saxon9HE.
Problem... |
I was issued the following coding challenge from a company to write an encoding and decoding function:
Encoding: This function needs to accept a signed integer in the 14-bit
range [-8192..+8191] and return a 4 character string. The encoding
process is as follows:
Add 8192 to the raw value, so its range is transla... |
Does this function
automationStatusIsSuccessful = (data) ->
data.Automation.Status isnt "FAILED" and data.Automation.Status isnt "COMPLETEDWITHERROR"`
make the conditional statement more readable or less readable?
With:
automationStatusIsSuccessful = (data) ->
data.Automation.Status isnt "FAILED" and dat... |
While misreading the beginning of Stage I of this classic paper by Ken Thompson, I decided to create program that replicates itself.
Let's say this program is called Replicator.exe. Upon running it once, it will create a new executable, Replicator_1.exe. Upon running either of those executables, a new executable, Repli... |
I'm studying Angular and want to develop my own notification alert. This is what I done, I like it and it's working like a charm but I think that it can be improved:
Do I need to use it in conduction with a service? If yes, how?
Will it be better if it became an E (element)?
I needed to put style="display: none;" (see... |
Follow up of - Dynamically-sized stack - follow up
I've took the tips given to me, and what I did now is:
changing the function names to have a prefix
making the pop() function only popping and not returning the value as well
checking for OOM exception / scenario that 0 is passed to capacityIncrement variable when ini... |
Would anyone be so kind as to review my code for Memory?
import java.util.*;
public class Cards {
public boolean gameInProgress = true;
public void shuffleCards() {
Scanner userInput = new Scanner(System.in);
List cardList = new LinkedList();
List matchedCards = new LinkedList();
... |
This is a simple JavaScript Fizz Buzz solution based on a Codecademy exercise. I refactored it down a few lines after seeing these implementations.
I wanted to post here and see what else I can learn from this basic exercise.
for (var i = 1; i <= 20; i++) {
var result = "";
if (i % 3 === 0) { result = ... |
For the purposes of this code review, I will use the standard library, but pretend that <cstddef> is <stddef.h>, that I didn't use std::cout, that new and delete[] are overloaded and call custom malloc functions, etc. So this is -std=c++11 -ffreestanding.
Here are my questions:
Currently my tohex function returns a bu... |
In keeping with using FizzBuzz as an introduction to a language, I present FizzBuzz with a Fortran95 twist:
For multiples of 3, print Fort, and for 5's multiples print Ran. For multiples of both, print FortRan.
Looking especially for style and common practice criticisms. A hint on how to left-justify the values in a st... |
Cousins are nodes at the same level of the tree, with different parents.
They don't have to share the same grandparent.
My solution depends on having a binary search tree with unique elements.
This code is faster than writing a special find(Node *) that returns the node's level and parent, and comparing results for eac... |
Some background:
I'm writing a number of classes that ensure user input is properly validated, and is rejected if it does not conform to expected types (there's also some extra options such as setting bounds and finite sets that the values can come from). There are a number of basic types (Integral, Boolean, String, Do... |
To help myself learn Racket, I ported a simple JavaScript ircbot module I wrote for Node.js to Racket. The Racket version is built atop the Racket irc package, so the low-level code is handled by that. My module simply provides some utility functions to make it easier to implement IRC bots.
My code is as follows. I kno... |
A recent question inspired me to implement a Fraction class. I decided to write this one in vba, because I like writing tools for the poor souls that still have to deal with that language myself.
I really wanted to be able to create a Fraction instance with a static-like syntax, so I created a FractionType class with a... |
To understand the concept, I implemented the stack operations using a linked list. Please review the code and tell me your suggestions.
Node.java
public class Node {
public int data;
public Node next;
public Node(int data) {
this.data = data;
}
public void displayNode() {
System.out.print(data);
System.o... |
The following question was taken from Absolute Java 5th ed. by Walter Savitch:
Write a program that outputs the number of hours, minutes, and seconds that corresponds to 50,391 total seconds. The output should be 13 hours, 59 minutes, and 51 seconds. Test your program with a different number of total seconds to ensur... |
Given \$f(n) = 1 + x + x^2 + x^3 + \ldots + x^n\$ and the fact that computers take more time when multiplying two numbers than when adding, how can we work out the result with greater efficiency?
#include <iostream>
using namespace std;
double powerWithIntExponent(double base, int exponent)
{
if(exponent == 0)
... |
There is a test of OO knowledge called Iffy Tractor. The task is to refactor the code and make it as much flexible as possible for the future modifications.
I have placed the code here.
It was taken from here.
This is a kind of a part of the game with a tractor unit, which receives the commands from user. So the possib... |
I tend to feel the need in my Knockout applications to pass along a reference of the root view model down to the sub view models. However, I don't like the fact that I then have a dependency that lies both ways: root has a list of children, and each child a reference to the root.
The Scenario
Here's a typical example, ... |
I would love some feedback on the following code for BFS traversal in a binary tree. Is there a cleaner way to write this?
abstract class Tree[+T]
case class Node[T](value:T,var left:Tree[T],var right:Tree[T]) extends Tree[T]
case object End extends Tree[Nothing]
def bfs_v2[T](node:Node[T]):List[T] = {
def en... |
For understanding the concepts, I've implemented the Queue data structures using a linked list. Is there anything to improve?
LinkList.java
public class LinkList {
private static class Node<T> {
private final T data;
private Node next;
public Node(T data){
this.data=data;
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.