instruction stringlengths 71 95.1k |
|---|
I have a large file that I want to search for text as fast as possible. There is not a memory contraint, so I am loading the entire file into memory so that I can use the rayon parallelism crate in order to improve performance (so I don't get blocked by an IO thread). I have the following code (I've indented the benchm... |
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
longest = ''
max_len = 0
for key,value in enumerate(s):
if value in longest:
longest = longest[longest.index(value)+1:] + value
... |
LINQ Extension
I present a LINQ method ArgBy that returns the item of a sequence that corresponds to the predicate specified. Two additional methods MinBy, MaxBy are provided as specific cases. Its specification how to handle null is the same as the existing LINQ methods (see link).
The purpose is to replace a two-pass... |
I have some functions and structs for loading and drawing an image with OpenGL. The two main places I would like feedback are:
I've tried to separate the OpenGL-specific code into the implementation so the caller doesn't have to know what rendering API I'm using. Can I do a better job of separating the OpenGL-specific... |
The task of the code that is presented for review is to prepare all the data for the export of the selected contract and create a file on this basis.
This is one of the first experiences with a large (for me) program. So I put the tag begginer. In this regard, please use the terms from my code and avoid general descri... |
Printing the lyrics of "Twelve Days of Christmas" seems to be a fairly popular programming challenge.
As I've successfully attempted it, I was wondering if the code can be simplified even further (say no loops)?
Any feedback in regards to style and/or logic would be greatly appreciated.
#!/usr/bin/env python3
verses ... |
I have a class that is used for serializing and deserializing global application variables. I would like to know if there is anything that I can improve. I know I could inject a dependency to support multiple different serializing formats, but that is not my concern. I would especially want to know if my locking does a... |
Recentely I have started teaching myself some basic AI concepts and this was my first attemp at using a random forest in order to classify the iris data set. It would be great if anyone could give me any sort of feedback on the code, specifically the style and readability. I apologize if the code block is formatted inc... |
I have solved the following exercise and would like to get some feedback on my implementation.
Create a function that uses futures to parallelize the task of downloading random quotes from https://www.braveclojure.com/random-quote using (slurp "http://www.braveclojure.com/random-quote"). The futures should update an a... |
I'm wondering if there's a better way to write the ApiService and the CategoryService so that CategoryService is basically just a call to extend ApiService with the string 'category' and the base type 'ICategory' or if this is the best that I can get from typescript and angular? There will be many more endpoint service... |
This is a snake game I made,
Note: at this point, I would like to hear any thoughts/ reviews about it.
Thank you
Game class:
package snake;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.KeyAdapter;
import java.awt.event... |
public final class App extends javafx.application.Application {
@Override
public void start(Stage primaryStage) {
var rectangle = new Rectangle(150, 100, Color.BLACK);
var text = new Text("START");
text.setFill(Color.WHITE);
var vbox2 = new VBox(text);
vbox2.setAlignment... |
This program prompts the user to enter a file name and displays the occurrences of each letter in the file.
Is there a simpler and more efficient way to do this? Please, help me figure this out. Thanks!
import java.io.*;
import java.util.Scanner;
public class OccurenceOfEachLetter {
public static void main(String[... |
I need to write a method that will print the integers from [1, maxValue] in a pyramid where the nth row contains n numbers like so (for printChart(24)):
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
16 17 18 19 20 21
22 23 24
I am wondering if there is a way to optimize my code for functionality, simplicity, or computati... |
This is a script to check the sequence number (8 bit unsigned integer) in a binary file and make sure it is incrementing till the end and not missing any sequence number in between. Sequence number is some 'x' bytes from a sentinel found in the binary file. The fixed size packet (some audio data) in binary file gets re... |
I have this code which is a third-party transfer for ATM console app. For best practice, should I just put all the code into one try block or with multiply try block like below?
class ATMConsoleApp
{
internal void Execute()
{
// todo: to replace these below with a automated test case - start
// ... |
I didn't find an implementation on CR of the circular doubly linked list, using generators. Hence, I tried it myself.
Description
The class Deck represents a circular doubly linked list, only
referencing the head node. The tail node is derived as
head.previous. The length of the list is evaluated from iterating
... |
This program is a clock that only displays minutes passed since midnight. This program is supposed to be really simple but because of some "aesthetic bug", I wrote quite a lot if-else statements that I think can be simplified.
Format Input
The first line will contain an integer T, the number of test cases.
Each tes... |
Some backup Bash script on my machine copies a specific directory entries filenames into a text file. Entries that no longer exist have to be kept (entries added during a previous run).
The script makes sure that entries which still exist will not be inserted twice in the backup file using sort and uniq.
local file=~/b... |
Given sentence for example: ala ma kota, kot koduje w Javie kota I should to every letter occurring in the sentence I should map every string that this letter contains. So the output should be:
{a=[ala, javie, kota, ma], d=[koduje], e=[javie, koduje], i=[javie], j=[javie, koduje], k=[koduje, kot, kota], l=[ala], m=[ma... |
So I made this calculator in c# console, I'm pretty nooby-ish in programming. I want to know if I can make it better, because my coding skills suck. Pretty sure my logic sucks too.
Any advice and tips?
public static void Main() {
bool returnToStart;
do {
returnToStart = Calc();
... |
I made this two player TicTacToe game as a challenge i was given in class. The game starts where the first player chooses where their X will be placed. Each area in the array has been given a number starting from 1 and ending at 9. After X chooses their area, the game will let the user know who's turn it is, and they w... |
This topic is about the same project as this previous one.
I think posting the full project was a bit too much, so here I post again only three functions, which are the core of my program, with a few modification from the comments I already had.
The goal is to generate words that sounds similar to a language. In order ... |
I'm currently making an app for my side project and I was looking to get some insight on the main js file, what can I improve, the error handling, what am I doing wrong, etc. I'm mostly confused about the error handling.
This is the main javascript file:
import express from 'express'
import cors from 'cors'
import dot... |
I've written some utilities to read text from streams. One of these, the ReadTo method, is to read text from a specified stream until a given text is encountered, behaving like string.IndexOf, but with streams.
Really, it's quite fast. But I'd like to know if anyone knows any way to make it even faster, as it's used in... |
This came out on the spur of the moment, as a quick and dirty tool to have the job done.
This is a simple image scraper for immensely popular and legendary comic website inspired by a Python Easter Egg.
For those who don't know it, run your Python interpreter and type import antigravity and hit Enter. :)
As for the cod... |
I've written this shell script to place Ant build.xml and build.properties into my project directory. It takes two options, one which ensures the project is set up for JUnit test compilation/running. The other modifies java compile/execution targets for JavaFX. A name for the project node in build.xml can also be given... |
I'm writing a bash script to that picks up a user password from an environment variable, hashes this, and inserts the results into a postgres database.
What I have works and looks fairly readable to me but I'm no expert on bash. Are there better conventions I could be following for what I'm doing?
#!/bin/bash
HASHED=$... |
I am new to JavaScript. The below code works on array y from tree values of 1 to 5, but I want to extend it to check trees value of 100.
array y is of the type [{key:value, key:value}, {key:value, key:value}]
I was wondering if I can I implement a loop within the repeating portion of the body of the code?
Thanks in ... |
I'm feeling uneasy with this service method that I wrote:
@Override
public Optional<Set<TenantDTO>> getAllTenantsOfUsers(Set<Long> usersIds) {
return Optional.ofNullable(usersIds)
.map((ids) -> tenantRepository.findAll(QTenant.tenant.users.any().id.in(usersIds)))
.map((i... |
Earlier I did post with full code about Prepare and export data to MS Word file. The user t3chb0t recommended me to separate some part of full code to this post.
Context
The task of code for review is convert my types (Contracts, ActCompletion) to Dictionary<>.
I will describe the context of this task. I have a templat... |
Jojo is browsing the internet while suddenly he sees an ad about the new cafe. The promotion is if the price
of an item is N dollars, then you can buy the second item for half the price, the third item for a quarter of the
original price, and so on, but if it becomes less than M dollars, then you have to pay M dollars.... |
I would appreciate som feedback on my fictional survey form. I am doing the freeCodeCamp curriculum and a Survey Form is one of the Responsive Web Design Projects using only HTML/CSS.
I am especially interested in feedback regarding best practice, naming conventions and efficient code.
The code is also on GitHub.
HTML... |
I have to calculate costs based on country code and city(optional). There is also a condition that countries in Asia have separate pricing logic depending on both country and city and they are stored in a different table (for segregating regional price variances). For the rest, it's only dependent on country code. Let'... |
For past few months I was trying to understand genetic algorithms (GA) and most of the materials availble in the web was not always easy for me. Then I came across this article written by Ahmed Gad Genetic Algorithm Implementation in Python which implemented GA with numpy. Using this as a guiding tool I wrote my first ... |
I was asked to move the code here.
I have different shapely.LineStrings like so:
which I then buffer to create a polygon like so:
I've played around a bit and found that buffering each line segment is slightly faster than unary_union-ing all the linestrings and then buffering the whole thing together. However I do ne... |
Here is my take on Minesweeper in Java. Any feedback is welcome regarding readability, design or anything really.
Cell.java
public class Cell {
public static final int BOMB = -1;
boolean revealed = false;
int row, col, val;
public Cell(int... coordinates) {
this.row = coordinates[0];
... |
As a guy who started coding a month ago, I would like an honest review of my version of breakout that I created using pygame.
import pygame
import random
import sys
#level1
global level1
level1 =[
[0,0,0,0,1,1,1,0,0,0,0],
[0,0,0,0,1,1,0,0,0,0,0],
[0,0,1,1,1,1,1,1,0,0,0],
[0,0,0,1,0,1,0,0... |
I am pulling some financial data from the IEX Cloud API. Since it is a paid API w/ rate limits, I would like to do this as efficiently as possible (i.e., as few calls as possible). Given that the tickers list is likely to have thousands of indexes (oftentimes with duplicates), is there a better/more efficient way than ... |
I am trying to do certain operations in dataframe as shown in my code below. Though this works fine.However I am repeating the same statements twice or following a dirty approach to perform the operations twice. Can you help me to make it efficient and elegant?
I have a dataframe df in which I have to apply certain rul... |
I have a settings file, which is loaded in once and takes the values from the settings json file and uses them as the attribute values. I was thinking of using the @property instead of overriding __getattribute__ but I feel as if there is a better, more elegant solution. Note that the application it is used in is multi... |
In part one (Tkinter program to teach Arabic) I was asking for help to review the part of the program responsible for managing the main screens and links to all of the different lessons. From the responses I got, I was able to reduce a lot of redundancies in my code thru the use of classes (a new skill for me) and was ... |
I wrote a page with Laravel to manage projects with Scrumpoker through blade syntax with controllers, models and Vue.js.
My problem is that I wrote the actual Scrumpoker in a single file.php file and it is loading by using a method through an onclick event of a form.
Now I want to split it up, make some refactoring and... |
I am making session store which will store some data and read some, This
session store can store multiple data( SessionInfo) to the map.
Data Structure
#include <map>
#include <string>
#include <iostream>
#include <fstream>
#include <vector>
#include <memory>
#include <iostream>
template <typename T>
class IBasicStre... |
I made this javascript code for a simple slider that can be controlled by arrows up/down.
I'm wondering what I could have done better..
document.addEventListener('keydown', changeSlide);
var wrap = document.querySelector('#wrap');
var slides = wrap.getElementsByTagName('div');
var slidesCount = wrap.children.length-1;... |
I have these scripts
@section('custom-scripts')
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script type="text/javascript">
let steps = ['device', 'agent', 's... |
This Python code generates mazes with color and size customization. I intend to add several new maze generating algorithms(Sidewinder, Kruskal, Prim ...) to the Maze class but for now, there is only one (Binary tree algorithm). I need feedback for the overall code and there are a few specific points that I need suggest... |
Problem
I need to read custom text input of a sample document object model (DOM) represented in a json format from a file and store it in a struct I've defined as DomNode. I need help on properly navigating these DOM elements from the input file and keeping track of the child node pointers at each level of the dom tre... |
I'm working on a server and need a complete list of plugins that are installed for all wp installations. I only need to know whether a plugin exists or not, it doesn't matter where it exists.
For example, given:
/siteA/wp-content/plugins/someplugin
/siteA/wp-content/plugins/anotherplugin
/siteB/wp-content/plugins/some... |
I have the following table in a PostgreSQL database:
creator uuid not null,
post uuid not null,
type text not null,
content text not null,
constraint check_type check
(type = 'comment' or
(type = 'vote' and
(content = 'up' or
... |
The code below parses a tracklist (sample input below) and generates a six-member tuple, including cumulative timestamps in mm:ss. (sample output at bottom).
couldn't easily see how to rewrite it from a for-loop to a generator get_track_with_cumulative_timestamp(itt)
I think we don't need a custom object, i.e. avoid t... |
I'm a beginner in python so I decided to take a simple challenge and wrote tictactoe
How to write it better in future?
What's wrong with my code?
from random import choice
again = ''
board = '[1][2][3]\n[4][5][6]\n[7][8][9]'
win_combination = [(1,2,3),(4,5,6),(7,8,9),(1,4,7),(2,5,8),(3,6,9),(1,5,9),
(3,5,7)]
pleyer_n... |
Here is my problem, I receive these kind of json data and I don't know in advance the keys (unknownProperty#) but the different objects in this data array have the same keys. What I need to do is to calculate the number of each level of alert (these levels are fixed).
Here is what my end result should look like
var res... |
I have just written this code for toggling between two possible states of an object.
// This can't change, and only ever has two states
const MODES = {
ON: 'ON',
OFF: 'OFF'
}
// this is my method
const toggleMode = currentMode => {
const modes = Object.values(MODES);
const newMode = modes.find(mode => mode !... |
I have a working code and it works fine for small amounts of data
Option Explicit
Sub Test()
Dim ws As Worksheet
Dim myAreas As Areas
Dim c As Range
Dim sTemp As String
Dim lr As Long
Dim i As Long
Application.ScreenUpdating = False
Application.Calculation = xlManual
... |
I have three datasets, "CV", "FV" and "LA". I have attached reproducible data for all of them. The idea is that some combination of the elements in each column of CV and FV should sum up to equal the corresponding column entry in LA. You can think of each row entry in each column as having two possible outcomes, either... |
This is one of the methods in a project for generating points between two given points. We add points of route with a 25ms delay in an array and a camera on Google Maps is always at the last point. So we need to move it smoothly. This method adds those extra points between any two given points to make it move smoothly.... |
I have a list of labels for printing. Now I have go over the list and print the labels. The layout is specified by how many labels per page and per row on a page I can print.
@{
var labels = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17 };
var labelsPerPage = 10;
var labelsPerRow... |
I have built my own generic class to implement IEqualityComparer(Of T), which takes a delegate as an input for the constructor. This delegate takes two objects of type T as an input and returns True if they are to be equal.
''' <summary>
''' A generic equality comparer which assess the equality of two objects via the p... |
I try to handle or catch possible errors with PHP/MySQL for security reasons and would like to know if I'm doing it right.
The first case, connection: I use it as a function and call it always when I need a database connection:
function pdo () {
try {
$pdo = new PDO('mysql:host=localhost;dbname=dbname', 'user',... |
I'm new to PyTorch and I'm writing a unit test for an activation function I'm making.
I plan to test against a reference implementation for this function. I want to approach this in a test-driven way, so I learned to write a test using a known-good function: the ReLU implementation "MyReLU" from this beginner tutorial... |
https://leetcode.com/explore/interview/card/top-interview-questions-medium/108/trees-and-graphs/787/
Given a binary tree, return the zigzag level order traversal of its
nodes' values. (ie, from left to right, then right to left for the
next level and alternate between).
For example:
Given binary tree [3,9,20,null,... |
I have a code that keeps checking a webpage with a price on it and when the price meets a number I set it to, the thing is purchased. I am looking for ways to increase the speed of it.
I have added multiprocessing and its performance may have improved, but I don't know if its the best-case scenario for this code and th... |
I'm writing an application where users can write custom expressions which are then converted to JavaScript functions and executed. The expressions are used for filtering and sorting data from a database and to improve performance I want to be able to run the expressions on my server without worrying about getting hijac... |
I have been writing code to automate some weekly reports. I had help over on Stack Overflow. I have code that works for the most part, however there are a few things that I just can't seem to fix.
In short, I loop through the data and create a dictionary of dataframes based on 'location' key unique values. I can use th... |
I've just started learning Rust (coming from Haskell) and decided to test a toy expression interpreter.
Code:
use std::rc::Rc;
pub type RAST<T> = Rc<AST<T>>;
#[derive(Debug)]
pub enum AST<T> {
ConstInt(isize, Rc<T>),
Add(RAST<T>, RAST<T>, Rc<T>),
}
pub fn eval<T>(x: &RAST<T>) -> RAST<T> {
match &**x {
... |
Recently I have started learning C++ and I decided to learn C along the way to improve my understanding of how computers work. For C I am using "The C Programming Language Book" by Brian Kernighan and Dennis Ritchie.
The exercise in question is to print all input lines disregarding trailing whitespace and empty lines.
... |
I'm trying to loop through an array, add " before, ", after each member but ommit the , at the very last member in order to generate a JSON string:
const generate_list_data_attribute = (attribute_name, from_array) => {
let string = '';
from_array.forEach((element, key, array) => {
if(Object.is(array.le... |
The management of bidirectional mappings is a reoccuring topic. I took the time to write an (hopefully) efficient implementation.
using System;
using System.Collections;
using System.Collections.Generic;
namespace buka_core.misc
{
/// <summary>
///
/// File Bijection.cs
///
/// Provides an implem... |
I just finished a huge project of mine; a maze pathfinder. At the start, the maze that the program is traversing is randomly generated, with a 25% change to place a wall (#) at that position in the maze. The program uses the distance between every direction it can make at its current position, and takes the direction t... |
I have this simple Rust program, which creates a file called numbers.txt and writes the numbers 1 to N (N is here 10000000) to it, separated with newlines:
use std::fs::File;
use std::io::Write;
const N: i32 = 1e7 as i32;
fn main() {
let mut data = String::new();
for i in 1..=N {
data.push_str(&form... |
This may be better suited on Stackoverflow, in which case, please let me know and I will move it over...
Background
Consider the following file structure:
/config
│ index.js
│ app.js
│ api.js
│ ...
The purpose of the above is to provide global configuration throughout a static frontend application, including w... |
As a self-teaching Python beginner for almost 4 months, I have mostly been doing online challenges including Project Euler problems.
Problem 45 asks:
Triangle, pentagonal, and hexagonal numbers are generated by the
following formulae:
$$
\begin{array}{lll}
\textrm{Triangle} & T_n=n(n+1)/2 & 1, 3, 6, 10, 15, \ldo... |
I maintain a C library project both on gcc and clang.
I am looking for advice on how to make the following macros more portable, terse, readable or standard abiding.
When I compile
#define STRINGIFY(arg) STRINGIFY_(arg)
#define STRINGIFY_(arg) #arg
#define VERSION 1.01
#define PROJECT myProject
#define SUB_PROJECT myS... |
Inspired by this question and its answers, I've made my own version.
/// <summary>
/// A one-one relation bidirectional map.
/// <para>
/// A one-one relation means that each entry of type <typeparamref name="TFirst"/> can correspond to exactly one
/// entry of type <typeparamref name="TSecond"/> and visa ve... |
I'm trying out a new continuous histogram coloring method for Mandelbrot rendering in R, and since it requires three loops (three passes), each of them doubly nested, there should be a way to vectorize the code to speed it up.
However, I'm not yet familiar enough with vectorization in R, especially when conditionals a... |
Currently my code (at GitHub) is this:
module Gaussian where
import qualified Data.Complex as Complex
-- Enables toComplex.
-- Qualified to avoid clashing.
data Gaussian = (:+)
{
real :: Integer,
imaginary :: Integer
} deriving
(Show, Read, Eq)
-- The gaussian integer type.
-- A gaussian integ... |
This is a program for converting English to the pseudo-language Pig Latin. Not the strictest form of Pig Latin but it most likely will accurately output an argument in Pig Latin. I got the idea from a list of ideas on Github. Is there any way I can improve it concisely?
def pig_latin(message):
consonants = ['b', 'c... |
I have two Models in my Rails 6 / PostgreSQL application which have a many to many relation; Car and Driver. The goal is to get all records (Cars) which have no association at all (Drivers). At the moment this is done using Ruby (2.6.3) like this:
result = []
Car.all.each do |car|
result << car.id if car.drivers.empt... |
I made the acquaintance of big-O a couple of weeks ago and am trying to get to grips with it, but although there's a lot of material out there about calculating time complexity, I can't seem to find out how to make algorithms more efficient.
I've been practising with the the demo challenge in Codility:
Write a functio... |
msoGraphic is an MsoShapeType enumeration that is available in Office PowerPoint 2016 and later (versions which can handle svg graphics). If you attempt to check an MsoShapeType against msoGraphic in earlier versions of Office you will get a compile error - as msoGraphic is not defined (in any module containing Option ... |
The code is to check the rows in a table. If in a table two non consecutive rows are checked then all the in between rows should be selected by itself. Also, after selecting two rows, on selection of third row it should throw an error.
How can I simplify this code?
onSelectionChange: function(oEvent) {
var aInd... |
I have a data file and a rules file. First column of rules file will have columns from the data file and the second column has an pandas operation which has to be performed on the respective Column. Please refer below details:
This is the input data:
d={'Name': ['Ankan', 'Shiv', nan, 'Sandeep'],
'email': ['ankan@domai... |
My company wants me to build a serverless component (AWS Lambda) that checks every minute for our system components health.
The data model (classes structure) I have devised so far is as pasted below.
The main problem I am trying to address is I wanted to have a collection of all our system metrics. At first I thought ... |
This is the first application or really any Scala I have every written. So far it functions as I would hope it would. I just found this community and would love some peer review of possible improvements or just tell me flat out what I'm doing wrong.
This code is supposed to read a table of tables then take all of the ... |
Assuming I have the following slice:
mySlice := []string{"one", "two", "three"}
and I want to know whether or not it contains a given string, say "three".
I could iterate over each entry:
for i, v := range mySlice {
if v == "three" {
return i
}
}
But I could also convert the slice to a map:
myMap := make(map[... |
(There is a follow-up question available to this: Follow-Up Question)
So I have this:
<html>
<body>
<div id="output">
</div>
<script>
function NodeSet() {
this.array = [];
}
NodeSet.prototype.clear = function() {
this.array = [];
}
NodeSet.prototype.add = function(node) {
this.array[node.id] = node;
}
NodeS... |
The below code was written to generate γ, for educational purposes.
Single threaded, no functional zeroes required, no binary splitting(which can all be used to compute competitively like y-cruncher, that version in works).
Uses the Arithmetic Geometric Mean to calculate large logarithms quickly.
Uses decimal module fo... |
I'm creating a 2D game in JS, and I've made the generic class that all objects in the game will be (I've decided they are all circular for now).
An object has motion and angMotion array properties which contain the 0th, 1st and 2nd derivatives of the object's (angular) motion.
I've also introduced aliases for each of t... |
I have a list of 9000 dictionaries and I am sending them to an API in batches of 100 (limit of the API). The API returns the list of 100 dictionaries just expanded with more key/value pairs. So both lists look something like this:
[
{Key1:Val1, Key2:Val2},
{Key1:Val3, Key2:Val4},
...
]
and returns:
[
{Key1:Val1, Key2:... |
I wrote a filter for pandas that converts :-) to ☺ but not in inline code or code blocks. Pandoc makes it so the applyExceptOnCodeBlock smileyfy function trickles through the whole tree. But since I operate on Blocks and Inlines I need to handle every data constructor for Block that takes Inlines.
import Text.Pandoc.JS... |
I have a primary table, REP_ASSIST.ES_LOG with multiple columns that are foreign keys to another table, REP_ASSIST.ES_DOCUMENT_STATUSES. Here is an example of what my main table looks like:
+-------------------------+-----------+-------------------------+-----------------------+
| created_at | filing_id | ... |
In a university library, there was copy of "Making The Most Of Your ZX 81" by Tim Hartnell. I flipped to an interesting page from the index and found this program in BASIC, and thought it interesting enough to rewrite in Python. It's a number guessing game.
from random import random
from sys import exit
print("LOST IN ... |
The following code solves Project Euler Problem 121. I will quote the description of the problem
A bag contains one red disc and one blue disc. In a game of chance a player takes a disc at random and its colour is noted. After each turn the disc is returned to the bag, an extra red disc is added, and another disc is t... |
The below code was written to generate γ, for educational purposes.
My general methodology is as follows:
Compute Gamma via the accepted answer's algorithm here.
In order to do this I need to compute the natural log of a large k.
Compute Pi via the AGM as here.
Compute the natural log of 2 via the last algorithm here... |
I've implemented the game of Pig in JavaScript. My implementation has the following rules:
Two players take turns playing in rounds.
In a round, the player rolls a single die as many times as they wish, with the sum of their results becoming their score for that round.
If the player rolls a 1, then their score for tha... |
Problem statement:
Working from left-to-right if no digit is exceeded by the digit to its
left it is called an increasing number; for example, 134468.
Similarly if no digit is exceeded by the digit to its right it is
called a decreasing number; for example, 66420.
We shall call a positive integer that is neither i... |
I have found the need to schedule a few simple functions in a first-come-first-served way so I developed a small task scheduler based on multiprocessing and I thought it would be a good candidate for my first question here.
I'm open to all kind of comments, regarding style, conventions, possible bugs and other things I... |
In another attempt to further my knowledge in the JavaScript language, I've written a chess board generator that will essentially create a chess board with any initial state supplied. This supports the idea of chess game types like fairy chess or series self-mate and puzzle generation alike.
It was a rather fun project... |
I have written the following quicksort without using online help. It seems to be fine, but is there anything to improve?
#include<iostream>
using namespace std;
void quicksort(int*, int, int);
void print(int *p, int n)
{
for(int i=0; i < n; ++i)
cout << p[i] << ' ' ;
cout << endl;
}
int main()
{
in... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.