instruction stringlengths 71 95.1k |
|---|
I am traversing two objects that may share a common ancestor. To make the code small enough to show here, I have changed it into two dictionaries with values. As you can see, a_d and b_d are the inverse of each other. The idea is to step into each dictionary step by step until we find an overlapping value for the two. ... |
I currently have an event listener tied to Laravel's Attempting class. The listener is designed to rehash an old password to something newer. The current DB stores the pass in an old crypt format. I'm just silently converting that old hash to a newer one. This works when going to the site to login. Now I want to be a g... |
I have simple class that I want to ask if is there any possible to improve it? I mean, for me it looks poor. Is there any way to use here try-with-resources, stream or optional?
package bookstore.scraper;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import java.io.IOExcep... |
I made a task scheduler to practice allocators and type erasure. With my project, you can delay execution of any callable (functions (using std::ref), lambdas...) in time by inserting it in a TaskScheduler, and by giving a std::chrono::time_point (you can also make a task be called multiple times by giving a period (st... |
I have a list of 2D matrices. Each matrix is filled using the function “fillMatrices”. This function adds a number of individuals to each day 0 in a matrix and updates the columns “a_M”, “b_M” and “c_M”. The numbers of individuals come from an initial matrix “ind”. The code works but it is slow when the number of matri... |
I’m trying to generate 5 characters from the ranges 0–9 and a–Z. Is my solution optimal or did I overthink it a little? Would hardcoding a character list be more optimal?
const numbers = [
...Math.random()
.toString(36)
.substr(2, 5),
].map(element => (Math.random() > 0.5 ? element : element.toUpper... |
I've developed a small memory game, the game contains a function to flip cards for every turn. I'm looping thru the array containing the images every time to pick one card. I'm sure there's away to optimize this function so I don't have to loop through the array every time in order to just turn one card. But I'm a bit ... |
Work flow is:
Copy Previous Year Reports Folder
Update Following Templates
Save
Close
There are 19 workbooks in the Source Folder and in the NewYear Folder. Each Workbook has to save the final data from the end of the year (the "YTD ACTUAL" pages) along with resetting and prepping the month sheets for the new year.
D... |
The simple program reads in some channel data and parameters from text files and should be able to generically transform the data using natural math syntax.
I am primarily concerned about performance. Any improvements in readability, correctness, and defensive coding style will also be appreciated.
main.cpp:
#include <... |
I have a lot of problems making this code look more elegant or to reduce its size. The algorithm is mostly copied from the pseudocode of wikipedia page. The difference is I prepare my string with the tokenSplit method.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Te... |
I'm looking for improvements of a code that filter the output of git status --ignored and git status --ignored -bs commands. I feel that it could be more readable but I'm not sure how since I'm a beginner. Please, all your critics and advice are welcome.
This is my code:
function filter(str, regExp) {
const reg = n... |
A coding challenge to write a function sortStack that receives a stack of integers into ascending order (with largest integers on top) and returns another stack with sorted integers. At most one additional stack may be used to hold items; no other data structures may be used to copy or hold the elements.
Stack Class:
c... |
I am fairly new to programming. I am writing a script which
gets URLs and parameters through a config and makes http requests to check status, finally push a json string to Open-falcon server.
I am not sure if the logic and writing is reasonable. Could I get some guidance from someone experienced with Go. Really appre... |
In a part of the project, I had to implement a solution for encapsulation of byte arrays. We do use ssh and secure ports for socket connection but I was in need of an extra layer of protection against man-in-the-middle attacks or a mechanism to drop packages rather fast before reading all the package content. (In case ... |
The challenge:
Given a mapping of digits to letters (as in a phone number), and a digit string, return all possible letters the number could represent. You can assume each valid number in the mapping is a single digit.
Example:
If {"2": ["a", "b", "c"], 3: ["d", "e", "f"], …}
then "23" should return ["ad", "ae", "af... |
The input graph to the bfs function is in the form of edge list representation.
from queue import deque
def neighbour(s,visit,que):
for i in l:
if(i[0]==s and i[1] not in visit):
que.append(i[1])
visit.append(i[1])
return que
def bfs(start=0):
que=deque()
visit=[st... |
This is a my first Python program, and whilst I am new to Python I would like to keep in good practice
Below is a short program to work out what type a triangle is and if it makes a valid triangle
I have tried to use as little documention for this as possible to try and get used to how things work in Python so I can o... |
I am working on a asp.net mvc project. And I wonder if the setup of the project is correct. So just some advice
Because I see this:
public IndicatorController(
IndicatorService indicatorService,
PatientLogService patientLogService,
PatientDbContext dbContext,
AppIdentityDbContext identityDbContext,
... |
I have a script that I wrote, and I'm sure that there is a better way to do it, but can't for the life of me figure it out.
Here is the problem statement:
I need to backup data to a remote location, but what actually gets backed up depends on what day of the week it is. I have a program that creates a folder with the d... |
For my first project with Rust, I decided to try and implement a minimal static site generator. I've never had any code review, and I've been looking for some feedback so I can get better!
Brief Context
The directory structure is the following:
./src/main.rs -> the code file
./posts/*.md -> a list of markdown files to ... |
export const updateWatchlist = (coin: IAsset, watchlist: IAsset[]) => {
watchlist.push(coin)
return watchlist.map((c) => c)
}
Is this 1-line-able with a lib like Ramda?
|
I have made a console game using c++ without using OOP.
The code works, but is it good that way or should I have used OOP?
#include <iostream>
#include <utility>
#include <vector>
#include <Windows.h>
#include <ctime>
enum direction {
STOP, UP, DOWN, RIGHT, LEFT
};
const unsigned short width{ 50 }, height{ 20 };
... |
It can be seen that the number, 125874, and its double, 251748, contain exactly the same digits,
but in a different order.
Find the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and 6x, contain the same digits.
from time import time
def is_permutation(n1, n2):
"""returns True if n1 is permutation of n2"... |
A coding challenge to construct a binary tree from an array.
class BinaryTreeNode {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
}
function makeBst(arr){
if(!arr || arr.length <= 1){
return arr;
}
let top = ar... |
I've written a function that returns how many Months and Days are between two dates. I want to respect calendar month boundaries, but I'm ignoring time as it's not relevant for my needs.
I've got the following, but I feel like I'm missing thing I can do to optimize it/refactor it. So I'm looking for additional eyes to ... |
I'm still learning Python, but thought this was kinda a cool project to work on. Feel free to critique and let me know what to work on or change.
main.py
# -------- MODULE IMPORTS --------
import random
# -------- CLASS IMPORTS --------
from phrases import Phrases
# -------- GLOBAL VARIABLES --------
p_p = Phrases.ph... |
with open(filepath) as fp:
#line = fp.readline()
cnt = 1
while line:
line = fp.readline()
print("Line {}%: {}".format(cnt, line.strip()))
line = line.replace('\n', '')
#print('line->',line)
rst = read_ct[read_ct['user_id']==line]
#print(rst)
if rst.shape[0] != ... |
I have 2 data structures with me in JS. One is an array say of length N. Let's consider N = 4.
const arr = ['a', 'b', 'c', 'd'];
The second one is an object:
const obj = {
a: 0,
b: 2,
c: 3,
z: 5
};
I wrote a code in Javascript, to create a new object out of obj which should not contain the keys which are not ... |
There are exactly ten ways of selecting three from five, 12345:
123, 124, 125, 134, 135, 145, 234, 235, 245, and 345
In combinatorics, we use the notation, 5C3=10.
In general, nCr = n! / r! (n−r)!, where r≤n, n! = n × (n−1) × ... × 3 × 2 × 1, and 0! = 1.
It is not until n = 23, that a value exceeds one-million: 23C10 =... |
Here is implementation for singly linkedlist. Any suggestions are most welcome
package linkedlist;
import java.util.Scanner;
public class linkedlist {
private int size=0;
private Node newNode,oldNode,firstNode,displayNode;
public void createNode(String value) {
if(size==0) {
newNode=n... |
May be my question is not up to the standard for Code Review, but of upmost importance for reassessing methods used in my VBA coding . While preparing/testing answer for a SO post (thought to simplest of simplest questions) VBA cell format that contain a specific percentage value, I came to a jolt that shaken whatever ... |
I was wondering what's the fastest method to compare similarity between two lists of strings (e.g. two dataframes, documents etc.) using levenshtein distance or other procedures.
I am currently using:
def wuzzyfuzzy(df1, df2):
myList = []
total = len(df1)
for idx1, df1_str in enumerate(df1.col1):
my... |
I've been fiddling around with some easy code challenges and there's one about determining if a triangle is equilateral, isosceles, or scalene.
I've come up with a working solution, but I feel this could be greatly improved and/or simplified.
The sides of a triangle come in a list e.g. [2, 2, 2] or [0, 0, 0].
Here's w... |
I've got below implementation for my controller and show action which implements MiniMagick gem. I've just wondering is there any better way to write it down? If block in a separate, private method maybe?
def show
identification_document = IdentificationDocument.find(params[:id])
authorize identification_docu... |
I'm using flexbox to create a simple header, hero image with caption and footer.
As you can see from my snippet, the header is fixed and the hero image scrolls underneath.
Is there a way to achieve my layout without fixed or absolute positioning? I'm relatively new to flexbox and and haven't come across a solution.
For... |
I've written this code in Scala that extracts bigram statistics from the Reuters dataset. It puts the statistics in a Map[String, SortedMap[String, Int]]. For example, the bigrams for "hi" could look like this:
Map("hello" -> SortedMap("there" -> 10, "friend" -> 6))
which means that "there" follows "hi" 10 times in th... |
I have a calculator (in React) and I wonder if the way I did is is good or what I could improve. I wanted to do it like the iphone calculator (you dont only see results when you press =) and I feel like my code became a little messy. Any suggestions would be awesome! Ps. I didn't yet add more then +,-,/.*,= operations.... |
Here is a stored procedure which we use to port the data from a remote server to our data warehouse server. The SP uses a generic style where all the tables along with its schema and data will be loaded into the data warehouse.
The script is working fine, but now we have a requirement where few of the tables like custo... |
this is a simple wrapper for sqlite3 to make working with databases easier
it isn't a professional implementation but it is much better than the raw c interface
I saved much time and code using this wrapper instead of the raw interface
any improvements will be appreciated
HandleBase.hpp
#pragma once
#include <type_trai... |
I am using an API to check if customers have social media profiles.
Depending on whether they have phone or email or both there's a different search type.
There's a lot of conditions in this function, and the real dataframe has about 50 columns. So I'm just wondering if this is the most efficient way to go about it.
... |
I have been working on my game for quite a while. one of its key features is cross-platform local multiplayer for example 2 players on 1 keyboard and some people on the controller.
However after finishing my script which took me a whole day to get it running just the way I want it to work. it works but is very ineffici... |
I recently made a logger program implementation in my game engine. Which logs any thing that I send it in either a file or the System.out printstream.
I use it like this:
private static Logger logger = LogManager.getLogger(Shader.class.getName());
And then I can call a log method like this:
logger.info("Info", e); // ... |
There is a follow up question here.
I've undertaken the project of creating my own programming language, Linny. It's a very, very simple language, with only variable creation, variable changing, and outputting to the console, but I've very proud of it. It's an interpreted language, with the interpreter being written in... |
here is a code of a simple contact form that I have created, I believe that the form is server-side protected against empty fields, header injections, CSRF, XSS, bots using 'Google reCAPTCHA v3' and so on..
The call is done through AJAX..
I just wanted to share this code and I am open to any suggestions that can improv... |
What is it?
The google sheet that the macros are on acts as a sort of "back-end" for the records of a behaviour system at a school. I build multiple google sheets that link to this one that pull the data. Each week the behaviour records are put in this main sheet and then formulas total up the rest. The macros are for ... |
I am relatively new to scripting. My programming experience stems from a QBASIC course when I was 11, and teaching myself HTML when I was a teenager (a while ago).
This script resides on what is essentially a log of orders for a company. Occasionally, orders will be "shorted" if all the products are not ready in time f... |
At the moment I have this:
function getValue(str)
{
let result = 0;
var regex = /(\d+[a-z]+)/g;
match = regex.exec(str);
while (match != null)
{
var match_str = match[0];
var last_char = match_str[match_str.length-1];
if ( last_char == 'h' )
result += parseInt(match_str) * 3600;
if ( last_char ... |
"This is {0} cool!", "freaking"
I've always wanted an easy and intuitive way to inject variables into a string. So after about 10 variations, I finally came up with this function.
How it works
The concept is that I can find every pattern such as {key} or {0} or whatever {taco} and get a unique list of these. If there ... |
I have written a bilinear interpolant, which is working moderately well except that is painfuly slow. How can rewrite the code to make it faster? Using opencv directly isn't a valid answer.
import numpy as np
import numpy.linalg as la
import matplotlib
import matplotlib.pyplot as plt
from skimage.draw import line_aa
im... |
I'm learning GLSL shaders on Book of Shaders and I decided to mess around with one of the examples. I wanted to see, whats a more efficient way to calculate to mask out the color?
#ifdef GL_ES
precision mediump float;
#endif
#define TWO_PI 6.28318530718
uniform vec2 u_resolution;
uniform float u_time;
// Function f... |
hi I have made and AI for my enemies which works perfectly but a particular section of code is repetitive and I feel that it can be optimised
void ChangeDirection()
{
if (movement == Vector3.left)
transformModel.rotation = Quaternion.Euler(0, 270, 0);
else if (movement == Vector3.right)
... |
I spent some time today trying to write FizzBuzz in a functional/declarative style. I thought it would be a good chance to get some feedback on it since I've been doing functional programming for about a year now.
(I know there are some similar questions asked here before, but their approach to the code has been differ... |
I have written some code that transforms 2 way matrices into 1 way matrices. Although it's comfortable to use, it's very sluggish and slow in execution. Does anyone have any idea how to improve the performance? I'm aware that the same transformation can be done with standard formulas, but solely for learning reasons I ... |
I would like some suggestions on how to make it better and also if any features that i should add to this Script. I am using beautifulsoup,requests for scraping and networkx for plotting the graph.
https://github.com/HardikM1999/WikiLinkMapper
import requests
from bs4 import BeautifulSoup
import sys
import networkx as ... |
I'm making use of RxJS and observables within my Angular application to process the results of API calls and process data. I've written the component and it works without any issues. However after further research into RxJS and observables I've became aware that the way in which I am using subscriptions is considered b... |
The website I'm developing allows customers to book an appointment. They can also cancel their appointment with the following rules:
if the appointment is cancelled between 48 hours and 1 hour in advance, the customer has to pay 50%.
if the appointment is cancelled below 1 hour in advance, the customer should pay 100 ... |
Print sums of all subsets of a given set
Problem summary : Print all subset sums of a given set of integers
My approach is to store previous results and use them to calculate new (similar idea as DP).
SubsetSum.cpp
#include<iostream>
#include<vector>
//using namespace std;
bool isPowerOf2 (long long x)
{
/* First x ... |
I made a program to explore the symmetries of an equilateral triangle using Python and Turtle Graphics. It's formatted using Black Playground.
As usual, my goal is to be writing "code that doesn't suck." What do I need to to to achieve that goal is this instance please?
I'm guessing some repetition could be avoided, an... |
Recently I am learning to program in Python and in order to practice I tried to program a little game which consists in a board with 9 cells. In this board each player draw an 'X' or 'O' with left or right mouse button. The next code is a simplification with only 3-cell board.
Code 1: View
from tkinter import *
import ... |
To teach myself Rust, I implemented a simple Quadtree over 2D points with insert, delete, contain function.
My code does not seems "idiomatic rust code" to me. Also I think it's not so fast.
I'm added 2 tests:
simple test for check code work
test to add 10_000 points to the quadtree
Code:
use std::ops::DerefMut;
#[... |
I am creating an iOS app and I want to implement Singleton Pattern.
I have created "Singleton" LibraryAPI to act as an entry point UserManager object to get data from web API. after that I used a facade Pattern "method" to call UserManager implementation.
final class LibraryAPI {
static let shared = LibraryAPI()... |
Follow-Up question
.Net provides String.IndexOfAny(string, char[]) but not String.IndexOfAny(string, string[]).
The existing built-in String.IndexOfAny takes an array of char and returns the lowest position of any one char from the array in a passed in string or -1 if none are found. Essentially it is the char equivale... |
As as final project for a MOOC I wanted to write a program that finds the exact cover set/minimum dominating set from the given social network data. So I did end up with writing this. I kinda followed this algorithm.(https://www.geeksforgeeks.org/exact-cover-problem-algorithm-x-set-1/)
I did test with the picture below... |
I have a semi-working project currently and am wondering if I am doing this the wrong way or if there is a more efficient way. I will try to be as general as possible as to keep the point concise.
Any tips, suggestions, articles, ideas, etc. that you have, will help me greatly. I am a one man show essentially when it... |
A function that funnels all filenames into a file and opens that file in vim. The user then changes the names, saves, and quits. Finally the function renames the files in the folder with the new names provided in the file.
bulkrename() {
mkdir -p ~/.temp
ls > ~/.temp/newfilenames && nvim ~/.temp/newfilenames
... |
I am working on an iban api which is about saving the iban of some members after (iban validation) in a database. The code is split between Domain (entities, behaviour for iban validation), Database and its access (new member, retrieval, etc.).
I am looking for feedbacks about the async code and the general coding styl... |
This is an experiment on extending a basic built-in Common Lisp sequence function (namely remove), in order to provide more functionality with little or no impact on performance. The long-term goal might be to provide such extensions for many other CL functions.
The CL sequence functions seem to provide at least 3 diff... |
A googol (\$10^{100}\$) is a massive number: one followed by one-hundred zeros; \$100^{100}\$ is almost unimaginably
large: one followed by two-hundred zeros. Despite their size, the sum of the digits in each number is only 1.
Considering natural numbers of the form, \$a^b\$, where \$a, b < 100\$, what is the maximum d... |
Purpose of the code is to delete all virus affected files from your pc.
private static void SearchAndDeleteFiles(String directoryName, List<File> files) {
File directory = new File(directoryName);
File[] fList = directory.listFiles();
if (fList != null) {
for (File file : fLi... |
Currently learning from "LPTHW - Zed Shaw" and "Automating the boring stuff".
There is a nested dictionary of the type {'string1': {inner dict 1}, 'string2':{inner dict 2},...}.
I want a non nested consolidated dictionary of all the keys and values from all of the {inner dicts}. I have written the code below, but I am ... |
I have re-implemented in C++ an algorithm already in JavaScript available here and there.
C++ code works fine, but I have memory management concerns:
I allocate memory with such statement as m_root = new Block(...) dangerously
When freeing memory with if (m_fit) { delete m_fit; m_fit = nullptr; }, exceptions are thro... |
Background
A recent question Print sums of all subsets made its way to the Hot Network Questions list. The problem is simple:
Print sums of all subsets of a given set
Given an array of integers, print sums of all subsets in it. Output
sums can be printed in any order.
Examples:
Input : arr[] = {2, 3}
Output: 0 2 3 ... |
I am refactoring this piece of code.
The main part I am fixing is:
for (i = j = 0, len = lines.length; j < len; i = ++j) {
line = lines[i];
lines[i] = maybeCode && (match = /^([ ]{4}|[ ]{0,3}\t)/.exec(line)) ? (isText = false, line.slice(match[0].length)) : (maybeCode = /^\s*$/.test(line)) ? isText ? lang.symbol : ... |
I've implemented an updateable priority queue as a part of implementing some single-source-shortest-path algorithms (Dijkstra, BF). I'm relatively new to Python.
class UpdateableQueue:
def __init__(self,iterable=None):
self._heap = []
self._entry_finder = {}
if iterable:
for item... |
Inspired by a recent question to rename files by editing the list of names in an editor, I put together a similar script.
Why: if you need to perform some complex renames that are not easy to formulate with patterns (as with the rename.pl utility), it might be handy to be able to edit the list of names in a text editor... |
Is there a more natural way to do this in rust? I'm having a lot of difficulty trying to make this look clean. Type mismatches and borrowing have me stumped. What are some refactors that I could make?
Input
Take in list of space-separated, command-line arguments
Output
Book (join all arguments except the last)
Ref... |
I created a test-server for RESTful integration-tests that I call TeapotServer because I like the status-code 418 that the server returns when the client makes a mistake and sends it an invalid request.
Example
Its API is similar to JustMock. I first tell it to what API I want to test, how the request should look like,... |
I have coded a rock–paper–scissors game in C++, and it works exactly how I want it to. However, I was wondering if there is a way to simplify the code and clean it up. It is for a school project, so the void function has to be included in the code, but I feel like the while & if functions could somehow be simplified.
#... |
A previous question regarding Linny exists here.
After a wonderful response on my previous question regarding my developing programming language, I worked on it for a couple days, and am returning for more scrutiny. What I added:
If Statements ( no else )
Functions ( with calls )
For Loops
Math operations
User input (... |
I'm playing around with using Dapper with Mediatr in a .NET Core API. It's all working nicely.
Its a learning project for me so I am just putting together a system that will hold user details against some training qualifications/certifications.
I am just building out the api's first and then will have a look at a UI.... |
I wrote an implementation of a hash table in Python.
This implementation uses chaining for handling collisions, based on lists.
I also use an expansion/shrink factor of 2.
The expansion is done when the amount of key entries is bigger than the amount of slots from the hash table. Shrinking is done when the amount fo... |
A function that funnels all filenames into a file and opens that file in vim. The user then changes the names, saves, and quits. Finally the function renames the files in the folder with the new names provided in the file.
This is the update to this previous version. The update makes it impossible to destroy files, an... |
I found a class that i coded for an old project about a year ago and i haven't really touched php in a while. Now i need to use similar functionality again i thought it would be the perfect time to rewrite/improve old class. i would appreciate feedback on any errors you notice or advice on anything i should use such as... |
Disclaimer, I'm new to OOP, but have experience in haskell and javascript.
Essentially, the challenge was to create a program which would shift an array a given amount of times to the left and then print the result.
I've tried to make this more extendable by allowing the option to shift to the right.
My code is
#incl... |
A follow up for this question:
Implementing Linked lists in Python from scratch
Node:
class Node():
def __init__(self, key):
self.key = key
self.next = None
Linked list:
from node import Node
class LinkedList:
link_connection = ' -> '
''' init, getters, setters '''
def __init__(self,... |
I'm a C++ beginner working through Cracking the Coding Interview. This is question 16.8:
Given any integer, print an English phrase that describes the integer (e.g., "One Thousand, Two Hundred Thirty Four").
I have written a simple program, below, that I have confirmed works correctly to answer the question (note th... |
I have completed this E-Commerce Mock App in Console C# which I used object to store the data to apply some C# OOP and LINQ techniques. Since it is just a mock version, features are reduced to the minimum.
Any code review on coding style or code refactoring will be appreciated.
I have created 3 projects in this solutio... |
The task is to enhance the Enumerable module with a method nth().
The method shall create a new list, which contains every nth-element of the object, when it is invoked.
For example: [2, 4, 6, 8, 10, 12].nth(2) shall return [4, 8, 12]
Here's my implementation:
module Enumerable
def nth(n)
i = 0
ordinal = 1
... |
My goal is to write a CPU Scheduling Simulator in C++ using the STL features as far as possible. So far, I have only written the code for FCFS and have not provided any input method.
What sticks out most to me is the definition of the process class. The way I have designed the program, there is very poor encapsulation.... |
This is the second version of my FeatureToggle service (see previous question). It still has the same purpose which is to help control whether a feature is ON or OFF and provide an alternative funtionality.
Changes
What is different in this version?
I created a FeatureIdentifier that replaces the previous string token... |
Inspired by CtCI 16.8: Integer to English phrase in C++, I wrote a program to show the Japanese reading of an integer (positive, negative, or zero). The Japanese is written in Hepburn romanization to avoid encoding problems. Also, traditional Hepburn is used to avoid macrons.
Unlike English, Japanese has sound change... |
Using visual studio I created a snippet which helps me surround my already written or new code into a try-catch-finally block. I use axios for REST so there had to be separate error handling method so that users can cleanly view the error result and report it to the support team.
Code:
try {
//Start the loading ba... |
I had created a service which does the actual play of Rock Paper Scissors.
Below is the service which takes a PlayRequest and updates the State of Player objects given by the PlayerService.
So the consumer of the API knows about winner, loser or tie by doing a GET on a Player.
One of the things I feel wrong NOW is t... |
Student.java
public class Student{
/*
Metrics examples (out of 100):
mathScore:98
scienceScore:99
englishScore:92
*/
private Map<String, Double> metrics = new HashMap<>();
public Double getMetric(final String metricName) {
return metrics.get(metricName);
}
}
Statistics
public ... |
I'm trying to learn streams and hashmaps, in doing so I want to make a very scalable, very clean version of FizzBuzz while adhering to the book Clean Code by Robert Cecil Martin.
public class Main {
public static void fizzBuzzHundredTimes(Map<String, Integer> fizzDivisor) throws ArithmeticException{
String... |
I tried to make a dynamic tree in python. It is simple and i have gotten it to work so far. I created a function in main that generates some example data for the tree and then the main goal was to create a member function that uses recursion to print all the data (display_data()). The only issue with this that i have i... |
Note: This is part of a set of demo applications I'm writing for colleagues to show we're not limited to VBA when dealing with Excel. Considering our IT challenges (no admin on-site & no local-admin privileges), this has to work on Portable Python without external libraries. Specifically, the Python 3.7.2(x64) shell fr... |
In the card game poker, a hand consists of five cards and are ranked, from lowest to highest, in the following way:
High Card: Highest value card.
One Pair: Two cards of the same value.
Two Pairs: Two different pairs.
Three of a Kind: Three cards of the same value.
Straight: All cards are consecutive values.
Flush: All... |
If we take 47, reverse and add, 47 + 74 = 121, which is palindromic.
Not all numbers produce palindromes so quickly. For example,
349 + 943 = 1292,
1292 + 2921 = 4213
4213 + 3124 = 7337
That is, 349 took three iterations to arrive at a palindrome.
Although no one has proved it yet, it is thought that some numbers, like... |
Consider the following function to traverse a BST
(defun bst-traverse (fn bst) ; [1]
(when bst
(bst-traverse fn (node-l bst))
(funcall fn (node-elt bst)) ; [2]
(bst-traverse fn (node-r bst))))
;; [1] This is a higher order function - recieves a function which it calls on each node.
;; [2] ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.