instruction stringlengths 71 71.9k |
|---|
I came up with a caching decorator for pure functions. Is it ok? Could it be better/simpler/faster?
def cached(f):
def _(*args):
if args in _._cache:
return _._cache[args]
else:
result = f(*args)
_._cache[args] = result
return result
_._ca... |
I'm doing some boring math with lot of sums over lot of variables. So, instead of nesting for loops I have decided to use something like this:
def combo(*limits):
if len(limits) == 1:
for l in range(limits[0]):
yield [l]
else:
for l in range(limits[0]):
for l2 in combo(*l... |
Suppose you have several sequences:
A: 1 2 3 4 5
B: 2 4 5
C: 2 1 3 4 5
D: 3 2
Here, some pairs of list contradicts each other, because they don't expose the same order for their similar elements: (A,C) (A,D) (C, D)
What is an algorithm or a linq statements to find such pairs? Or just to say if my ... |
I'm writing a program to split the words contained in an hashtag.
For example I want to split the hashtags:
#Whatthehello #goback
into:
What the hello go back
import re,pdb
words = []
# corncob_lowercase.txt contains a list of dictionary words
with open('corncob_lowercase.txt', 'rb') as f:
for read_word in f:
... |
I have made a simple gender guesser for an app and thought that this simple bit of code may be useful to other developers. It takes in a string and returns an 'f' for Female and an 'f' Male depending on the name provided. I am not a PHP expert so I was wondering if anyone can give me some feedback on this code.
The ful... |
(function( d, w ){
function showClimb( e ){
var t = e.target;
console.log( t.id );
while( t.id !== 'document-body' ){
t = t.parentNode;
console.log( t.id );
}
}
d.body.addEventListener( 'click', showClimb, false );
}( document, window ))
I just wro... |
I just want your opinions about my code. How could I improve it? Is there a better method to do it?
from sys import exit
from random import randint
print "Welcome to the PIN Game 1!"
print "Tell me your name"
user = raw_input('> ')
#asks the user for an entry and prints what he has chosen
def start():
print "%s... |
I recently came across a email bot that would give you random problems to solve.
Here is the problem.
Please write a function in python which receives a natural decimal N-digit number (1 to 15 digits long) as an input and returns the minimal next N-digit number with the same sum of digits or -1 if there isn't one. Try... |
This class combines multiple instances of Iterable into one and iterates through them in the order they are given to CombinedIterable.
CombinedIterable.java:
package net.coderodde.util;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.uti... |
I've been trying to separate my button functions from my main GUI class
The code works but as an programming beginner i want to hear if i'm doing things the 'proper' way. Point out what am i doing properly and what not. Thanks in advance.
Frame class:
GuiFrame() {
setTitle("Aplikacija (bez imena) v1.0.1");
set... |
Into my workbook I've the db of inventory, in another sheet I've one pvt and in the filter field I put the filed "Card". Now I want create one sheet for each "Card" usually I use this code for this operation:
Sub cmdg2b2(control As IRibbonControl) 'genera una sheets per ogni card
Application.ScreenUpdating = False
App... |
Breadcrumbs should look like this:
Home > Mobiles & Tablets > Mobile Phones > Phone Super Duper
every product belongs only to one category. e.g Phone Super Duper can be found only under Mobile Phones.
This is just a sketch but i want to know your opinion if the direction is ok or i should change the strategy.
ANY crit... |
I want to search some or all public properties of a class and for this requirement I have implemented a Property Searcher.
The Input for a Search is always a string. The Output contains the SearchString, the SearchContent in which the SearchString is contained and the searched Property.The Output is wrapped in a Searc... |
I've got some if and else if statements to show and hide svg elements and it works the way it should but I wonder if I can shorten the code since it looks so repetitive.
I'm not sure if it's possible since I'm not a JS/JQuery expert.
If/else if code
//Door type 1
if( id2 == "#Door1" && id3 == "#Grey")
... |
I have create a functioning automated traffic light sequence using an array and if statements. It all work correctly but I am wondering if there is anything more I can do to improve my code without changing to structure or way it works, so without the use of dictionaries, etc.
<!DOCTYPE html>
<head>
<title> Traffic ... |
The statement of the problem is :
If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.
If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used?
NOTE: Do not count spaces ... |
Visual Studio generated this great route for me, where I can load an entity:
// GET: api/Jobs/5
[ResponseType(typeof(Job))]
public async Task<IHttpActionResult> GetJob(int id)
{
Job job = await db.Jobs.FindAsync(id);
if (job == null)
{
return NotFound();
}
return Ok(job);
}
Here's the Job... |
This is a FizzBuzz program, designed to take parameter inputs for start and ending numbers, as well as a "fizz" number and a "buzz" number. The program then outputs the numbers one per line. If the number is divisible by the "fizz" number (normally 3), "fizz" is printed instead, the same with the "buzz" number. If the ... |
Not confident enough if this would be the correct 'node way' of writing Promises:
Essentially, there are two async database calls, the result from both of these calls has to be collected and used in rendering the view:
Creating ...
exports.getIndustryById = function(industryId) {
return new Promise(function(resolve,... |
I have a rating system where users can vote between 1-6. I'd like to normalize the votes a bit to better accommodate for extreme voting, where individuals tend to vote as high or as low as possible. To do this, I have the following algorithm which seems to work well. However, it's extremely inefficient and not very wel... |
There's a lot going on here, but the background for why this is necessary is that there is a set schema, or 'core' set of tables that are prefixed with 'bu', and any core table can have a custom table of the same base name but prefixed with xb and has the same primary Key. I have no idea if a customer has created an ex... |
I recently discovered the exponential search algorithm which can be used to find whether a value exists in an ordered range. An exponential search checks whether a value is smaller than the \$2^n\$th element of the range, then if the searched value is indeed smaller, it performs a binary search in the range \$[2^n, 2^{... |
While the experience is limited in C#, it is not in OOP generally. While the Beginner-tag is used, relentless, harsh (but constructive) feedback is still wanted. It is more for you to get a grasp of the experience in C# so far.
Would you want this code in your next AAA game title? If not, what are the problem(s)? That ... |
I maintain our organizations intranet page as an additional duty. One thing that every department in the organization likes to use is calendars -- upcoming events, training, etc. At first I was only getting a few a month, and it wasn't difficult to create the calendars using cut-n-paste.
I wrote the following to creat... |
Following-up on my Linq-to-Sage implementation, I ended up implementing all CRUD operations, following the Sage 300 view protocols.
So, the entities derive from classes that look like this:
namespace SageAPI.Views.PurchaseOrders
{
/// <summary>
/// Defines view and key field mappings for 'Purchase Orders' view.... |
For this next assignment, my job was to create a GUI with a button that changes text and color when clicked, and a slider that updates a label (with a TitledBorder) based on its value. Right now it looks like this:
I've made GUI's before, but it's been a few years and I know that the language has updated since then. ... |
Given the following event dispatcher code
public interface IApplicationEvent { }
public delegate void ApplicationEventHandlerDelegate<in TEvent>(TEvent @event) where TEvent : IApplicationEvent;
public class ApplicationEventDispatcher
{
private bool _disposed;
private Dictionary<Type, Delegate> _applicationEve... |
I have the following code that converts a string that looks like:
aaa-bbb|ccc-ddd|eee-fff
to two strings that look like:
aaa|ccc|eeeandbbb|ddd|fff
The code works fine, but I am wondering if I probably missed some string/array functions that can makes the job in fewer operations / or with faster runtime.
var id = "H... |
In my current project I'm writing a C function to write a BMP-File. Internally, the function is split up into three parts: write header, write info header, write data.
In some of these functions I do need to allocate heap space with malloc and actually write to disk with fwrite. These functions are doomed to fail from ... |
I built a simple calculator that supports addition, subtraction, multiplication, and division. It can also chain operations. I'm looking for feedback on my code for places that could be done better in terms of either efficiency or best code practices.
$(function() {
'use strict';
var calculator = (function() {
... |
I've just started using Lazy.js, which is my first exposure to a "functional style" javascript library. I'm still utterly lost as to which of the hundred different functional javascript libraries to use, but so far I like Lazy.js, so I've used it to write a tag harvesting module for a blog engine project I'm working on... |
Code works exactly how I want it to, but any simplification to the code that could be made would be much appreciated (granted this program uses almost everything within the scope of my C++ knowledge).
// sum calculator
#include<iostream>
#include<string>
//integer sum: 0 + 1 + 2 + ... + n
int integer_sum(int a, int b... |
My program does exactly what I want it to do and it works well. However, I feel like it's very clunky.
I'd like my code to be more efficient. By that I mean, I'd like it to accomplish what it already can, but in the best way possible and in the least amount of code. Basically, optimized.
I'd also like it to be easily u... |
I'm using this method and I would likely have a code review. Also, I have one concern and is that source.Count() is executing synchronously and I don't know how to make it async in this context.
public static class IQueryableExtensions
{
public static Task<PaginatedList<T>> ToPaginatedListAsync<T>(this IQue... |
The code below was inspired by this post in Code Review.
Here is how it was first intended by its author:
I have the following code that converts a string that looks like :
aaa-bbb|ccc-ddd|eee-fff
to two strings that look like
aaa|ccc|eeeandbbb|ddd|fff
Somebody already proposed an answer, and I found it could b... |
I have the following first-letter only alphabetical sorting algorithm:
Note: FileManager is just a file I/O class that reads in the unsorted words from a textfile then writes the sorted ones back out).
public class Sorter {
static String list[];
public static void main(String args[]) {
FileManager fm... |
Alright, so my code is 'all over' and missing some fundamentals as regarding to the MVC design pattern.I should separate my concerns and I don't have a model layer and i'm clueless to how to implement it in the current situation.
My two classes are :
public class GuiPanel extends JPanel {
public ImageIcon resource01;... |
I have written this class to check internet connectivity on Android, while there are many instances when WiFi is connected is taken as an implication that internet is connected as well. I wanted to have a method which actually checks if internet is connected. One issue was to run the internet code in a background threa... |
I've written this function for to check if two strings are equal.
Can I improve it?
Is there a better way to accomplish the task?
// Compares two Strings concerning equality.
// -- Parameter --------------------------------
// 1. String - The string to compare against.
// 2. String - The string to compare with.
//... |
This is the perl code which compares the sequence in fasta file & maps the header. Though the code is working well, I still would like to make it more efficient. Since the files I compare has >100000 sequences it is taking huge time despite using hashes. Can you please suggest more efficient way ?
Example:
File1:
>Seq1... |
I have some nokia mobile models with some offers. There are two objects, one for nokia models with price, another one for offers.
For example I have offers for these two models:
"brandname": "Nokia"
"model":"Lumia"
"submodel": "Lumia 735 TS"
"brandname": "Nokia"
"model":"Lumia"
"submodel": "Lumia 830"
My expectation is... |
I wonder if there exists a shorter/more elegant functional programming way than listing all the possible cases. Here, a function that determines positions of beginning/end of subintervals greater than threshold is coded. The idea behind the listed code is to mark and retain the beginning of such an interval, then to pu... |
I got a function that has as input 2 strings, computes the string similarity of all the combinations and give back and output the highest similarity. For example, "you are" and "are you" will have 1 as similarity value.
import itertools
from difflib import SequenceMatcher
import numpy as np
def _compare_names(a, b):
... |
I had done this program that takes an input from STDIN and processes it to check if it is a Latitude/longitude combo or a place's name. Then it uses geocoding and returns an address corresponding to the latitude longitude or returns a latitude and longitude if the input is an address. I am using Nomatim, I would like t... |
In a web application I'm working on I have a class that Map objects to other (different) objects. It is implemented with something like:
public interface IMapper
{
object Map<T>(T item);
}
public class Mapper
{
private static ConcurrentDictionary<Type, Delegate> cache = new ConcurrentDictionary<Type, Delegate>... |
I built my portfolio page using Bootstrap and jQuery, but on lower performance computers the animations seem choppy. I am interested in JavaScript optimization and was hoping you all had some ideas on how to more efficiently execute my code. You can see it live here: bgottschling.github.io.
HTML:
<!DOCTYPE html>
<html ... |
I have just wrote a linked list implementation of disjoint sets in Java for the Rainfall Problem. Can you take a look and tell me if there is something missing and also make a judgement in performance?
public class DisJointSet<E>
{
int rank;
DNode<E> head;
DNode<E> tail;
public DisJointSet(E data)
... |
I use a lot T4 templates and want to avoid extra code writing when it could be generated. Currently I have following class:
class Recursion
{
private readonly string _function;
private readonly Func<int, string> _appFunc;
public Recursion(string function, Func<int, string> appFunc)
{
_function ... |
I have posted a discussion on Math.SE regarding visualizing the complex space and effects of factorization methods on that space. A quick link to the paper is available here. I have 3 routines in that paper, the first is the complex space generator. It works, but it is very slow and would appreciate any suggestions ... |
I'm writing a script that can grep the rows and columns from a text file that match a regex. I have an implementation but I'm looking to make it more elegant.
input.tsv
a b c d
a 2 9 6 1
b 6 4 7 0
c 3 7 2 0
d 5 ... |
I'm learning Clojure and I'm doing a little thing that reads direct messages from Twitter using twitter-api wrapper. The code doing that is below.
(ns twitterbot.my-twitter
(:require [twitter.oauth :refer [make-oauth-creds]]
[twitter.api.restful :refer [direct-messages]]
[clojure.edn :as... |
What would be the most elegant way to refactor the following method?
public void AddOrUpdateDesignCVT(DesignInformation designInformation,
CommonTransformerProperties commonTransformerProperties,
SecondaryWindings secondaryWindings,
Ca... |
This code basically calculates a few metrics based on numerators and denominators and then it bins the data into quintiles. This is a common operation that I perform for various data sets. My issue is that I always have to rename the metrics and columns.
I have a feeling that I could create functions to make this more ... |
I have my class DBFuntcions containing this 2 methods:
The method for the connection to the database:
Connection connection_db(String username, String password, String dbname, Connection c) {
try {
Class.forName("org.postgresql.Driver");
c = DriverManager.getConnection("jdbc:postgresql://localhost:5... |
I'm trying to benchmark two variations of one of my functions. Namely, these functions are for displaying integer values on the command line.
The first of these uses my own implementation and prints from high to low, this is it actually determines the first digit to print and prints it, in contrary to the second method... |
I've figured out a way to switch threads in the middle of a method. The benefit of that seems super obvious to me: that's what everyone wants to do anyway, and splitting up methods, using callbacks, or lambdas, or whatever is just code bureaucracy to make it work.
But if this is so obvious to me, Microsoft guys probabl... |
I wrote this for a problem in one of the online contest at hackerearth. Problem statement is:
Input:
The first line contains the compressed string in form a2b4h5a2
Expanding it means aabbbbhhhhhaa.
You have to sort the expansion in increasing order(a-z). ie. aaaabbbbhhhhh
This is followed by Q that indicates the numb... |
This selects a random student from a class list, stored in a .ss file:
from Tkinter import Tk,Button,StringVar,Entry,Label
import random, tkFileDialog, tkMessageBox
root= Tk()
root.wm_title("Random Student Selector")
current=StringVar()
kids=[]
addKidName=Entry(root)
def addkid():
kids.append(addKidName.get())
addK... |
I got this basic script which I'll be using to check if the answer is right. The only problem is that I'll be using with many forms. That's why I need this code to be more like DRY code.
function checkAnswer()
{
var answer = document.getElementById("answer").value;
if (answer... |
I need a LinkedList but unfortunatelly the one that the .NET provides didn't have the functionality I was looking for (not working with linq and the LinkedListNode is sealed). I created a replacement that works similar but is linq-compatible.
The main class is a LinkedObject<T> that might be used on it's own but is bet... |
Background
For a piece of software that I need to get extensible, I wanted to design a
simple compile-time "plugin" system in C++.
My use case was that the program (actually a library) can accept several input
formats at the same time according to a requested interface version. There is
a factory that selects the right... |
I've solved The trip from Programming Challenges. My solution suffers from lack of floating-point precision, though.
The problem:
Your job is to compute, from a list of expenses, the minimum amount of
money that must change hands in order to equalize (within a cent) all
the students' costs.
Input Standard input... |
I was wondering if there are any significant improvements that could be made in order to make the program more concise or efficient, particularly in the findmatch function. However there is a catch: I cannot use strings or array notation; working only with chars and pointer arithmetic.
In short, the program accepts tw... |
This is my implementation of Conway's Game of Life in Python. Now since I am a novice coder, naturally I have some key doubts:
The usage of idioms and code redundancies - Are there any small fragments of the program which can be better written?
The usage of sys.argv - Is my usage of system arguments acceptable? Eg: $ ... |
So its a class that lets you make a 'Screen' which is a n x n grid of chars. Your able to move a cursor by chosing the row and which column in the row and using that you can insert into into that place and change the char thats there.
#ifndef Screen_h
#define Screen_h
#include <vector>
#include <string>
#include <iost... |
Job -> Many Quotes
Quote -> EmailLogList
EmailLogList -> Many EmailLogs
I want to return a CreatedDate from an EmailLog which has been created most recently - using a Job.Guid.
Is this the best way possible?
public DateTime? GetMostRecentEmailLog(Guid jobGuid)
{
using (DbContext dbContext = new DbContext())
{... |
I have written a module that provides some functions for dealing with Roman numerals. I would like some feedback concerning my style, potential performance or elegance improvements, and any suggestions for additional functions to add.
In particular, I would like to know if there is a clever way to simplify the function... |
I wonder to know if there is any bad smell on my practice for i18n on Angular.
I put the I18n translating function on Angular controller (because I don't know how to put it on HTML template file)
And about the i18n scope, I use this way I18n.t("city." + city_name) to indicate that the city_name is under "city" scope. C... |
This question came from a Java tutorial online:
Write an example that counts the number of times a particular character, such as e, appears in a file.
I was just wondering if there is any way to improve this particular solution.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamRead... |
I have the following code to write:
Modify the Student class so that instead of 3 tests you will now have
an array of 100 tests. However, not all of the scores may be set. You
need to add an additional field to keep track of the number of tests
currently being stored. You will need to modify setTest and getTest ... |
I place various divs on screen by adding random x and y positions successively normalized with this function. My question is, how well is it written? Can I improve it? If so, then how?
I am worried not only about the coding style but also performance since I'm using multiple Math.random()s.
function normalize(n) {
... |
I came to C++ from Java. This is my attempt at making a calculator on about 2 days worth of knowledge. I don't really know what is redundant or unnecessary. Nor do I know of the better ways to achieve this effect.
First class (it does the math):
#pragma once
#include <iostream>
#include <sstream>
#include <string>
usi... |
I am learning C and decided to make an implementation of Base64 encoding according to the info Wikipedia provides about it.
My main question is: should I declare the index_table array inside the get_base64_digit function like static char index_table[] = "blabla"?
A general code review would also be appreciated.
funcs.c... |
I'm writing a struct class in Python and was wondering if this were a good way to write it:
class Struct:
def __init__(self, **kwargs):
for key, value in kwargs.items():
if isinstance(getattr(self, key), str):
setattr(self, key, value)
def create(*args):
newStruct = ... |
I'm updating a website I made awhile ago from a functional design to an OOP design. There are still a lot of functions below this class that I haven't implemented yet but I'm getting to it (such as getUnsentNotifications, fireUnsentNotifications, and other functions such as sendSMS and sendEmail). Please let me know wh... |
I am working on a Laravel 5.1 website where I am counting the average rent of apartments in a specific area. Besides of that I want to get the average rent by amount of rooms in the apartment. The functionality itself isn't anything that hard, but then I want to be able to get the average rent for apartments with e.g. ... |
I am implementing a statistical program and have created a performance bottleneck and was hoping that I could obtain some help from the community to possibly point me in the direction of optimization.
I am creating a set for each row in a file and finding the intersection of that set by comparing the set data of each ... |
I intend to expose a ASP.Net REST API for a project. I would like to use the default ASP.Net Identity system to provide the SQL backend. Users are managed in a different project. For my REST API project I simply point the connectionstring to the same database.
I want to be able to authorize/get the ClaimsIdentity on a ... |
I've picked up the timeout-function below from ActiveState's recipes for Python2 and polished it for python3.4.
Is there any leaner, less clunky way to write it?
import signal, time
class TimedOutExc(Exception):
def __init__(self, value = "Timed Out"):
self.value = value
def __str__(self):
retu... |
I have a dict wherein a value needs to be retrievable by any one of several keys. It seemed that making multiple dictionaries or multiple entries in a single dictionary pointing to the same value object (ref type) was more maintenance than I wanted to commit to.
I decided to use a tuple for the key. I would then use fi... |
I'm currently populating before and after arrays with indexes, based on a number provided. If the input going in is an int, there will be three indexes (left, middle and right). If it is a decimal, there will just be two (left, right). There will me a maximum of three indexes to sort into a maximum of two arrays (befor... |
We are given a map of sides of length n and m (both n and m are less than 1000), divided into n*m fields (squares of side 1). The map looks (for example) like this:
. z x . x
. x x . .
. . x . x
x . . n .
Here n=4 and m=5. We start from the field with "z" and we have to get to the field with "n". Suppose we are at po... |
This is what the code does:
Check if the user's website exists and is active.
After checking the user IP already exists and if the weather 24 hours have passed, if so it deletes the IP database.
Check if there is an ads in the database
Insert a view in the database, insert the ip database
<?php
require_once("../... |
I have refactored the previous combination generator, and now it is an iterator returning combinations as lists. It hides larger constant factors as the previous version, yet it is really easy to use:
for (List<String> combination : new CombinationIterable<>(allStrings)) {
System.out.println(combination);
}
Combin... |
I was given the following instructions
Using the below HTML, using ONLY CSS, JavaScript or jQuery create the following (see attached gif animation):
<div>This is a cube</div>
<div>This is a triangle</div>
<div>This is a big, green circle</div>
Rules:
The HTML cannot be modified in any way
For the animation portion,... |
This is what my viewObject looks like:
{
description: "GOOG AAPL TSLA"
id: 42
ticker_1: "GOOG"
ticker_2: "AAPL"
ticker_3: "TSLA"
timespan: "1mo"
}
Here is the function use to check the object. In a very dirty fashion, it creates a string to be used to replace the URL with:
function createUrl(vi... |
I got the following task to solve:
"PRODUCT_NAME","PRODUCT_CATEGORY","SALES_PRICE"
"Hair Gel","Beauty",6.99
"Scotch tape","Office Supply",2.99
"Office Chair","Office Supply",134.99
"Eraser","Office Supply",0.99
"Lipstick","Beauty",9.99
"Nail Polish","Beauty",8.99
"Note Book","Office Supply",2.99
"Flower Pot","Home & G... |
So I've been looking for examples on the internet for a while now and this seems the most common way everyone is suggesting, but now I ask is there a better way to make a new jframe pop up on click than this.
The code :
JLabel prevention = new JLabel("<html><U><font color='red'>Prevencija</font><U></html>");
preve... |
I am working on an Android unit converter application, but I came to the point where I have to assign the formulas to the calculation method. At the moment I am using a switch-case statement, as it is more neat than an if-else, but still this proves to be very, very lengthy.
The way the application works is the user se... |
Part of my job is to maintain an old application written in Silverlight talking to a WCF service which in turn fetch/persist data into a SQL Server database and in a BI cube.
Most of the security is specified at database level using database roles, users are authenticated using Windows Authentication (integrated secur... |
In preparing a review of this question, I decided to rewrite the code from scratch using a more object oriented approach as I suggested in my review.
To recapitulate the problem statement, we are given an input such as the following:
6 5
. s . . .
. d . . .
. . x . .
. . x . .
. . . . .
. . . . .
The two integers a... |
I know a lot of memory is being used, but how do I make this more efficient in space(and time) .
public class AnagramsTogether {
public static String getAnagramsTogether(String sentence){
if(sentence == null || sentence.trim().equals("")) return null;
String[] words = sentence.split(" ");
... |
This is a simple implementation of a parenthesis-matcher. Given an expression, I want to find out if it is balanced.For example, the expression '{{[[()]]}}' is balanced while '{]{{}}]]' is not. I will output a simple 'NO' is the expression is not balanced and 'YES' if it is.
The algorithm is to push every opening paren... |
I have made a connection pool for SQL Connection objects. The purpose of this object is to provide multi threaded support for the accessing of the underlying database.
The code works by using a reflection proxy for overriding the close() method of the returned connections, so it can detect when the consumer of the API ... |
Task
Write an implementation that determines the count of happy numbers between a given start and end value.
Implementation
public class HappyNumberCounter {
public static int getLastDigit(final long number) {
return Math.toIntExact(number % 10);
}
public static long digitSquareSumCalculator(final long numb... |
I made a simple Blackjack/21 game in C++. It does not use any fancy graphics, just the console output. It is as simple as it can get.
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <algorithm>
void printData(int pTotal, int dCard) {
std::cout << "\nYour total is " << pTotal;
std::cout << "\n... |
Here is the problem statement:
Take a second to imagine that you are in a room with 100 chairs arranged in a circle. These chairs are numbered sequentially from One to One Hundred. At some point in time, the person in chair #1 will be told to leave the room. The person in chair #2 will be skipped, and the person in ch... |
I wrote a function that recursively walks a given directory.
module WalkDir (walkDir) where
import System.Directory (doesDirectoryExist, getDirectoryContents)
import System.FilePath ((</>))
walkDir :: FilePath -> IO [FilePath]
walkDir r = contents >>= fmap concat . traverse helper
where contents = fmap (r </>) . ... |
I'm looking for advice on coding practices in general.
public class Knapsack {
public static int getMaxBenefit(int[] weights, int[] benefits, int capacity) {
int[][] maxbenefit = new int[weights.length + 1][capacity + 1];
for (int i = 0; i <= weights.length; i++)
maxbenefit[i][0]... |
Problem statement of PE18 is :
By starting at the top of the triangle below and moving to adjacent numbers
on the row below, the maximum total from top to bottom is 23.
3
7 4
2 4 6
8 5 9 3
That is, 3 + 7 + 4 + 9 = 23.
Find the maximum total from top to bottom of the triangle below:
75
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.