instruction
stringlengths
71
95.1k
I don't have much experience using either OOP or PHP since this is probably my first thing ever written in this language. I've had some exposure to OOP but I'm not used to writing programs that way. I would greatly appreciate some feedback concerning OOP and PHP best practices, clean code, and overall design. I'm also ...
I have written a small PHP script to get a variable from the URL and echo it in the body ID. An example of the url: http://www.example.com/?var=123 I have added this to the head of my HTML page: <?php if (isset($_GET['var'])) { $var = $_GET['var']; } else { $var = NULL; } ?> The body tag of the HTML page look...
I have decided to rewrite what I did here, following the suggestions to use smart pointers. I will rewrite the other data structures as well using smart pointers where appropriate. I just want to see how my code stands now, I am sure there are still areas I need to improve or fix. I again want to thank this community i...
I implemented a custom Sliding Window Spliterator in Java. Do you have any ideas how this could be improved? Thinking if replacing the buffer with a plain array could have a positive impact on the performance side of things if done correctly. I'm not going to use that code in any production system, just exercising. pu...
A simple concept yet I seem to have written it in a complicated way. I have written some C++ source code that should: read in a file parse it save the data to a class print out all the saved class data I am absolutely new to C++ and OOP and Programming and English. #include <iostream> #include <string> #include <fstr...
INTRO I am using an Excel worksheet as my "database." No headers so [F1] is assigned to column one by default. I filled the entire column, all 1,048,576 cells with RANDBETWEEN(1,20). I then hard set these values by copy/pasting as value. It is very slow. Much slower than using Excel functions would be to generate same ...
Just made a simple Vec class, nothing fancy but I am open to suggestions for improvements. Of course, this is not suppose to replace or used for the same tasks as std::vector. This is more like opencv's Vec and eventually I want to include this in a bigger project of mine. #include <cmath> #include <vector> #include <i...
I'd like to improve how ownership is handled within a simple interpreter written in Rust. The interpreter takes simple calculator like expressions and returns either a string of the AST or a number of the evaluation: // Simple expression for working on numbers enum Exp { Add { e1 : Box <Exp>, e2 : Box <Exp> }, ...
I am creating a simple bot that collects coins in-game. The code runs under a game-loop so there are 60 ticks p/s Here is the function that I use to check for the nearest coin (Game object) to be collected: public GameObject getNearest(ID objectID) { LinkedList<GameObject> object = new LinkedList<GameObject>(); ...
For a new project, I've started learning Golang. This is one of my very first steps in Go. The objective that I've given myself is to convert int to a String representing the roman numeral of that int. The supported range shall start with 0, negative numbers can be ignored, and it's okay for now that for negative numbe...
I have been trying to learn Python and just solved Euler Problem 3: The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143 ? I am looking for any feedback on improving efficiency and the code itself. My code: from itertools import count, islice def is_prime(number...
I'm pretty new to working with databases, and I would like to know if I've made some common, major design flaws in my implementation. For context, the whole project is intended to be used by a single user. The code I want reviewed: class DatabaseConnection { //properties private MySqlConnection _connection; ...
I was very bored over one of my breaks this year, so I built a Hardy-Weinberg equilibrium simulator for two unrelated alleles of the same gene. Hardy-Weinberg equilibrium is when there is no evolution, random mating, and a constant population size. The idea behind the simulation is to show the effects of genetic drift ...
I have two view controllers which have same tableview. One is for Post and one is for Profile, which also contains a post by a user. I have decided to reuse the code, so I have created the class PostTableView. class PostTableView: UITableView { var arrayPosts:[PostTableViewCompitible] = [] { didSet { ...
I have the following method: private P2SAFile populateP2SAFile(File file, Message out) throws Exception { String filename = file.getName(); FileType fileType = extractFileTypeFromFileName(filename); String instrument = null; Boolean calibrated = null; String destination = null; Date date = new D...
I want to write a generic parser which takes a value, and type and returns label of given value instead. Currently, this is my code: import a from "../constants/a" import b from "../constants/b" import c from "../constants/c" const find = (value, fromArray) => fromArray.find((term) => term.value === value); const getL...
I have a large HTML document where everything is inside a main div, structured like this: <div class="main"> \\block 1 <div class="header"><span>content1a</span><span>content1b</span></div> <p>content1c</p> \\block 2 <div class="header"><span>content2a</span><span>content2b</span></div> <p>cont...
This class is intended to be used in situations where queue.Queue does not suffice, because the following two properties are needed. Every item in the queue can have a priority assigned. No item can occur more than once in the queue. So here is my current implementation. I would be happy to hear your ideas on how the...
Coming to the close of week 1 learning a programming language (Python) Looking for general review, comments, and tips Objective of Code The objective here was to practice pulling information from dictionaries within lists and also adding dictionaries created from user input. Code def make_album(artist, album, tracks =...
I have some code that I'm trying to speed up. Maybe what I've got is right, but whenever I ask on StackOverflow somebody usually knows a clever little trick "Use map!", "try this lambda", or "import iteratetools" and I'm hoping somebody can help here. This is the section of code I'm concerned with: #slowest part from...
I need to print signed 64-bit numbers in decimal form. Program runs in freestanding environment (no C library available, libgcc may be unavailable too, or may not work correctly). So I can't use printf(3) function. I'am trying to write function, which will be able to convert number from binary form (int64_t) to ascii. ...
This is not really a question but I'd like to obtain some opinions about this simple class. For an old project I had the necessity to load some php template files that includes some foreach() and for() loops and other variables loaded from a database. I was start thinking how to obtain this using a templating class and...
Code Summary The following code is a data science script I've been working on that cross-validates a fixed effect model. I'm moving from R to Python and would appreciate feedback on the code below. The code does the following: Split data into train and test using a custom function that groups/clusters the data Estimat...
Sometimes in advanced OOP scenarios, a class needs to hold instances of another class which needs to hold a reference to the "parent". For example when you have a dynamic UserForm control that needs to "call back" to the parent form that created it, or when you have a ViewAdapter that talks to some UI, which in turn ne...
I have a VBA code which copies same data from Multiple sheet and then paste it in "Main" Sheet. It then auto fills the blank cells for values from above and then it delete all the rows Where H:H is blank. However being novice in VBA, i feel my code has too many loops, which makes it run slower. Moreover if have the "Ma...
I have a function which plots n randomly generated non-colliding circles. The circle is a Circle object, part of matplotlib.patches. We will generate each random circle by its center and r, for example : r = random.uniform(min_r, max_r). To make circles with no collision, no two circles (with c1, r1 and c2, r2 as the c...
I'm curious if there's any way I can substantially improve its speed (it runs through >200k rows). I think I'll most likely need this once, so please bear with me since it probably looks terrible. Thanks for reading! Code I would like reviewed: Option Explicit Public Sub RemoveDuplicates() Dim r As Range Dim r...
I have written a Python program to loop through a list of X files, open each one, read line by line, and write (append) to an output file. Being that these files are several GB each, it is taking very long. I am looking for suggestions to improve the performance of this program. I have no formal CS training so it's lik...
Learned alot in this first week, following PCC, but biggest leaps came from the community and others giving their time to help, thank you! All input appreciated! ObjectiveGoals were to fill a class with user inputs from multiple users and then be able to call methods to each user input created class. (... did I say tha...
function ExecuteWindowsTaskScheduler { param( [Parameter(Mandatory = $true)] [String]$TaskName, #e.g. "Open Notepad task" [Parameter(Mandatory = $true)] [String]$TimeToExecute, #e.g. "3:45pm/am" [Parameter(Mandatory = $true)] [ValidateSet('Once','Daily','Weekly, Monthly')] [string]$Frequen...
We assume we have unlimited number of coins and bills. My code works fine but the method optimalDMCA() has a Cyclomatic Complexity of 8. import java.util.*; import java.math.*; class GoodEnough { long how2 = 0; long about5 = 0; long this10 = 0; } class Solved { static GoodEnough optimalDMCA(long s) { ...
I'm wondering how I could condense the following (redundant on many levels) code: import java.util.*; public class Randomstems { private static final STEM[] allStemsW1 = new STEM[25], allStemsW2 = new STEM[25], allStemsW3 = new STEM[25]; public static void main(String[] args) { Scanner getAnswer = ne...
Is there a more efficient way to write the following PLSQL statement? It seems inefficient to me to have the SQL statement nested inside the where clause. SELECT REQ_ID FROM REQUESTS R WHERE P_REQ_ID IS NULL AND EXISTS ( SELECT * FROM REQUESTS WHERE P_REQ_ID = R.REQ_ID )
Issue: Code base has lots of data structures which are accessed between threads with >= 1 writer. Application logic becomes obfuscated due to lots of mutex locks. Solution: Create a template class which provides synchronized access through member functions. This seems very hacky -- Is this a futile effort / antipatte...
I am trying to learn some Common Lisp, except basically all of my computing background is the C family of languages. So, I'm starting small. I have made a Tic-Tac-Toe game, and I am looking for some constructive criticism. In particular, is this idiomatic Lisp? Is it styled normally? What would an experienced lisper im...
I have a basic method to export files, however I have several arrays to export and I need the files to have these names, I'm trying to make it by the enum list, however when I do it, the file isn't created and I'm wondering is there a way to combine the directory+name of array+.txt? Here's method that doesn't export no...
I am trying to learn trie and this is my first implementation. I started off with the idea of being able to handle different data types for key and value; however, I found the data structure a bit complicated and switched to just string for keys and int for values. So, parts of my code are specific to some data types w...
I'm trying to learn Python, so I made this project. I think there are problems with the code, but I don't know how to improve it. import os import random clear = lambda: os.system('cls') def game(): def printOutCorrectGuess(): print('Correct! There is/are ', lettersInWord, 'of this letter in this word.') ...
Given a fraction p/q, I want to count the number of unit fraction solutions $$\frac{p}{q} = \frac{1}{u} + \frac{1}{v}$$ with some contraints $$lower \le u \le upper$$ By manipulating the first equation and completing a square you arrive at a formula $$(pu - q)(pv - q) = q^2$$ So the number of solutions is related to th...
Original Question Problem Description You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. You may assume the two numbers do not contain any leadi...
This is a nice workqueue class template to keep the gui fluid, while data is being written into a database or into some file/network... #include <cassert> #include <condition_variable> #include <mutex> #include <thread> #include <functional> template <template <typename> class Function = std::function> class workq...
I am writing Python program which calculates area and perimeter of various 2d shapes. I am trying to learn about OOP and this is the first project which I wrote from scratch. I'm wondering how to let user now what attributes he should use in order to get the correct result from particular class? For ex: C = Circle(ra...
Question- Generate all prime numbers between two given numbers. https://www.spoj.com/problems/PRIME1/ My attempt- I used segmented sieve method. t=int(input()) import math def segsieve(x): if x==1: return False for i in range(2,int(math.sqrt(x))+1): if x%i==0: return False return...
Yes, I made it up. This program checks if an entered string is a palindrome or not by assigning a char variable the characters in the inserted word in reverse order. The program then takes the variable and appends it to a StringBuilder to be able to compare the original word and the finalized reversed version. package...
I recently finished a simple Blackjack game that I made to get better at C#. I am wondering how I can better organize or simplify my code. There are 4 files: Program.cs /* Blackjack Game Copyright (C) 2018 This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Publi...
Given a binary tree, return all root-to-leaf paths. Example: -- 1 / \ 2 3 \ 5 Output should be: ["1->2->5", "1->3"] My approach: I walk the branches from left to right, finding the first leaf on the leftward tangent collecting the segments until the last node. I collect the vectors of the tree into a passi...
I'm working on part of a service for data processing. The main idea of the service is to get the input data, process it and return the processed data to another service. Input and output data format are flat JSON documents (documents without nested objects and lists, only first level objects). The core entity of this s...
I wanted to make a function that will dynamically retrieve a line from a stream to a buffer. This function just needs to take in the char* and the stream to read from. It'll keep allocating a bigger buffer until it can read all the data into the rtr variable (terminated on new line). Any ways I can improve this would b...
Motivation As an exercise, I wanted to try implementing function overloading in Python 3, i.e. to implement a way of defining multiple functions with the same name and then calling the appropriate function based on the given arguments in a function call. I know that this isn't necessary with Python and my understanding...
I'm doing some exercises in OOP and I just created a program that calculates amounts of denominations in a change at the shop. So, let's say something costs 10, I give 25.30 (for some reason), so I should get as a change: one 10, one 5, one 0.20, one 0.10. When I started to create the program, I thought it would be nic...
I wrote some code to do regularised linear regression and it works, but I don't like the fact that I've had to double call the functions when plotting, nor the fact that I've sliced those calls to get the parts that I want. import numpy as np import matplotlib.pyplot as plt def fit(phi_fn, xx, yy): w_fit = np.lina...
This AjaxCompound is invoked every time when the user types a key for search or click to sort. It contains 1million data 10 distinct rows by compound name. It takes 1.1 minutes and return only 1-5 KB data to search (general and column specific) or sort or pagination. Any way to reduce the execution time? Any wrong prac...
I have this piece of code placed in ESI class. There is switch statement nested in a try-catch block and it feels simply wrong for me (I have a suspicion that I'm close to exception driven development). I'm looking forward to read your suggestions on how could I potentially improve this code. @PostConstruct public void...
Is there more efficient, proper way, to write a function like this? The effect I want to achieve is to remove CSS classes in three steps, one after another. function loadColors(){ setTimeout(()=>{ document.querySelector('.class-1').classList.remove('class-x') }, 0); setTimeout(()=>{ document.querySelector('.cla...
The script will work through each number from 0 - 10. aList=[3,5,... over 10k numbers ...,2,2,6] Let’s say, for example: findSquence01=[3,5] or findSquence02=[3,5,3] count = 0 for i in range(len(data)-len(pattern)+1): tmp = [data[i], data [i+1]] try: for j in range(len(data)-i): print(i, i...
I have written a game in which the user has to guess six numbers between 1 and 49. I want that my program gets checked in the following criteria: Does this program meet the requirements of object-oriented thinking and programming? Did I have used the library of the Java language wisely or were parts of the program imp...
I need to count the number of substrings of s which contains both the strings a and b. This is what I did till now: a = input().rstrip() b = input().rstrip() s = input().rstrip() min_length = max(len(a), len(b)) n = len(s) count = 0 for i in range(min_length, n+1): for j in range(n+1-i): temp = s[j:j+i] ...
I am finishing up an actor system (like those used in 90s games, like Doom, Unreal, etc.), which currently deals with damage and event handling. actor.cpp /* * Actor System * (with Event System included) * * Author: Gustavo Ramos "Gustavo6046" Rehermann. * (c)2018. The MIT License. * * This system basically allo...
I am making a poker application in JavaFX. When I try to display the cards on the screen it is working perfectly fine. Yet I have a method with a lot of duplicated code in it. I have tried to compress the code into 1 function with a for loop but I couldn't get it to work. Anyone has an idea how to get rid of the dupli...
I am trying to make a multi choice quiz with a score to count. This is the first time I've used Python and I'm finding it difficult to make the code work properly. How can I make the code shorter and work better? It tells me my code has an infinite loop, how is that so? #Convert the 0 into a number so we can add scores...
I have a data object like that: const data = { "id": ["1", "2", "3"], "name": ["foo", "bar", "baz"], "age": [20, 30, 40 ], "location": ["pluto", "mars", "jupiter"], }; Those properties are matched in the array order. I need to create an array which holds all the items like: [ { id: '1', name: 'foo', age: 20...
I am reading a text, that from a higher level explained adjacency list implementation of a graph. I have now tried to implement this as simply as I could. I did not see any reason to have an actual vertex or node class. Based on my implementation, does it look like I understood properly how an adjacency list graph work...
This program estimates the likelihood for a string to belong to a certain natural language by computing the cosine similarity between an input string's and several natural languages' letter frequency, and it allows the storage of a prediction as a list in a .txt file. I would like to know whether improvements (both for...
I'm making an ASCII roguelike game and while writing the code for processing the player's move I can't decide between these two options. I have defined a class named point to handle positions in the game, like this. I would also like to know if this is a good idea or if I should use a structure instead. Should I pass a...
This is the problem: You are given queries. Each query is of the form two integers described below: - 1: Insert x in your data structure. - 2: Delete one occurrence of y from your data structure, if present. - 3: Check if any integer is present whose frequency is exactly. If yes, print 1 else 0. The queri...
I wish that someone could review my code and find faults with my style and weak areas, so that I might work upon it. prime_numbers = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163...
I have been studying C# for 2 weeks already, I wrote a simple math game but not quite sure how bad it is. I'm just teaching myself to code through internet references. If you could review my work, I would appreciate it. It is a simple math quiz game player gets 1 point in every correct answer the game will be over whe...
I have addressed the critique for this post and resubmitted it for iterative review; C++ multithread pool class. Class for creating thread pools with the latest C++ standard. Currently C++17 and C++2a. It currently only accepts and executes parameterless routines. Multiple functions may be enqueued via variadic templa...
I am working with a Star Wars API from http://swapi.co/api/. Here's the problem that I was working on for the Star Wars API problem. And the code works and prints out the exact output that I desired. I would like to get some code review. > # You are a Coordinator for the Star Wars rebel forces and are responsible for...
I think the general functionality is there, but sometimes it looks a little slow/clunky when I try to run my app. Highlighting cells can be slow as it skips over some of the cells I hover over if my mouse is moving somewhat fast. Also the speed the grid evolves doesn't always consistent. I suspect that calling setState...
I have used d3 to draw a sine wave going around a circle. This is the very first time I've used d3 or drawn a SVG and I'm fairly new to JS as well, so I don't know if I've overcomplicated it/if there is a simpler way to achieve this. I'd appreciate some feedback - especially if there's any way to make my code more conc...
We have specific Email2Case emails that come in that we just want to delete. Below is a simple APEX trigger that I think will do the trick. trigger CaseDeleteDatabaseCompaction on Case (after insert) { List<Id> casesToDelete = new List<Id>(); for (Case a: Trigger.New) { System.debug('Subject: ' + a.Subjec...
I've solved an assignment a week ago, which is my first assignment using Lisp. Tasks: Task 1: a. Given a tree as recursive lists, print the tree in breadth first order. b. Given a tree like in task 1a, print it in child-successor order. Input for Tasks 1a and 1b: (A (B (C (D))(E (F) (G (H)))) (J (K (L (M) (N (P)))...
The purpose of the application is very simple. PlantList is a object containing a list of PlantConfiguration. Each PlantConfiguration has two schedules: HourlySchedule and DailySchedule, as well as a TimeZone. The program reads a PlantList object, stored as a JSON file in the settings, and returns an enumerable of Sche...
The following small function receives a range and returns it with only the cells that contain constants or Nothing if there's none. Private Function GetConstants(ByVal Cells As Range) As Range On Error GoTo ErrHandler Set GetConstants = Intersect(Arg1:=Cells.SpecialCells(Type:=xlCellTypeConstants), Arg2:=Cells) E...
A school student here. Hope you are having a nice day. So, I implemented a Singly Linked List in Python and of course also a Node. I tried to make it have the best Big O time complexity I could. Here it is, please tell me what do you think can be improved, changed, etc. class LinkedList(): """ A basic class imp...
This code finds duplicate files in Linux. I assume that MD5 hash will return unique hash number. What can I improve in this code? #!/usr/bin/python; import sys import subprocess import os import hashlib FIND_CMD = "find . -name \*.* -print" BUFFER = 65536 #Get path from the user root_path = sys.argv[1] #Checks tha...
I have a matrix A containing numeric values and a matrix B containing 0/1s: A <- matrix(1:25, 5, 5) B <- matrix(c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0), 5, 5) A B 1 6 11 16 21 0 0 1 0 0 2 7 12 17 22 0 0 ...
I'm new to python and programming in general and I found Project Euler problems a good way to practice python. But my code is pretty slow. It seems to work, didn't wait long enough for the code to print the answer though. Any tips on how to make it faster ? I assume that you don't have to check every single number but ...
I have this xml file and i am parsing it with php simplexml. My XML file looks like this: <?xml version="1.0" encoding="UTF-8"?> <noticias> <noticia url="noticia-1"> <titulo>título da notícia 1</titulo> <desc>plain text.</desc> <texto>plain text.</texto> <img></img> <in>Publ...
I have written a simple snippet of code that implements a function that returns a list of primes up to a certain integer n. Assuming that this function could be called several times in the script for different values of n, I wanted to make it as "lazy" as possible—that is, able to reuse previously-calculated variables....
I wrote an Othello version with limited UI to try to learn python(3.7) and OOP. The game has 8 classes. Start creates a controller object which is responsible for the logical flow of the game. Controller creates AI objects that chooses moves based on difficulty settings. Start also creates a GameFrame object which cont...
Intro I wrote this code to solve sudoku as part of an assignment (closed now) for an AI course. The program works correctly and I am quite happy with the code. Please let me know if I am rightfully pleased or if the implementation could be so much better. This is a pure code review question so don't hold back on anyth...
My first delve into vimscript was writing a plugin for folding markdown lists. I reckon there are a few idioms I'm missing here, so I would greatly appreciate any comments to improve the plugin. I've noticed something akin to "header guards" in C family languages among popular plugins: if exists('g:touchdown__loaded') ...
I'm attempting to minimise the "duplicate" functions I have defined which do almost the exact same thing, but I'm unsure of the best way to do it, I thought of passing in the type I'm looking for (e.g. 1 for GreyLeader, 2 for HeadMarshal etc.) but that ended up looking too messy for my liking. Could you guys perhaps su...
I have made a password reveal feature, however the code is duplicated. Essentially all I want to be able to improve the code, however I'm not exactly sure how I could do this, all I know is it would consist of some form of loop. I would go straight to jQuery but there is no need in 2018. This is my functionality markup...
I have an implementation of the flood fill algorithm. Assume that an image is provided as a vector of vectors. It takes in parameters of a square to segment the image into two regions. It also takes in a point where mouse click is detected. Based on the point, a particular segment in the image will be filled by a custo...
I have implemented function templates that take a begin and end iterator as well as an optional comparator for user-defined types. It was my intention to mimic the usage of std::sort. The three sorting algorithms I used were bubble sort, selection sort and merge sort. I perform merge sort in place. #ifndef BRUGLESCO_DA...
This code is intended to generate a class (domain) from a class with class with similar/identical properties (api). Motivation is to speed development time when using clean architecture. import org.joda.time.DateTime import org.joda.time.DateTimeZone import javax.inject.Inject import kotlin.reflect.KClass import kotlin...
I write this class to process and output xml/rss feeds. I'm still working on, but any suggestion will be appreciated. As a little trick if the xml file come from an online resource, I've added a method to cache the xml file as a json file. <?php class NewsFeed{ public $url; private $cachedFeed; private $c...
I was working on this problem, where I am constructing a Object Oriented structure of file system where you can have Directories and Files. The Directories could have sub Directories and files. I have the following layout and I am looking for feedback on improvements or if my approach is wrong. My OOP design has three...
I implemented the Dijkstra algorithm. I'm looking for feedback how to make this more pythonic. I'm also wondering if I should move get_shortest_path method out of the Graph class, this would mean I need to expose the vertex list. The MutablePriorityQueue is just the code snippet from: https://docs.python.org/3/library...
I made an encoder/decoder for the Vigenère cipher. This one is using a table, not the remainder technique. Please let me know what you think can be done to improve performance, etc. import string import itertools class Vigenere: """ A class for vigenere encoding and decoding. Doesn't preserve spaces, UP...
My version of implementation ObservableDictionary. Its should work as ObservableCollection, I hope. Based on referencesource Dictionary implementation. .NET 4.5 framework using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel; using S...
On Wikipedia, there is a graph shown: It shows the quadratic \$y = ax2 + bx + c\$, varying each coefficient separately while the other coefficients are fixed (at values a = 1, b = 0, c = 0) As a learning experience I decided to replicate these plots in Matplotlib as follows: import numpy as np import matplotlib.pyplot...
Question Input number of test cases. Input each test case and output its next palindrome number. Link: https://www.spoj.com/problems/PALIN/ Language Used: C++14 (gcc 6.3) My code #include<iostream> using namespace std; int main() { long long int t,rev=0,x,no,f=0; cin>>t; while(t>0) { cin>>no;...
I'd love to get feedback on my first go at Dijkstra's algorithm in Rust: use std::cell::Cell; use std::cmp::Ordering; use std::collections::{BinaryHeap, HashMap}; use std::fmt; use std::fmt::Debug; use std::hash::{Hash, Hasher}; use std::rc::Rc; fn main() { let s = Vertex::new("s"); let t = Vertex::new("t"); ...
I wrote a simple data handler class. I would like to know if I can make my class more simple and efficient for doing the identical feature. My Code : #include <iostream> #include <string> #include <vector> using namespace std; class MyData { public: void add(const pair<string *, int> &elem) { size_t i...
I just learned Merge sort, and I really like this Merge sort implementation since it is very logical and very easy to follow. If I was asked in an interview to implement merge sort, will this implementation suffice? I know creating those new arrays every time the mergeSort() method is called is bad practice. I fully un...
In a followup this application was turned into a GUI using FLTK: Cleaning a file / Word Query GUI (FLTK) I did the following two exercises in Programming: Principles and Practice Using C++ (2nd Edition), by Stroustrup, which build upon each other: From Chapter 21 (Algorithms and Maps), Write a program to "clean up" a...