instruction stringlengths 71 95.1k |
|---|
I have this following code to sort an array of strings order by ASCII value (alphabetically) using bubble sort.
#include <stdio.h>
#include <string.h>
int main(){
char txt1[201][10], temp[201];
for(int i=0; i < 10; i++){
if(i){scanf("%c", txt1[i]);}
scanf("%[^\n]s", txt1[i]);
}
for(int ... |
I have a controller in an ASP.NET Web API application which generates a CSV file. The controller looks like this:
[System.Web.Http.HttpGet]
public HttpResponseMessage Download(int? id = null)
{
if ( !id.HasValue)
return new HttpResponseMessage(HttpStatusCode.NotFound);
HttpResponseMessage result = new ... |
I'm a first year computer engineering student who's learning about algorithms and data structures. I've implemented a parallel merge sort algorithm in C++ and would like constructive criticism. This was done in Visual Studio on Windows.
Some thoughts:
portability isn't a concern I have atm.
merge_sort isn't using tail... |
I wrote a simple library for reading RIFF-encoded files in C++.
I tried to adhere to modern practices and provide an idiomatic API, but there is one part that sticks like a sore thumb to me: the way you get the contents of a "chunk" is by calling a data() method, which returns a std::vector<char>. Most of the other way... |
I'm using standard jQuery Ajax to update values in the database and reflect the result in an output. This repetition seems like bad practice and I don't know enough about jQuery to consolidate this correctly.
jQuery
$("#vendorticket").change(function() { //Input/Select tag
var output = ("#vendortick... |
I'm working on a Quantum Random Number Generator and wanted to get some feedback on the project so far.
I'm using PyQuil to generate machine code for the quantum computer, first to create a bell state placing our random bit into a superposition, then I measure the bit to collapse the superposition and repeat the proces... |
Here are the changes I've made thanks to suggestions made by @vnp, and @Henrik Hansen. Here is the link to the previous code review: Linked list implementation along with unit test - Round 2
I've made some new additions that were not mentioned and added more unit tests. I really feel like I'm improving!
Implementation
... |
I wrote a solution to Course Schedule II - LeetCode
There are a total of n courses you have to take, labeled from 0 to n-1.
Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]
Given the total number of courses and a list of prerequisite... |
I have created a thread-safe and lock-free memory pool program using C++11 features. A couple of notable features:
g_memStack is a stack that contains the memory unit; we can allocate memory from it.
g_waitingReclaims is something like a stack that contains units waiting reclaim from the memory unit.
g_allocatingCount... |
Improve Request to Reduce Queries
I have a web application, where users can upload Documents or Emails, to what I call a Strema. The users can then define document fields email fields to the stream, that each document/email will inherit. The users can then furthermore apply parsing rules to these fields, that each docu... |
About the Program
It's a simple implementation of Observer Pattern.
The choice of different NotifyMethod will affect how those observers are notified. The SimpleNotify in blow just uses a simple for loop.
The concrete Observer is initialized with a concrete Observable that it want to observe. In the blow program concre... |
I am trying to create a Repository & UnitOfWork for Data Access Layer. In my current implementation I have to modify my UnitOfWork everytime I create a new repository. I would like to avoid that and also keep the functionality to extend my repository abstract class.
Following is my generic Repository & UnitOfWork inter... |
I have a sniffer tool which populates my DB with data found after parsing the packets and filling them in. Since each row in my table deals with one packet, I had to make a procedure that provides the correlation between packets. I fill that using the stream_index column.
+--------------+------------------+------+-----... |
I'm new to C language and want to read a string line by line, I made this function and want to know what do you think about it, can I rely on it a production environment ?
/**
* this function is not thread safe,
*/
char* strReadLine(char* text)
{
static char* text2;
static int start = 0;
static int len... |
This is for some quantum mechanics software so there will be references to molecules/atoms etc but the core issue is a python logging one, unrelated to all that.
I have a couple of logging decorators, one for logging what the program is doing, another to log exceptions (along with their full stack trace and some class ... |
I created a brainfuck interpreter in javascript. It works good to me as I have seen no bugs in my compiler. I like to get a suggestion and review from you to what should this compiler improve.
Here's the short code:
function bf(str, input){
var array = str.split("");
var memory = [0];
var pointer = 0;
var result ... |
Purpose:
I wanted a way to improve event clarity and event code organization. I
observed that every single event flow went through the following
steps:
Trigger -> UI Change -> (Async) Action -> UI Change
Here is a JSFiddle.
Notes & Concerns
Something about the name of the class seems bad, but I can't come up... |
Approach
All data is submitted into my DynamoDB from another Lambda > API Integration function whereas the lastUpdated row gets inserted as null and then the function below basically polls my database every 1 minute looking for new rows that have a null value & performs actions on them until the lastUpdated can then be... |
I am trying to improve my code to find the tennis court line intercepts so that I can find the boundaries of the different quadrants of the court.
This is the tennis court image I am trying to analyze
This is the final result
I achieved this by first finding the white pixels in the image, then applying canny edge dete... |
this is a really short code, but I'm trying to improve my Python skills. I've got a DataFrame, with a week variable, for every week I want to know the number of different id's in that week, and then get the maximum number of id's among all weeks. I achieve that doing this:
listt=[]
for i in range(df.week.max()):
li... |
I am making a data-driven bond screening and I have as input a big dataset of 1526 columns and 2412 rows. For 10 columns it takes 2 minutes processing time at the moment, which is too much. The following function takes 90% of the time:
Input of the function is df: a pandas series, where the index is a time series and t... |
I am trying to write is_device_mounted script, which in turn will serve a greater purpose in my home Linux system.
It does not even have an error reporting function included and as you can see, I have made it clean for readers. My intention here is to review the code for general Linux. But if you are on a *BSD, I woul... |
The task:
Given a string, determine whether any permutation of it is a
palindrome.
For example, "carrace" should return true, since it can be rearranged to
form "racecar", which is a palindrome. "daily" should return false, since
there's no rearrangement that can form a palindrome.
My solution:
const isPalindro... |
I am using Google Execution API to create an invoice and it's a small part of a bigger system. However, my boss is pretty displeased at the total execution time before an invoice is generated. It takes 16 seconds for an invoice to be generated, and even longer for multiple payments in one invoice. I have been requeste... |
The purpose of this class is to efficiently notify another thread when data is available with minimal blocking to access/pass the data. The data reader/producer thread processes data in bulk which contains many objects. Instead of dispatching each object individually the objects are immediately or periodically pushed i... |
The task:
Given a string, return the first recurring character in it, or null if
there is no recurring character.
For example, given the string "acbbac", return "b". Given the string
"abcdef", return null.
My imperative solution:
function getFirstRecurringChar(str) {
let i = 0;
const len = str.length;
const... |
Bit of a complicated one for me.
I have a database full of hundreds of thousands of records, many of which are duplicated.
I need to get all records within the last year but making sure every instance of that record is within the last year, e.g. if a record is duplicated and one is older than a year this shouldn't be i... |
I know that this question has been asked many times over many years and I have read every one of them but I wanted to get a modern solution since software has changed and String_Split has been introduced in SQL Server 2016.
I have a stored procedure that splits a comma-separated string and inserts the values into a tab... |
I have written an algorithm to do consecutive word match in a dataset
The input is a dataset (list of textlines) and I want to scan that and return repeated word(s) in the dataset along with some metadata like the strings (lines) they matched at.
I am having hard time to wrap my mind around a better approach to hand t... |
I initially posted a question on SO. I have come up with an answer for the same. Basically, given two dicts of models and parameters, user can create an object, and get the report in 5 steps.
Following is the code.
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split, GridSearchCV... |
I'm working on the following problem: I've got a dictionary like this one:
dic={0:[0,1,2],1:[3,4,5]}
And I want to reverse it so it looks like this:
dic2={0:0,1:0,2:0,3:1,4:1,5:1}
I managed to make it, but doing this:
dic2={}
for i in dic:
for j in dic[i]:
dic2[j]=i
I know about list and dict comprehensi... |
I'm writing a Diffusion-limited aggregation simulation, and need to pick a random point along the edge of an area defined by a dimension pair of [width, height]. The point shouldn't be deep within the area; it should always be on the border of one of the sides. This is the intended behavior:
(let [rand-gen (Random.)
... |
The below code works however it takes several minutes to run. Is there a way to optimise performance so that it can be completed in a shorter amount of time?
My code is designed to look at the "Standard Roster" worksheet and use information in that worksheet of start and end times of a 14 day roster and compare that to... |
I have put together a piece of what can be a much larger frontend in Reactjs.
I just put together the component that renders to the user a list of airports and hotels as well as a header component.
I feel confident about the JavaScript implementation, but what I would like some feedback is on my use of SCSS. I installe... |
I am searching for the global minimum of a certain function and trying to use its gradient (here same as Jacobin) to guide the step counter. However, my x is fix and so is my gradient. I am also trying to retrieve the fastest way possible the first x for which f(x)<1, therefore I am using a constraint.
How can I updat... |
I'm currently self-teaching myself C++, using a C++ For Dummies book that I bought a couple months ago. To practice, I've created a Bank class that holds usernames and passwords, and that has a login/logout system. IT also implements a failsafe if there are too many failed login attempts. I'm looking for advice that ca... |
I am working on Word Ladder - LeetCode
Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest transformation sequence from beginWord to endWord, such that:
Only one letter can be changed at a time.
Each transformed word must exist in the word list. Note that beginWord is no... |
I am trying to learn how to correctly structure my projects and write a good, clean code. I would also like to learn how to write good tests. Can you please review it and give me some tips and tricks how to make that better?
The application is calculating the exchange from the bill for lemonade. Lemonade costs 5$ and c... |
I have two tables as below
ACCOUNTS:
+--------------+----------------+----------------------+-----------+
| BANK_ID (PK) | BRANCH_ID (PK) | ACCOUNT_NUM (PK) | CURRENCY |
+--------------+----------------+----------------------+-----------+
| 20 | 621 | 1001 | ILS |
| ... |
I am using an array_count_values function since I have translated the code from php to javascript and javascript does not have this function, but not sure on the performance of it. I'm sure it can be faster. It currently takes 50ms for 32000 iterations each time it is called.
I have one that returns a simple array:
fun... |
I tried to solve the Super Pow - LeetCode
Super Pow
Medium
Your task is to calculate ab mod 1337 where a is a positive integer and b is an extremely large positive integer given in the form of an array.
Example 1:
Input: a = 2, b = [3]
Output: 8
Example 2:
Input: a = 2, b = [1,0]
Output: 1024
My solution
import ... |
I'm learning design patterns and I thought that it would be a good idea to make my examples of each pattern. This is my example of the Strategy Pattern. Can you tell me is it good and what to improve?
This is the Gallery class
public class PhotoGallery
{
private ICollection<string> photosNames;
private ISha... |
I'm a beginner as you can see and I would like to know how I can improve my code. Studying for 6 months now. Thank you.
roman_dict = {1: 'I', 4: 'IV', 5: 'V', 9: 'IX', 10: 'X', 40: 'XL', 50: 'L', 90: 'XC', 100: 'C', 400: 'CD',
500: 'D', 900: 'CM', 1000: 'M'}
divide_list = [1000, 100, 10, 1]
def not_in_... |
I am working on an easy math question Happy number Happy Number - LeetCode
Happy Number
Write an algorithm to determine if a number is "happy".
A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the p... |
Intersection of two sorted vectors in C++ - can this be written any better?
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
vector<int> result;
int l = 0, r = 0;
while(l < nums1.size() && r < nums2.size()){
int left = nums1[l], right = nums2[r];
if(left... |
I could use some help refactoring my component and service. I have a lot of nested logic and wasn't sure what I could do to improve this. I'm new to Angular 7 and their piping syntax. I suspect this is what I could use in this example to improve my code? Also, I have an issue where the drawPoll() function is being call... |
What will be the best practice to create an efficient error handler in object class in VBA? Creating some for Outlook (used later in both, Excel and Access) and trying to get the most efficient and well-built handler.
My concern here is that I have multiple Functions returning an object which makes bubble structure ha... |
The code below does what I need it too but it is ugly and clunky. If I could set the list of cells I want to retreive data from as an array that is declared somewhere, then I could loop through that array rather than declaring each individual cell.
As you can see below, I have had to declare each of the cells I want in... |
This is the code that I'm submitting for the "Good vs Evil" Kata on CodeWars:
https://www.codewars.com/kata/good-vs-evil/train/javascript
function goodVsEvil(good, evil) {
good = good.split(' ');
evil = evil.split(' ');
//hobbits, men, elves, etc
let goodWorth = [1, 2, 3, 3, 4, 10];
//orcs, men, wargs, etc ... |
Here is a simple heap implementation that allows the heap arity to be chosen at compile time, including the degenerate case where n=1 and the heap is effectively a sorted array with a terrible repair strategy.
The heap implementation class, broadly speaking, has two repair strategies: making swaps in the direction of t... |
I've created a Python script that tries to properly indent and dedent ASP code. Similar to http://www.aspindent.com/
Since I've began using it I've noticed some edge cases that I hadn't anticipated. The reason these edge-cases appear is because of the fact that I'm not parsing straight ASP code. There are instances of... |
I've recently picked up a book that gives various "modern" C++ challenges/solutions. One of the first ones I did was on modeling an IPv4 address in C++. Below is the full implementation; it's also on Github. Any suggestions? My goal is to make this as modern as possible and I'm not sure if there are some C++17 features... |
Here is a class that stores a single value into the limited cache. If cache is full, it will remove the oldest element to make a space for a new value.
I'm using 2 structures to accomplish this because I need a fast lookup. I'm not very confident this is the best approach.
Cache will contain a small amount of data (let... |
Im trying to teach myself some computer science (and c++). I am relatively new to this (and to code review).
I have attempted to implement a queue. I have copied the code below for reference.
QUESTIONS:
I have used assertions in many instances: I assert that the size must be non-zero when accessing the front or the b... |
Imagine simple game:
type Combatant = {
hp : int
attack : int
}
type CombatantGroup = Combatant list
type CombatantGroups = CombatantGroup list
type Battle = {
combatantGroups : CombatantGroups
}
there is some battle, in which some amount groups participate. In each group there is several combatants. No... |
I've just written a Producer / Consumer pattern templatized that should work in multi threads environment (IE producer(s) and consumer(s) in separate threads).
The original use case is one producer and one consumer in separate thread with a limit of container size.
It should work for a multi producers / consumers case ... |
I employed the conventional Kadane's algorithms to solve a maximum subarray problem in leetcode Best Time to Buy and Sell Stock - LeetCode
Description
Best Time to Buy and Sell Stock
Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at mos... |
This is a function which aims to convert an amount of milliseconds to a more human-interpretable Day(s) Hour(s) Minute(s) Second(s) format:
function dhms(t) {
d = Math.floor(t / (1000 * 60 * 60 * 24)),
h = Math.floor((t % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)),
m = Math.floor((t % (1000 * 60 * 60)) / (1... |
I am allowing user to upload images & drag uploaded image once user click on mask images, also gave an option to Edit the text....
I am fetching mask images and text from json file....
I am uploading each mask images in single canvas & using absolute positing....
But now its getting very difficult to do any code chang... |
I've been reading about pure methods and immutability in Java. I have a current application and want to convert all the methods to pure methods.
My app takes payment from users. I first create a payment in the DB:
Payment payment = new Payment();
payment = createPayment(orderId, status, address1, address2, country, s... |
I wrote scripts that sums up the students and their grades. It uses four csv files.
students
marks
tests
courses
.
# main
import pandas
from statistics import mean
if __name__ == "__main__":
students_df = pandas.read_csv("students.csv")
marks_df = pandas.read_csv("marks.csv")
tests_df = pandas.read_csv("... |
Here is the problem.
In a town, there are N people labelled from 1 to N. There is a rumor
that one of these people is secretly the town judge.
If the town judge exists, then:
The town judge trusts nobody.
Everybody (except for the town judge) trusts the town judge.
There is exactly one person that satisfies propert... |
I have the following tables in my database:
people: phones:
+----+------+ +-----------+------------+-------------+
| id | name | | person_id | number | description |
+----+------+ +-----------+------------+-------------+
| 1 | Jade | | 1 | 1234567890 | home |
| 2 | Ben | | ... |
This is my first question here and this is my working Body Mass Index Swing Calculator.
Any improvement or recommendation is welcome.
// Metric units
// Weight in kg
// Height in meters
import javax.swing.*;
import java.awt.*;
public class MainProgram {
public static void calculateIMC(DataPanel in){
St... |
This has been my white whale for a while, the idea is convert all the symbols to the goal symbol using all the pieces.
I did an algorithm like 5 years ago (now is lost) and reach lvl 48 but got stuck here and drop. After I watch The Imitation Game and see how Turin solve enigma using a Heil Hitler to reduce the space ... |
I created a morse converter from a .txt file.
I'm learning java and I created a simple morse converter. Convert only A to Z and 0 to 9 chars. Space char remain for split words in morse-code.
At the beginning I used a big switch for any letters or number but it was no good.
public static String toMorse(byte[] bytes) {
... |
The task:
Find an efficient algorithm to find the smallest distance (measured in
number of words) between any two given words in a string.
For example, given words "hello", and "world" and a text content of
"dog cat hello cat dog dog hello cat world", return 1 because there's
only one word "cat" in between the t... |
The first version of my solution was wrong (the usage of compile() function), for details see Stack Overflow.
The solution has been fixed and now it works correctly. Another approach is used: my_add.__code__. The questions stayed the same.
I am reading the book: Obi Ike-Nwosu. Inside The Python Virtual Machine and have... |
My love calculator gives a result from 0 to 100% based on these factors:
If the first letters of the names are the same.
If the number of vowels is the same.
If the length of the name is the same.
If the number of consonants is the same.
Also, there is an extra boost of 10-50%, so the result is also partially as a re... |
I'm new to C language and want to explode a string like we do in PHP explode() function, I searched for a built-in function with the C standard library, and I found strtok , but It doesn't support empty tokens like 1,2,3,,5 . Inspired by the answers I found in this SO question I made this function, it is supposed to be... |
I'm currently working on this problem from Kattis. In short, we're supposed to find the string that has the least similarity to any other string given. Every element of a string is either 0 or 1. Similarity between two strings is measured by increasing the similarity by 1 if both strings have the same character in the ... |
I understand that C++ STL template sort runs faster than qsort in C because qsort needs to call the comparator multiple times and C++ makes the code specific to that type. However, C's pre-processor can hack that, too. So I build a test using qsort.
#include <stdlib.h> /* EXIT */
#include <stdio.h> /* printf fputc std... |
I am writing a Python script that will be used to generate line protocol for inserting metrics into an InfluxDB. I'm parsing the status page of my cable modem. That part works. I receive the data and can extract the table of information I need.
The HTML for the table looks like this (yes, it has the commented out line... |
I have some survey data that represents individual's responses to multiple survey questions. There are about 10,000 people in my actual dataset, and each person answered 35 questions. From these 35 survey questions, I create 1 composite score for each individual by taking the average of the values of all the question... |
I have written a code for a tic-tac-toe game and it works well. But, I don't know whether it is an efficient one. Any help on how to optimize it?
def restart():
num=[0 for i in range(9)]
board=[" " for i in range(9)]
a=2
start(board,a,num)
def wincheck(t):
for i in range(8):
if t[win[i][0... |
I would like to make the timer queue:
1. Each timer has id, time expired and callback to call
2. Queue stores timer and execute the callback of each timer whenever expired.
Here is my code and demo:
#include <iostream>
#include <thread>
#include <chrono>
#include <mutex>
#include <functional>
#... |
The task:
Given a list, sort it using this method: reverse(lst, i, j), which
reverses lst from i to j.
My functional solution:
const reverse = (lst, i, j) => [...lst.slice(0, i), ...lst.slice(i, j + 1).reverse(), ...lst.slice(j + 1)];
console.log(reverse([0,1,2,3,4,5], 2, 4));
My imperative solution:
function rev... |
I am building some classes to serialize (in an async / await way) potentially pretty long IEnumerable<T> over the network via the Stream class, I am wondering whether my code is easily readable et maintainable.
For example one purpose is that the serializer classes can be used in some ASP.NET controllers and write to ... |
I have been doing projects from the book The Elements of Computing Systems. Under the scope of project 10 and project 11, I had to implement a compiler for a (toy) programming language called Jack (its grammar can be found here). The compiler translates Jack code into Virtual Machine instructions (all Virtual Machine c... |
Is doing something like this utilizing currying in a practical sense?
function processOneClickPurchase(item) {
let context = { step: 0 }
let addItemToCart = item => {
let cart = getSession().cart
cart.items.push(item)
log('Cart items', cart.items)
return cart
}
...
... |
Recently, I've been experimenting with an array searching algorithm that I'm not sure I've seen anywhere (minor references here).
I'm still not fully-learned on how to state the efficiency of what I've done (as per writing it's speed in mathematical notation (e.g.: \$O(\log n)\$) either but I'd like to pass on that thi... |
I tried to solve the simple problem of generating all permutations of length n with m distinct elements where repetition is allowed. Doing this recursively took me like 10 minutes:
void genAllPermsRec(vector<int>& perm, vector<vector<int>>& perms, int n, int m) {
if (perm.size() == n) {
perms.push_back(perm... |
The purpose of the pricingTest object is to grab pricing information from the dataLayer on the page and render content blocks accordingly. My goal in posting this is to hopefully receive some feedback in regards to the design pattern used and performance of the code, or anything else you see as worth pointing out. For ... |
I have a list which has 25000 data and I am iterating in all data and in each iteration, I am searching data in another data table. my whole routine is taking a long time to finish.
Loading data from XML file into a dataset.
If the ignoredata field is there in QCCommentstmp dataset table QCCommentstmp.Tables[0].Columns... |
I want to convert strings to their hex representations as strings too (like hex dump programs), for example "abz" to "61627A".
char * strToHex( char * str )
{
int length = strlen ( str );
char * newStr = malloc( length * 2 );
if ( !newStr ) shutDown ( "can't alloc memory" ) ;
for ( int x = 0; x < le... |
Is the following code easy to understand? If not how should it be changed to be more understandable. The purpose of this is reducing similar code in unit tests. This avoids repeating lines for calling getters, setters, and checking for equality.
/**
* Example string for testing.
*/
private static final String STRING_... |
My solution to Leetcode Next Permutation in Python.
Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.
If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).
The replacement must be in-pl... |
The following code is making two asynchronous requests to obtain the desired data. The second request needs to access the data from the first request, hence I need to nest it. I know that it is better to chain promises, but this is a case where nesting seems necessary.
However the lint raises a warning: avoid nesting p... |
I am working on a basic blog application in Codeigniter 3.1.8 and Bootstrap 4.
Several entities are present in all controllers (except Login.php and Register.php): static data, categories and pages.
$data = $this->Static_model->get_static_data();
$data['pages'] = $this->Pages_model->get_pages();
$data['categories'] = $... |
I'm trying to create a node based scripting/computation system.
I've come up with 2 solution that seems to work. One involves template, the other one inheritance. Basically what I want to achieve is: when a node is connected to another node, data computed from the previous node are transferred to the second one. Connec... |
My intention is to POSIX-ly write one generalized function for running various text editors I use for different purposes through sudoedit, i.e. editing files as root safely. Safely = for instance, if a power loss occurs during the file edit; another example could be lost SSH connection, etc.
Originally, I had these Ba... |
The task is to write a JavaScript-function which translates a given blank-separated sentence to title-case.
Means that all words shall start with a capital and then the rest of the word in lower-case. But: A certain, specified set of conjunctions, preposition as well as article shall be all lower-case.
Example: "The se... |
Upon solving the problem 'contain duplicates` in leetcode:
Given an array of integers and an integer k , find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k .
Example 1:
Input: nums = [1,2,3,1] , k = 3
Output: true... |
I am trying to implement AES CTR encryption mode with HMAC authentication for messages.
It's encrypting and decrypting fine as long as the key length is 64 bytes, since AES key and HMAC key are being derived from this key.
Questions
Is it safe to append IV or nonce to the encrypted messages?
Is it safe to append HM... |
I'm trying to figure out what to call this sorting algorithm:
function sort(array) {
array = array.slice();
for (let i = 0; i < array.length; i++) {
for (let j = 0; j < array.length - 1; j++) {
if (array[j] > array[i]) {
//swap
[array[i], array[j]] = [array[j], array[i]]
}
}
... |
device_raw_ptr is a simple fancy pointer. It essentially wrap pointers to GPU memory. It's sole purpose is to separate out host pointers from device pointers, i.e. they should not be inter-convertible and must not be dereferenced. At the same time, they should be zero-cost (with respect to raw host pointers) and be max... |
I have this grouping thing, which is would be a switch case if it weren't for the ranges or a Counter of some sorts, but as there are those ranges I don't know how to implement this any more efficiently.
def getGroups(user_array):
# group1 is group 1-10 x
group1 = 0
# group2 is group 10-50 x
group2 = 0
... |
I've recently started looking into encryption in python and I came across with pycryptodome library. I made this simple program that encrypt/decrypt a file using AES-GCM. Could someone take a look if I implemented the encryption and authentication correctly? For sake of simplicity, I'm posting only the encryption and m... |
What can be done better? My future plans is to implement algorithms such as: DFS, BFS, Prims, Dijkstra, Kruskal, ...
Faults I know of:
Not implementing rule of five
Vertex.h:
#pragma once
#include <iostream>
#include <unordered_map>
template<typename T>
class Vertex
{
public:
Vertex(const T& value);
~Vert... |
I have a list of unsorted numbers. Each time, I need to remove 2 smallest numbers and insert back its sum into the list. Repeatedly do this till the 1 final element is remaining in the list.
Return the total sum of newly inserted elements
My logic was to use heap sort, remove 2 elems, insert elems sum back - repeat.
Th... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.