instruction stringlengths 71 71.9k |
|---|
I have the following backbone function to read a JSON schema and draw the tree structure (as in the screenshot below). I want to make sure if checking against the type as object/array is alright or if there is a better way to do it.
traverseJSONSchema: function (root, rootName, level, rank, resultPane) {
var height... |
I've have make this animation on the weekend as a "just for fun" thing. And for to play with various techniques I've seen in others code.
I think it works quite alright.
Nevertheless I would appreciate comments about:
How to structure / shorten the JavaScript- and Sass-code better?
How could the animation be improved?... |
I have written the following code in order to:
Find begin and end of FTP user and password from a given URL (ftp://[user[:password]@]host[:port]/url-path)
Allocate memory to hold this string
Copy the sub-string into the allocated memory
Here is the code for your review:
static char * swd_parseUsrPass(void)
{
char... |
I'm writing a "crypto library" and gradually adding algortihms. Now it's just ancient cryptography, but I'm going to expand the library.
It doesn't depend on any external libraries.
class Crypto():
def __init__(self, rotInt=3, letters=list("abcdefghijklmnopqrstuvwxyz")):
self.letters = letters
self.... |
Recently I came across this problem , here is an excerpt of it,
It is well known that the routing algorithm used on the Internet is
highly non-optimal. A "hop", in Internet jargon, is a pair of nodes
that are directly connected - by a cable or a microwave link or
whatever. The number of hops that a packet may ta... |
I assume there can be space in between and I have ignored that. Also, there will be only lower case characters in the string.
My logic: There can be only one occurrence of odd number of character in palindrome string.
#include <iostream>
#include <algorithm>
#include <unordered_map>
using std::cout;
using std::end... |
I have this small program in PHP implementing merge sort. I used one rather simple run time optimisation via using one additional array which allows faster merge operations:
function merge_impl(&$source,
&$target,
$source_offset,
$target_offset,
... |
Often, I find myself folding over a range object if I need to repeatedly transform something. This, to me though, feels like an abuse of fold since I never even use the numbers that I'm folding with.
Almost perfect example:
(ns shuffle-example
(:import [java.util Collection Collections]))
(defn shuffle [^Collectio... |
I recently came across this problem:
Heroes in Indian movies are capable of superhuman feats. For example,
they can jump between buildings, jump onto and from running trains,
catch bullets with their hands and teeth and so on. A perceptive
follower of such movies would have noticed that there are limits to
wha... |
This is working pretty well right now:
var p='';
if(typeof parameters!=='undefined'){p='&p='+parameters;}
var t='';
var l='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
for(var i=0;i<64;i++){t+=l.charAt(Math.floor(Math.random()*62));}
if(!sessionStorage.t){sessionStorage.t=t;}
if(!localStorage.t){loc... |
The problem is instead of doing what is stated in the if statements, does the else line like the if statement is false. However, when printed the variables i am working with, seems i have managed to get the desired expressions. I can't see a problem with the code either so if you experienced coders can please help me. ... |
I wrote a DSL for defining a finite state machine. My robotics team wants to use a state machine to manage the state of the subsystems on our robot, like the arms, drive train, lifter, etc. Each subsystem is implemented as a FSM and subscribes to events published by buttons and sensors. I'm using an event bus as the mi... |
I was given an assignment to write a mini-shell:
To write your own shell, you will need to start with a C program that
will prompt the user for input and accept in a number of arguments
from a command line. The commands entered will be accepted into your
shell and then processed to understand if it is a built in... |
This code is part of the Construct library. Docstrings explain what the code is supposed to do.
@singleton
class VarInt(Construct):
r"""
Varint encoded integer. Each 7 bits of the number are encoded in one byte in the stream, having leftmost bit not set when byte is terminal.
Scheme defined at Google's sit... |
This code is part of the Construct library. Docstrings explain what the code is supposed to do.
from construct.lib.py3compat import byte2int, int2byte, bytes2str, iteratebytes, iterateints
# Map an integer in the inclusive range 0-255 to its string byte representation
_printable = dict((i, ".") for i in range(256))
_... |
I was tasked with implementing Conway's Game of Life. It seems to work fine but the implementation is lacking as I find that it takes a long time to generate the next generation of the grid. I'm looking for flaws and tips to speed up the process. Currently, I can only refresh the display twice a second.
The grid class ... |
The idea behind this problem is to represent a configuration of 8 queens with a one-dimensional array. So a[0] represents the first row, a[1] the second row etc. and a[row]=column position, where column position represents the "row position" of the queen.
Is there anything I can improve?
#include <iostream>
#include <m... |
This is a program to calculate the largest prime number. Are there any possible improvements in style/speed/accuracy?
public static int? LargestPrime(int max)
{
if (max < 0)
return null;
int largestPrime = 0;
for (int i = 0; i <= max; i++)
{
bool? isPrime = IsPrime(i);
... |
Here is my go at understanding generics, Comparables and Comparators, as well as type bounds. I believe I made it as close to Collections.sort as possible in terms of interface. Please review.
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Random;
public class QuickS... |
I am just into redux. I am developing a dashboard using ReactJS redux and material-ui for components. It's a large app as my dashboard contains various features like add/edit/delete device, add/edit/delete tab, create card etc etc.
It's growing very large and I am just into redux, so I am not sure how I can refactor my... |
Using modern C++ feature template argument deduction for class templates and folding expressions it is possible to implement "multi" scope guard utility, which have right order of functor calls:
#include <utility>
template< std::size_t I, typename F >
struct wrapper { F f; };
template< std::size_t I, typename F >
con... |
I'm relatively new to C++ (learned it years ago, but never used it much until now), and I needed an exercise to get a better handle on the language. I also needed a good way of handling events, and while there are plenty of libraries that have good event systems, I didn't like the client code for any of them. It felt u... |
I have code which works pretty well. I just need some of your opinions on how to write it better with fewer line of code. I want to use a ternary operator but I couldn't make it work so I did an if else instead.
Basically, I want to insert a price on my database. The price column is a nullable decimal. Even in my C# co... |
Can somebody help me with optimizing this code? I'd like to have some control about placement. Masonry doesn't do the job in that way.
What I have done now is to create some sets of columns. For different screen width one of the column sets will be active. Big screens have 3 columns middle screens 2 and small screens o... |
Description:
I am trying to solve algorithmic problems mixing them with Object oriented design as part of my interview preparation. So, the question is given an array of integers find the pair of index which satisfy the given sum hence, given:
arr = [1, 2, 3, 4, 5] , sum = 6, answer = (2, 4) or (1, 5)
Code:
class Sol... |
Here is my class that handle all MarshMallow Permissions I prefer separate it class as I will call its methods in all my apps.
At first I get used to check permission by this way:
private void CheckPermissionGranted() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ActivityCompat.checkSelfPermis... |
I'm working on my own "MVC" framework for learning purposes and for personal use. I use the "MVC" expression as a concept not a concrete design pattern. So I refer to MVC as a "separation concept" not a concrete thing since (mainly in the world of web) the implementation can be different in every framework.
Main
The ht... |
I've a static method which parses a String (from the App.config) to a Int32. I need to have a valid (since the parsing would fail of course^^), positive and not zero integer. I've done it like this:
public static int uiScale ()
{
int retint = 0;
try
{
retint = Int32.Parse... |
This is an iterative review.
Previous Iteration
My snake now moves and grows and successfully kills itself.
Eventually, the game board will handle state and things like the list of fatal coordinates and telling a snake whether it's dead, but for now that's just a function called fatal_board_positions paired with is_fa... |
I m making a script to store date information in the smallest size in bits
(I don't mind of the actually memory use in the program / runtime)
#!/usr/bin/env python
import random
import datetime
MAGIC = "DAT"
def extract(data, size):
return (((data >> size) << size) ^ data)
def compress_date(year, month, day, hou... |
I need to compare 2 xml strings where the formatting may be different. The approach is to use the XmlWriterSettings to format both strings and compare the formatted result:
public static class XmlHelper
{
public static string FormatXml(string xml)
{
try
{
var stringBuilder = new Stri... |
I am taking on this challenge on CodeWars. You have to create a function that takes a positive integer number and returns the next bigger number formed by the same digits:
next_bigger(12)==21
next_bigger(513)==531
next_bigger(2017)==2071
This is my solution:
def next_bigger(s)
s.to_s.split("").permutation.to_a.... |
Following is the piece of code which represents the bottleneck of my application:
#include <iostream>
#include <chrono>
#include <unordered_map>
#include <vector>
#include <memory>
#include <cassert>
#include <thread>
#include <random>
#include <utility>
using namespace std;
using namespace chrono;
static const size_... |
From this question and John Palmers answer about active pattern I discovered a gap in my knowledge about F# and took the challenge to code me into some level of understanding this technique.
The result is as follows:
module PokerCards
open System
type Suites =
| Clubs
| Diamonds
| Hearts
| Spades
type Valeurs = // I... |
A challenge in the beginner book "Automate the boring stuff":
#! Python3
# Table printer
# Takes a list of lists of strings and displays in right-justified table
# assumption is inner lists contain same number items
# each inner list must be printed as a column
the_list = [["a", "bbbbbbbbb", "tttt"],
["d"... |
My react.js Image component will load an image from a URL or base64 string, do some processing on it and put it on a canvas. The "preload" prop is a 10x10 pixel image that is blurred just a little bit to make it look smoother.
The blur algorithm itself is very fast (I also tried removing it, but got the same results i... |
I wanted to implement the Sieve of Erathosthenes up to int.MaxValue in C#. No object is allowed to exceed 2Gb so you can't allocate a bool[int.MaxValue] array. In order to solve the problem, I created a class that packs the bits into an array of bytes instead.
I know that it's possible to use a segmented sieve: this wa... |
I want to calculate the Cartesian product of n copies of a small list, marker=[0,1,2]. I want to use these Cartesian product tuples as keys in a dictionary. The value per each key is to be a numpy array with n random floats between 0 and 1.
The only twist is that for each key:value pair in the dictionary, if the key ha... |
I have managed to write code that does something fairly complex. It's working as I need it to, but it is so slow.
Information about a list of suppliers needs to be consolidated into a word document that maintains the same layout on all pages. To do this, a document in the required layout has been created with bookmarks... |
I am working on Project Euler problem 504, which states:
Let \$ABCD\$ be a quadrilateral whose vertices are lattice points lying on the coordinate axes as follows:
\$A(a, 0), B(0, b), C(−c, 0), D(0, −d)\$ where \$1 ≤ a, b, c, d ≤ m\$ and \$a, b, c, d, m\$ are integers.
It can be shown that for \$m = 4\$ there are exac... |
I am trying to test #initialize of class Author:
# lib/author.rb
class Author
attr_reader :name, :filename, :website
def initialize(name, filename, website)
@name = name
@filename = filename
set_filename_from_name if filename == :auto
@website = website
end
end
In reality there are 8-9 propertie... |
I have an ASP.NET MVC 5 application that needs to log to the database every request for a specific controller action and every link click that happens on the view of that action. Since the user shouldn't be affected of this operation.
I came up with the following pattern:
For the controller:
//get the repository instan... |
I have made a small game just for my own practicing. While making it I wrote an asset loader, which (as the name says) loads assets. But my main knowledge and effort was on the game, so now I am wondering how I could improve the asset loader.
On the bright side: It does the job quite well, no matter what changes I put ... |
I am trying to find a efficient solution for the 3n + 1 problem on uvaonlinejudge. The code I have uses memoization using a dictionary. I am getting a 'Time limit Exceeded' error when I submit the code.
Can anyone suggest an improvement(s) that will help with the execution time of this code.
I have already seen this po... |
I'm originally a Java developer taking a stab at some Scala development. One of the main reasons I'm posting is because I know that in Scala you can write your code in a Java (OOP) way and it will run but that makes it bad Scala code.
I was hoping I could get a review of my code and maybe somebody could point out how I... |
I've made a dice game that rolls three die, calculates the sum of their results, and asks the user whether he/she thinks the next roll's total will be higher, the same, or lower than the current roll. It works but I want to know if there is a better/more efficient way to do this. I just started C programming a couple d... |
This code is part of Construct library that converts between byte and bit representations.
from construct.lib.py3compat import *
def integer2bits(number, width):
r"""
Converts an integer into its binary representation in a b-string. Width is the amount of bits to generate. If width is larger than the actual a... |
This is part of the Construct library. Rebuffered is used to turn a seekless/tellless stream like from a socket or pipe into a seekable/tellable one like a BytesIO or a file.
If tailcutoff is provided, only that amount of bytes is kept counting from the end of last read write operation backwards. Otherwise entire stre... |
The following is part of a personal budgeting program I'm writing.
This code pulls line item information from multiple tables and writes it into an array and then displays the information by transid => family => category => lineItems. Everything works, and I get the results I want out of it. I want to know if there is ... |
I have a function that extracts basic parts-of-speech words (NN,NNP,JJ,VBS etc.) from about 2000 sentences. I want to understand if there is a way to optimize so I can bring down the execution time (from about 12 secs right now to single digits) if possible.
import re, nltk, html
def extract_entities(text_list):
... |
I am interested in learning a more succinct (or better performing) way of writing the following working code. I just figured it out but it is pretty messy. This program takes a file full of daily financial transactions for x number of months (for example), and appends each line to the appropriate month file to create s... |
This class returns a cached contact by ID. The two cached functions here are doing the same thing. The only difference being an early return statement or using else and having only one return statement. CacheHelper class is a static class that is a wrapper around .Net's MemoryCache class. It's a dll reference so I don'... |
This was one of my assignments in which I had to create a backup script that will individually compress all files (of an arbitrary number) of file-types (indicated by their .extension).
Example: backup a b c will take all files ending in .a, .b and .c and compress them using tar, keeping the original file, and naming t... |
Edit: it seems flow based (or reactive) programming approach would help here; there are some libraries in python that try that.
I tried to follow the generator pipeline style (see David Beazley's famous presentation) for finding duplicate files (similar to answers here). It seems pretty straightforward with MapReduce, ... |
This is new code and continue discussion from thread (Social network broadcast message algorithm), and this thread focus on build new graph from strong connected graph part. Let me post the problem again, this time I want to focus more on the 2nd step of the algorithm (i.e. code after replace nodes in a strongly connec... |
I had to create a report for a customer by most sold products in the last month and sorted by parameters they have assigned.
We have three parameters on products: Colour, Type and Collection.
The desired result is to sort products by most sold Collection, then most sold Colour, then most sold Type. The query I have wri... |
I have an app with a bunch of questions defined in a yaml file. For various reasons I would like the data to be divided into sections (section_0, section_1, section_2 etc.). When I load this file into my js app I get an object that looks like this:
const questionData = {
"section_0": {
"items": [
{
... |
I'm working on a problem to clone a linked list (each node has a regular next pointer), and each node also has a random pointer which could point to any node in the linked list. Each linked list node has a unique ID and new cloned linked list node should have the same node ID.
One major concern in my current implementa... |
I recently applied for a job as a node/react developer. I'm attempting to cross over from a research position to web development. I didn't get the job but all the feedback I got was that my code was too academic and that it would take me too long to get up to their requirements. I'm not really sure what this means so a... |
I have a WinForms project in which I am trying to implement the Passive View MVP pattern (meaning no business logic in my Views). Each form is a concrete View with an IView interface to which a Presenter is connected.
I do think i should handle some UI related logic in my View because I am otherwise adding needless co... |
I recently applied for a job as a Node/React developer. I'm attempting to cross over from a research position to web development. I didn't get the job but all the feedback I got was that my code was too academic and that it would take me too long to get up to their requirements. I'm not really sure what this means so a... |
I had a task to create simple audio player. So far I managed to do functionalities and all that is needed. Other part of same task was to make it semantic and modular.
I read some blog posts and articles about semantic but I am not sure how to do it in right way.
player();
function player(){
music = new Audio... |
I am building a Go based image processing worker for my web application. I am trying to be idiomatic, but I am new to Go. Any feedback, is appreciated. This program uses bimg to generate 4 square images based on top, left, width, height, which come from a client side cropping library (croppie.js)
package main
import (... |
This code is supposed to search for a specific key in a object or an array or a mix between both. Is there anything I can improve?
function getAllObjectsIn(key, data, casesensitive){
var returns = [];
var searchForInner = function (key, data, returnParameter, casesensitive){
if(typeof(data) === 'obje... |
I need to run 12 queries on a SQL Server DB. Currently I pass the "SELECT..." string to a function below.
Is it optimal to open and close the connection again and again (as my code is doing), or can I set up an ADODB connection as a global variable and reuse the same connection?
Sub ConnectServer(FileName As String, r... |
I have a view that performs some rolling totals. In this instance, it must be in a view. The issue is that it takes about 10 minutes to run, returning 2700 records. There should be a faster way, but I am not privy at the moment. I asked a question here in order to get this far.
I am running SqlServer 2008 R2, so advanc... |
This method finds an employee from a given mother company which consists of group of companies. An employee can work for many child company.
$scope.getEmployee = function(subsidiary, salaryScale){ //1
var workingDepartments = [];//2
var findInGroupOfCompanies = function(comGroup, salaryScale){//3
... |
I had an assignment, for which I got full marks, but am really upset about the code I have written. I feel it is too manual and repetitive. Please help me make it more optimized.
I am making many objects of StringTokenizer and using many static variables. I wish to reduce that, and instead of using declaring 10 Strings... |
Was looking at this question (which I initially misunderstood completely), to which Peter Taylor posted a good answer outlining a much better algorithm.
For kicks, I implemented it in Ruby, but I feel like it can be done more cleanly:
def next_greater_permutation(integer)
digits = integer.to_s.chars.map(&:to_i) ... |
I've been learning Assembly over the past few days, and I've made a simple RPN calculator.
Here is the main logic of the program, excluding utility functions such as printing:
%include "utilities.s"
SECTION .data
badOpMsg db "Unknown character: ", 0h
badNumMsg db "Error parsing number: ", 0h
badE... |
I have an original method that almost does what I want (a method I did not create), but now I need to find records that were deleted so I added another method GetAllGuideRecords minus the delete condition in the where clause.
But now I kind have repeated code so I decided to pack everything in one method, with an optio... |
I am using the book "Realm of Racket" which was written by the people behind the Racket and Dr. Racket projects. It is a great book based on games, similar to the famous "Land of Lisp".
The first game we are supposed to code is the classic "Guess My Number". Following the instructions on the book you end up with this c... |
I'm pretty new to web development and I don't know if my solution is OK according to the best practices, considering performance and clean code.
I have a Merchant model that belongs to a Price model.
Price table:
create_table "prices", force: :cascade do |t|
t.string "price_range"
t.integer "percentile"
t.date... |
This code prints out a list of all the possible sums that can be made from a set of cash.
For example, say you have 2 fives and 2 tens in your wallet. With these, you can make exact change for $0, $5, $10, $15, $20, $25, and $30.
import itertools
cash = {1: 1, 5: 3, 10: 2} # Keys are denominations (e.g. $1 bill)
... |
The way these 1's and 0's flip are like the Lights Out game, except I only have to worry about a single row.
So, if I have 1001 and I "press" the first bit it will become 0101 Now if I "press" the third bit, it will become 0010 and so on until you get the string to be all zeros.
The way I solved this puzzle was to tes... |
This is my solution to Project Euler Problem 48.
Problem:
The series, \$1^1 + 2^2 + 3^3 + ... + 10^{10} = 10405071317\$ .
Find the last ten digits of the series, \$1^1 + 2^2 + 3^3 + ... + 1000^{1000}\$.
I would like feedback/advice to possibly increase efficiency and/or correct incorrect practices.
public static vo... |
I'm in the middle of a program to simulate gravity between particles for > 50000 particles. It works so far, but the way I calculate gravity seems to be a tad askew. Generally, it works. It fails when particles get too close (distance between them approaching 0, gravitational force approaching infinity). I believe this... |
I'm looking for feedback on my singly linked list implementation in JavaScript. Please let me know if you have any suggestions on coding style, documentation, bug fixes, etc.
UML / code overview
LinkedList
_head - The first element in the list
_size - The number of elements in the list
getSize()
R... |
I am writing a module that will synchronize destination to be the same as source, but will only overwrite files in destination that differ from source as to not cause excessive writes, hopefully prolonging the life of the backup. I will probably add additional functionality on top of this later.
I am primarily looking ... |
I recently created a QuadTree implementation in C++. It varies slightly from most implementations.
Instead of storing elements it only organizes elements. This allows programmers to insert elements into the QuadTree and maintain access of those elements outside the QuadTree.
Nodes will only subdivide if an element is i... |
in my application i have a form 'DetailScreenView' which implements 'IDetailScreenView'. It is connected to 'DetailScreenPresenter' by the Passive View MVP pattern. I also have a 'DetailScreenUserControl' which needs to be put onto the 'DetailScreenView'.
I have looked at how other people have implemented it, such as ... |
I need to create method which handle HttpResposeMessage.
Method should throw an exception if error exist, client will handle rest.
You can see my code bellow. This code is working fine and doing what I want, but still it looks quite ugly to me.
Do you have some ideas for nicer implementation?
[Authorize]
public abs... |
I'm working on a problem to find wholly repeated shortest substring of a given string, and if no match, return length of the string.
My major idea is using a Trie tree to build substrings from length 1 to half length of the whole string, then traverse the Trie tree to find if there is a wholly repetitive match or not (... |
I have page where I am inserting some data into Entry fields. For each Entry I have written in XAML different controls with parameters. One of them is Formated parameter where I am giving a string which I am checking on C# logic code. The problem which I figure out that some one could insert wrong string or string but ... |
Can you help me to optimize my code for the following problem:
An array of hashes named expected_tasks has tasks. Each task has a user that has to execute an action and contains fields.
The expected_tasks are related to the actual_tasks.
We want to execute the expected_task[action] on the actual_task["id]".
Therefo... |
As the title say, I have a huge SQL Query which was built over the time (as new requests came, fast workarounds were demanded).More, there were three DB Admins who contributed to this query, and I'm just a poor programmer who has to deal with it.
This query's purpose is to build a report, using some functions and appa... |
I'm implementing a stack by C++ and here I think it has memory leakage problem: in Stack::peek() and Stack::pop(), where I created heap space and returned pointer to function caller.
Users who call these two functions may perform deletion on returned pointer, which will recycle heap space once done. I am wondering what... |
I created a small logging class library and wanted you guys to check it out, I used to use Log4Net but thought I could create something more user friendly that was more suitable for my project than Log4Net was, don't get me wrong Log4Net is an amazon library but it can just be hard to edit to your personal preference a... |
I would really welcome some advice, and notes about my code. I am a long time Python user, and some days ago i decided i should try C++. So a couple of days passed, and i wrote my first application which has a practical use. I still find C++ very complicated (my current perspective is over complicated) but i can clearl... |
I have written this function for creating complete HTML-elements including arbitrary attributes and inner HTML.
I want to keep and reuse it. Therefore I have tried to document the usage well.
I would be interested in hints concerning:
Could the code be improved? So that it is becomes more succinct and efficient?
Can... |
I make a 2D matrix class (where matrix elements are of type float) which so far can:
Create a matrix of zeros of any size by typing Matrix2D myMatrix(n,m) where n is row size and m is column size (default is 1)
Create a matrix based on an initializer list, for example Matrix2D myMatrix({{1,2},{3,4}}) creates the matri... |
I'm getting the right results for the code for the sample outputs, but the OJ is giving a TLE (3 seconds max).
The questions is here.
int main()
{
double h,u,d,f;
while(scanf("%lf%lf%lf%lf",&h,&u,&d,&f)!=EOF)
{
//cin>>h;
// if(h==0)
// break;
//cin>>u>>d>>f;
double ... |
I was given this task: Calculate amount of elements in collection by property: "name"
let array = [
{name: 'Serhii'},
{name: 'Serhii'},
{name: 'Nile'},
{name: 'Apple'},
{name: 'Serhii'},
{name: 'Serhii'},
{name: 'Apple'},
{name: 'Serhii'},
];
Here is my solution:
function calculate... |
Objective:
Print all combinations with repetition of k elements out of a set of n elements.
using System;
namespace Chapter10Exercise2
{
class KofNCombinationsIterative
{
static int[] combination;
//-------------------------------------------------------------------------
static void Mai... |
I'm looking to identify any weak points and unnecessarily slow/expensive operations to optimize this function:
https://jsfiddle.net/vkoc22kh/24/
Any help is much appreciated!!! Thank you!!!
function cleanTerm(term) {
// Escape any regex syntax inside this.term
var cleanTerm = term.replace(/[-\/\\^$*+?.()|[\]{}]... |
I'm not sure about this code but it feels ugly to me. It is a solution to this.
package main
import ("golang.org/x/tour/tree"; "fmt"; "reflect"; "sort")
// Walk walks the tree t sending all values
// from the tree to the channel ch.
func Walk(t *tree.Tree, ch chan int) {
if t != nil {
ch <- t.Value
... |
The "Images" exercise in A Tour of Go asks for an implementation of image.Image. I wrote two solutions, one easy and one harder (just for practice in dealing with interfaces).
SOLUTION 1: (HARD WAY)
package main
import (
"golang.org/x/tour/pic"
"image"
"image/color"
)
type Image struct{
// one array ... |
I just started to learn C++ and I decided to make a Rock Paper Scissors game. It works fine but I would like to know how can I improve it further.
In particular I couldn't find an efficient way to implement a play again feature. Thanks in advance.
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <strin... |
I have code in the this example:
legacy_id phone_type phone_number
1 f 1234567890
1 b 1233854100
1 f 4110256565
2 f 0707070770
2 b 7895120044
I want the data to end up like the following:
legacy_id f_phone_number_1 b_phone_number_... |
I want to know about smart pointers in C++11, so I started to write my own linked list implementation:
#include <iostream>
#include <memory>
template<typename T>
struct link
{
T data;
std::shared_ptr<link> next;
link(T value) : data(value) {}
void add_to_end(T value)
{
if (next)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.