instruction stringlengths 71 95.1k |
|---|
I wanted to practice my programming skill and I started solving exercises from kata-logs site. The exercise:
The game consists of 10 frames. In each frame the player has two rolls
to knock down 10 pins. The score for the frame is the total number of
pins knocked down, plus bonuses for strikes and spares.
A spare i... |
These two functions act on a stack, an array of integers (whose first element is the top of the stack, LIFO).
The first function retrieves the first element and puts it at the end. The other is the opposite.
I would like to combine these two functions into only one function, if possible. (I have a constraint, 25 lines ... |
I quite often plot graphs looking at how some property or function varies with different parameters. Normally, I find the analysis code can be written fairly succinctly and separated into a suitable number of functions. However, when I come to plot the graphs my code tends to come unmanageably long.
Below is a basic ex... |
The task:
Given a string and a set of characters, return the shortest substring
containing all the characters in the set.
For example, given the string "figehaeci" and the set of characters
{a, e, i}, you should return "aeci".
If there is no substring containing all the characters in the set,
return null.
My so... |
Let \$\mathcal{C} = \{ C_1, \dots, C_n \}\$ bet a set of \$n\$ different countries. We associate with each country \$C_i\$ with its potential \$P_i\$. We choose a specific country \$C_e\$ in \$\mathcal{C}\$. The battle operator \$B\$ is given as
$$
B(C_i, C_j) = \arg\max_{c \in \{ C_i, C_j \}} P_c,
$$
or, informally, i... |
We are writing program which makes XML file which is a calendar with all free days in Poland (Saturdays, Sundays, and all hollidays). We tried to write this code as readable as possible so probably no comments are needed.
What do You think about this code? What do You think is better in multiple files or maybe with Bui... |
Just for fun I did the following exercise from "Cracking the coding interview. 4th edition":
You have two numbers represented by a linked list, where each node
contains a single digit. The digits are stored in reverse order,
such that the 1’s digit is at the head of the list. Write a function
that adds the two n... |
I just came through a GitHub repo, which has an amazing animation for Button in Android.
So, I thought why not make that for web buttons too.
And I started designed that.
Here is my repo for the same.
Here is my code:
let icons = $('.magic')
for (let i = 0; i < icons.length; ++i) {
icons[i].onclick = function (e... |
In this code I find a list all of the running java processes and give the below function a name to look for, it will do its best. But since I find my approach a little too ugly, could some POSIX shell script writer have a look and possibly give me some simplification recommendations?
#!/bin/sh
# here is an ugly const... |
I made a Python 3 class that scrapes data from Pro Football Reference. It uses requests and beautifulsoup4 to gather the data and places it into a pandas data frame. All you need to do is create an object and use the get_data() method to get the data frame. This method needs a start_year, end_year, and table_type as ar... |
I was wondering if anyone had anything to recommend for how to clean up the code I made below. Essentially I am asking if my code is messy or not and if there are any recommendations for my improvement.
# Most basic fantasy combat simulator
import random
p_health = 5
g_health = 5
goblin_alive = True
def status():
... |
This is an extension of the System.ComponentModel.BindingList<T> class that allows for notifications of item changing and deleting. These notifications provided the outgoing item and the incoming item, as well as a Cancel property to cancel the change or deletion.
In additon, it also allows for a bulk addition of items... |
I implemented a simple voting widget like the one used on Stack Exchange sites, to use for other purposes (see live on bashoneliners.com), as a reusable package, dubbed UpvoteJS.
Here's how it works:
Upvote.create('topic-123');
<link rel="stylesheet" href="https://janosgyerik.github.io/upvotejs/dist/upvotejs/upvotejs... |
This is a very simple clone of Flappy Bird using Kivy, to be used for programming class for teens. The game consists of 3 classes: Bird, Game, and ResetBtn.
Q: How to make it more efficient, clean, and clear for the students? (without using kv file)
Code Explanation:
The Bird class inherits from Image class, a Clock... |
I work with an API where I need to write code to generate n appointment dates in the coming m months (from today). For the purpose, I write a Random date generator class provided. One condition is I need to use the java.sql.Date for the class.
import java.sql.Date;
import java.time.LocalDate;
import java.util.Calendar... |
It's an exercise from a Vue.js course I'm enrolled into. The aim is to get comfortable with the Vue.js features Slots and Dynamic components. By clicking on the buttons one shall be able to change the currently selected and rendered component.
With green button clicked:
With the red button clicked:
The four main file... |
I'm playing with a simple (for now) project in PHP with Google Calendar API. I have posted the code here in order to improve my programming style about whatever you think it's worth suggesting. Thank you.
As you can see, at the moment the script listEvents.php retrieves all the events in the last 7 days from primary ca... |
I'm a java programmer by trade and starting to learn C/C++. I'd appreciate any pointers on glaring issues with my code style which is acceptable in java but not in C. I feel like open_files is probably bad in C I'm used to that sort of thing in java to make code easier to scan ( setting *src_file on one line and testin... |
So, i recently wrote code that can count the number of monotonic items (increasing, decreasing and constant). For an input such as x = [1,2,3,3,2,0] The provided example was:
1. Increasing: [1,2], [2,3], [1,2,3]
2. Constant: [3,3]
3. Decreasing: [3,2], [2,0], [3,2,0]
So, i broke the problem into two steps, firstly ju... |
This program prints out a table in the console. Suggestions for improvements are welcome.
Example output
Name Sex Age
Klaus Ulbrecht male 12
Dieter male 14
Ursula female 16
You can test and modify the program here.
import java.util.Arrays;
import java.util.List;
import ... |
The task:
Given a list of integers and a number K, return which contiguous
elements of the list sum to K.
For example, if the list is [1, 2, 3, 4, 5] and K is 9, then it should
return [2, 3, 4].
My solution
// init
const arr = [1, 2, 3, 4, 5];
const K = 9;
// main
const getContiguousElementsSum = (arr, K) => {
... |
My latest school project was to implement malloc(), free(), realloc() and calloc() from the standard C library. I came up with something a bit similar to the glibc malloc(). It supports multi-threading; speed is pretty good according to my tests. Not very portable (meant for Linux 64bits and Darwin 64bits). You will no... |
Coding problem:
Given an array of integers, return a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i.
My solution:
arr = np.array([1, 2, 3, 4, 5])
def coding_solution(_arr):
ind = 0
new_arr = []
for n in range(len(_... |
I've recently migrated away from floats and have started using flexbox to build my grids.
My navigation has 4 menu items. I'd like my logo to sit in the middle of these. To maintain a good page structure for SEO, I don't like the idea of putting my logo within a list item inside the nav.
Instead, I've built a solution ... |
I have a class with a property of grid[][] and each value is either true or false. I need to convert this to a string with letters o and b in place of the boolean.
First way, simple for loops over the array and return the string:
get rle() {
let result = "";
for(let y = 0; y < this.grid.length; y++) {
... |
I wrote this small jQuery plugin to set some fields so that they allow only 0-9 digits to be entered.
I intended to do that by preventing user from typing, pasting or dropping non-digit content.
It seems to work (on Firefox), but I'd like to know if this code has some issue or unpredicted effect I'm not seeing now.
$.f... |
This script is running indefinitely as the Linux background process.
I have put an enormous effort to make this POSIX shell script containing an infinite loop shut down tidily along with the operating system (TERM signal) and by me sending it a HUP signal.
Ok, we don't call it exception-handling, but I didn't find any ... |
I'm a newbie to Selenium and I'm trying to get better at it by taking up interview assignments. This YouTube link describes the workflow that needs to be automated.
The following points are worth taking into account.
For your purpose, use your own gmail id/password but make it readable from a file in your project.
Us... |
I have taken your inputs on my original question and formed a new implementation of the Monty Hall Simulation:
Again keep an eye on CleanCode and OOP
The Price to be won:
enum Price {
GOAT, CAR
}
The Door keeping that price in secret
class Door {
private final Price price;
Door(Price price){
thi... |
(The next iteration: A simple Java class for implementing code stop watches - follow-up)
Here is my attempt at more convenient benchmarking (yes, this time I am aware of JVM warmup, etc.), and it looks like this:
package net.coderodde.stopwatch;
public final class StopWatch {
private long earliestMillis = Long.MA... |
Preface
I'm using WireGuard as a VPN solution to connect a remote client permanently to my home server.
Unfortunately due to Consumer DSL-related IP address changes, the client loses the connection to the server.
Because of its philosophy of simplicity, re-resolution of the server's (DynDNS) hostname is out of scope f... |
I'm fairly new to coding and I wrote this script in Python for a house with a roof in Minecraft Pi. I've found different ways to write the coordinates to make the code base shorter, but I'm wondering if it is possible for me to refactor it any further so I don't have to list each coordinate line by line.
import mcpi.m... |
For a personal project that I've recently started I have to analyze the rotation of two shapes with sets of spokes, where the spokes are evenly-spaced, and split into a given number.
That is, if I have a shape with x evenly-spaced spokes, and a shape with y evenly-spaced spokes, I need to analyze two major properties:
... |
After reading this article on writing a Brainfuck interpreter in Haskell and achieving awful performance with it (for example, mandelbrot generating 37.5 minutes on an old Intel Atom powered laptop) I've decided to write a compiler for it.
I picked NASM for my output language, because that is the only assembly language... |
I have a sorted array. It can be empty. I have to find its closest greater and smaller number. If the given number is present in the array, it will be considered as greater number. I implemented it like the below style. But I am not satisfied with my approach. Can anyone suggest better ways?
findPreviousNext(array:numb... |
Inspired by the various quiz programs on this site, as well as Simon Tatham's puzzle collection, I thought I'd write a quiz that constructs its questions automatically and randomly. A typical session looks like this:
What is (true and false)? false
What is (true and true)? true
What is (true implies false)? false
What ... |
I am learning MPI (via boost::mpi) and wrote this program that takes the euclidean norm of a 1-D vector (represented as an array here.) I want to make sure that I am using boost::mpi properly, in terms of both functions used and the way the code is parallelized.
The sample below is the program with just the norm functi... |
My Base64 encoder class converts a string with ascii characters to a base64 encoded string with padding if required. Note that I'm not using istream as the input because my goal was only to convert a std::string with ascii characters to another std::string with base64 encoded characters.
Only resource I used was this w... |
I've been working with binary files with this last assignment and part of it was to determine the maximum and minimum byte. Initially this was 2 functions but a bonus portion was to make them into 1 function through usage of an enum, I imagine to reinforce their utility. I would like to know if there are better ways of... |
Here is a program I wrote to reproduce the known win proportions for random Tic Tac Toe games (X always moving first). It takes about a minute to play the one million random games that will be played if you run main.py after putting all the below .py files in the same directory. (The program does reproduce the correct ... |
The task:
Given an integer list where each number represents the number of hops
you can make, determine whether you can reach to the last index
starting at index 0.
For example, [2, 0, 1, 0] returns true while [1, 1, 0, 1] returns
false.
My solutions:
// functional:
const reachLastIndexOf = (arr, start) => {
... |
This is code I wrote to check a product structure from 1 table in a database. It's based on a type which can have area(s) and area(s) can have group(s).
I have:
type and code area: blank group: blank
type and area and code group:blank
type and area and group and code
As you can see, it is stacked and the lookup i... |
I'm supposed to create a website that adds multiple forms to the page, is responsive and checks if the inputs are valid (validation is not important, just needs to show some attempt at regex). Below is what I've written so far. What I'm looking for is any advice on making it more efficient and compact. Any and all help... |
I've written a binary-tree using .NET Core 3.0. What can I do to improve my coding style?
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
namespace BinaryTree
{
/// <summary>
/// Represents a binary tree <seealso href="https://en.wikiped... |
At the moment I try to get used to SQLite and Python. I started with insert, select and so on. But now i want to get a bit further.
Now I have a DB with 200 rows for testing and in want to update two values of each row in this case called "Test2" and "Test3". My problem is that those two values should be the value tha... |
I'm making note where you can add items that you buy or sell, any suggestions?
public class Main {
private static Scanner in = new Scanner(System.in);
private static String commands = "[-1]Quit, [0]Commands, [1]Available items, [2] Sold items, [3]Add, [4]Delete,"
+ " [5]Edit, [6]Sell. [7]Bilans ... |
I have received a nice answer for this post. Now, it is my attempt for some improvement:
package net.coderodde.time;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
/**
* This class provides easy-to-use means for measuring elapsed time.
*
* @author Rodion "rod... |
So I've run into a few occasions where I'd want to sort a list according to a criteria, then for all loosely sorted sublists (a sequence of equal elements), I'd want to sort those sublists according to another criteria. I previously did something like this (assuming there are m criteria.
sorted(sorted(sorted...(sorted(... |
The idea originaes from the CodeKata19, find a word chain for two words of a wordlist
example 1 turning lead into gold:
lead
load
goad
gold
example 2 turning code into ruby:
code
rode
robe
rube
ruby
Note
it would be also valid if you had found this chain even though it is not an optimal solution (because it's depth 6... |
The task:
Given two strings A and B, return whether or not A can be shifted some
number of times to get B.
For example, if A is abcde and B is cdeab, return true. If A is abc
and B is acb, return false.
Solution 1:
const haveSameLength = (a, b) => a.length === b.length;
const isSame = (a, b) => a === b;
const isF... |
I'm new to C, just started reading K&R C book, and am working through exercises. This is my solution to 1-21, and as far as I tested it works.
Anything that I'm doing wrong, or that it's not idiomatic C? What can be improved ?
Exercise 1-21. Write a program entab that replaces strings of blanks
by the minimum number... |
Suppose You have two kind of response like one for success and one for failure
Success response model will looks like
struct UserLogin: Codable {
let status: Bool?
let accessToken: String?
let data: [UserLoginData]?
....
}
Failure Model will looks like
struct FailedResponse: Codable {
let status:... |
Round 1: Analyzing spoke overlaps during rotation
I previously posted this question, but I've changed a lot of the code since then.
There was a mention of the previous being a bit mixed up, and things being too integrated, so I've abstracted away a lot of that functionality.
The purpose of this program is to draw two s... |
I made a brute force password cracker with Python, but it's extremely slow. How can I make it faster?
import itertools
import string
import time
def guess_password(real):
chars = string.ascii_uppercase + string.digits
password_length = 23
start = time.perf_counter()
for guess in itertools.product(chars... |
I'm calling an API to request token, and making sure i'm not leaving any corners for errors and handle the result appropriately.
It's a web service POST call in general, The code gets credentials, formats them in the URL and parses the result.
The objective here is I'm looking if code overall is good when it comes to ... |
I recently started learning C++ and have made a very simple Console-based Snake Game, I would like to have some feedback on improvements.
You might notice the obvious delay in clearing and printing of the screen, as I did not use system("cls") since it was stated as 'evil' and 'bad'. I printed a bunch of newlines inste... |
I am trying to teach myself C++ and using Problem Solving in C++ by Walter Savitch.
This is a program project from the book that I used to practice using classes/ structs and would like some feedback, please. I included in the notes the question as well as tried to specify my functions for others to try to see my train... |
For practice, I solved Leetcode 15. 3Sum question:
Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
My code pass all testcases from my location but get Time Limit Exceeded from leetcode. Can anyone suggest... |
I just wrote an echo server that responds to curl requests with the method used and the data sent. Sticking to GET and POST for now, but I would like to know if there's something I can do to improve my RESTful API.
I'm supposed to:
Only be able to call the /data endpoint
Only allow JSON parameters
Use best practices ... |
I've got a class with few fields:
public class Helper {
String first;
String second;
String third;
String fourth;
String fifth;
String sixth;
}
And helper service with method which I try to refactor.
public class HelperService {
public Helper toRefactor(String[] attributes) {
Helpe... |
i created this console application ( it's actually a Mastermind) and i would like to know what can i improve as a beginner. Thanks !
#include <iostream>
#include <cstdlib>
#include <time.h>
std::string colorsRandomizer();
int verif(char couleur);
std::string transform(char couleur);
int main()
{
std::srand(time(0... |
This is my database connection class in order to handle multiple connections with the use of context managers. Brief explanation:
The __init__ method reads database configurations from an INI file in order to call the connection and set two dictionaries, one for connections and one for cursors.
The __enter__ method ta... |
The task:
We're given a hashmap associating each courseId key with a list of
courseIds values, which represents that the prerequisites of courseId
are courseIds. Return a sorted ordering of courses such that we can
finish all courses.
Return null if there is no such ordering.
For example, given {'CSC300': ['CSC1... |
This is a python game that I am working on. It is a grid based treasure hunt game in which you collect coins from specific tiles (some tiles ask you questions in which you need to answer correctly in order to get coins), and after a number of moves the coins that you end up with are recorded and put in a file. At the m... |
I'm looking to parse a reduced subset of the Valve Data Format (VDF). It is similar to JSON, allowing representation of key-value collections (maps) with arbitrary recursion. As a small example:
"root"
{
"key1" "value1"
"key2" "value2"
"key3"
{
...
}
}
I'm taking on only a subset ... |
Mostly as a learning exercise, and partly as I thought it might be useful, I have written an implementation of AVL trees ( https://en.wikipedia.org/wiki/AVL_tree ).
An AVL tree is a height-balanced binary search tree, where if the
height difference of the left and right sub-trees becomes more than
one a "rotate" ... |
My goal is to create a class that I can call from my webpages like this. Similar to a data access layer?
string sql = "SELECT EMPLOYEE_ID, FIRST, LAST, HIRE_DATE " +
"FROM EMPLOYEES ";
DataTable dtEmployees = SqlConnectionHelpers.TimeManagementDataTable(sql);
The class itself looks like this and is worki... |
This is a select-all checkbox (and checkboxes that it controls), that's usually found in tables/lists.
Two things I'm concerned about:
I'm returning elements from a React Hook - is that OK to do? As opposed to create a Component (probably a render prop)
I'm calculating master.indeterminate in a useEffect, as opposed t... |
I want to have a function that checks to see if a certain resource (deployment, job, cronjob etc) exist in a namespace. Using the Kubernetes Python client, I can create a boolean function (using deployments as a concrete example).
from kubernetes import client, config
def deployment_exists(name, namespace="default"):
... |
I did a Goldbach's Conjecture exercise and got it to work. It's pretty slow though and I was wondering how I could optimize it.
number = int(input("Enter your number >> "))
print("\nCalculating...")
if number % 2 == 0: #Only even numbers
primes = primenums(number) #returns all prime numbers <= input number
adde... |
So this question might be a bit opinion based but I am a bit confused, say i have these two code snippets -
if (eventArgs != null && eventArgs is OnZoomEventArgs)
{
var zoomEventArgs = eventArgs as OnZoomEventArgs;
if (zoomEventArgs.focus != null)
{
var line =... |
it's hard for me to implement all those features that were suggested, i did so many thing wrong.
can you please review this update on my code, concerning OOP, clean code, and maybe an eye on the algorithm used
What's note-worthy:
the code looks very more clear now, single responsibility seems to be corrected, no more b... |
I'm writing a system that's responsible for changing Status of Order. There's a specific set of rules that define route of changing Statuses. But, Order and its Products have to satisfy some requirements associated to given Status.
For example, Let's say we have this route of status:
NEW -> ACCEPTED -> CLOSED
Status NE... |
I made a GLFW window abstraction, as I find it very useful for me to make such abstractions while learning an API, and It actually pretty much eases my work while coding.
Anyways, share your thoughts. Is the code practice good? Is it bad If I am very explicit in my naming conventions? For example, every method is Wind... |
The task:
Given an unsigned 8-bit integer, swap its even and odd bits. The 1st
and 2nd bit should be swapped, the 3rd and 4th bit should be swapped,
and so on.
For example, 10101010 should be 01010101. 11100010 should be 11010001.
Bonus: Can you do this in one line?
My solutions:
// imperative:
function swap8BitI... |
I want to understand how resnet works also called us residual networks and I understand it better when I code one myself. I tried to find a simple implementation of resnet in the web but most I found were complicated and all of it used convolutional neural networks especially in python with keras. Because of this I hav... |
I have written simple input manager which is used for me to detect key press, and fire assigned function. For example I can do something like that:
auto own_pointer = std::make_shared<Player>(*this);
inputControl.addKeyToCheck( sf::Keyboard::H, std::function<void( Player& )>( &Player::sayHello ),own_pointer );
and in ... |
This is a class that holds mutex and associated object. On checkout/access the mutex is locked while the stack object lives and a reference to object is obtained. Any suggestions or improvements is welcomed.
#include <mutex>
template<class T>
class MutexProtectedObject {
//this relies on benign use and it is just a ... |
I have written a script that retrieves specific fields of Exif data from thousands of images in a directory (including subdirectories) and saves the info to a csv file:
import os
from PIL import Image
from PIL.ExifTags import TAGS
import csv
from os.path import join
####SET THESE!###
imgpath = 'C:/x/y' #Path to folder... |
Since my last question (BinaryTree<T> written in C#), I have rewritten my code based on the responses. My project can be found on my GitHub repo here;
using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
namespace BinaryTree
... |
I'm currently trying to teach myself Vue.js and I've just created my first small project: a simple todo list. While writing the component I discovered that you can't access methods from the parent component directly, but I didn't want to put one half of the code in the child component (the deleteToDo method), so I've p... |
Context
I have blocks of if statements that check if a certain cell contains a particular string and to add to the counter of the respective custom property. Originally I was using global variables, but those are zeroed out when excel crashes. I learned of custom document properties and their non-volatility and made th... |
I have a DataFrame that has a text column. I am splitting the DataFrame into two parts based on the value in another column. One of those parts is indexed into a gensim similarity model. The other part is then fed into the model to find the indexed text that is most similar. This involves a search function to enumerate... |
The following program displays a menu, and prompts the user to choose an option. Options include to add a book, delete a book, view all books, and to exit the program. (Note that the actual code to implement the database functions will be added later.)
The program files were compiled with no error messages or warnings... |
While implementing socket.io on my server, I ran into some problems and eventually fixed them. The code below is fired on the connection event of socket.io:
var newarray = []; //a new array
data.map(function(inde) { //data is an array which contains the data of the user's acc_id and some more information,
newarray... |
The task:
Given an integer n and a list of integers l, write a function that
randomly generates a number from 0 to n-1 that isn't in l (uniform).
Solution 1:
const getRandNotInList = (n , list) => {
const rand = Math.floor(Math.random() * n);
return list.includes(rand) ? getRandNotInList(n, list) : rand;
};
co... |
Never had any programming course. Am not programmer. Does not plan to be.
If anyone has a lot a time to lose, I feel like I have no clue what I'm doing / that a lot of my code is very badly organized.
It's meant to be a "game". Actualy the game is me coding that.
I'm just looking for a review. Yes it's a lot. I know t... |
The task:
A number is considered perfect if its digits sum up to exactly 10.
Given a positive integer n, return the n-th perfect number.
For example, given 1, you should return 19. Given 2, you should return
28.
My solution:
const sum = (acc, m) => acc + Number(m);
const getNthPerfectNumber = n => {
let i = 0, x ... |
I have started practicing problems in leetcode and I solved the following problem on LeetCode.
The challenge is :
Given a non-empty array of digits representing a non-negative integer, plus one to the integer.
The digits are stored such that the most significant digit is at the head of the list, and each element in th... |
In a recent project my backend architecture consists of
Repositories (talking to database)
Services (handling business logic)
Controllers (handling incoming REST calls and providing according responses to the client)
I introduced DTO classes for representing the data that is returned by the controllers when a client ... |
I'm looking for feedback on some code I've written to work as a transparent proxy. I'm developing a web app that needs information from another web site's API, but that web site has disabled CORS and I cannot get it directly. This was an intentional decision by the web site to encourage development of services that w... |
I have a Jupyter notebook that allows a user to type in a phrase and the program will 'guess' which Office character it resembles.
Here is a link to the github repo
I have the following littered throughout my code:
the_office_raw_script['polarity'] = the_office_raw_script['line_text'].apply(lambda x: TextBlob(x).sentim... |
A modified version of the prime sieve. I actually doubt it could be implemented any faster, but I might be wrong:
from math import sqrt
def sieve(n):
"""
* A fast implementation of the prime sieve algorithm. Finds all prime numbers up to a given upper bound.
* Params:
* n: The up... |
An algorithm for finding prime factors of a number given a list of all primes up to the square root of the number. It's worst case time complexity is \$O(n^{1/2})\$, the best case would be \$O(\log(n))\$, and I don't know how to calculate average case or amortised worst case. I am aware that this is not strictly optima... |
102. Binary Tree Level Order Traversal
Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
For example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its level order traversal as:
[
[3],
[9,20],
[15,7]
... |
I'm relatively new to .Net/UWP networking and have been trying to make sense of the APIs. I'd like to implement a TCP client that is capable of reading and sending messages independently (there is no protocol and all messages are independent).
Typically (e.g. in a POSIX C++ server), this would be done by spinning up a ... |
I am learning tree on Leetcode. Need to prepare the testing data.
It is easy to convert the array to an organized node, where its elements are integers.
such as [3, 9, 20, 15, 7]
Here is my code:
extension Array where Element == Int{
func arrayToTree() -> TreeNode{
var nodes = [TreeNode]()
for num in 0..<self.... |
For a homework assignment, I have to create a "TO-DO" list, which will add a list item to the unordered list dynamically using JavaScript. The input element is also added using JavaScript, having to generate a unique id that changes with each site visit. I'm looking for any suggestions that will improve the efficiency ... |
A recent post on StackOverflow about a recursive directory listing which produced an unsorted mixed file/directory list, sparked the stray thought of "What would it take to write a wrapper for the recursive call to produce a sorted listing with directories sorted first?" (this rabbit trail followed...)
In addition to t... |
I am trying to optimize my navigation drawer code. I have tried and followed the BEM naming convention for my CSS although I would like it reviewed with respect to the best practices being followed.
Also, I have used javascript arrow functions for my list in order to avoid repetition of the list item which also needs t... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.