instruction stringlengths 71 71.9k |
|---|
Input Format
Input starts with an integer n (1 ≤ n ≤ 100) indicating the number of cases. The following n lines each contain a test case of a single even number x (4 ≤ x ≤ 32000).
Output Format
For each test case x, give the number of unique ways that x can be represented as a sum of two primes. Then list the sums (one... |
I have an object that houses only static functions. The functions are stand alone and are not dependent on the state of the object.
I hear that static functions are a nightmare in terms of testing, an anti-pattern if you will. I get it, the state of the object could be impossible to predict.. But these are stateless.
... |
I've written an amd64 assembly routine (in gas syntax using the System V calling convention) to convert three decimal digits to Densely packed decimal because I wasn't satisfied by the performance of the assembly generated by gcc and clang for all implementations of the conversion I could think of. Here is the code:
... |
I created this function to recursively copy an entire directory from an FTP server. It works just fine except that it is about 4 times slower than using FileZilla to do the same operation. It takes approximately 55 seconds to download the directory in FileZilla but it takes 229 seconds with this function. What can I do... |
I wrote a Ruby module to update DNS zones on certain events of the Docker API. Its purpose is to make container reachable by their name over a network. I know this is also possible through /etc/hosts entries, but in my use case I can not use the name resolution of the docker host.
I'm am pretty new to Ruby so I guess t... |
I am working on a speech reorganization project. I have a util class that consists of three methods: check if a microphone exists, check microphone availability, and check text-to-speech availability. Can anyone review my code?
public class MediaUtil {
//returns whether a microphone exists
public boolean getMi... |
I'm writing in VB.NET, using VS Community 2013. I don't know much about this language. I have managed to make my code work, but I suspect it is possible to improve the code a lot.
This code extracts packets from some data I've received using TcpClient.
Private inbuf(10000) As Byte
Private inoff As Integer
Private S... |
I have a helper extension method that I use for path string validation. It looks as below. It's purpose is to work with network paths as well, so in case a network resource is not available, I do not want my applications to freeze, hence the specified timeout etc.
public static bool IsExistingFilePath(this string sourc... |
I tried to write a foolproof function for the first part of the first problem on adventofcode, which asks for the count of ( characters minus the count of ) characters in a string.
The function intentionally ignores any other characters in the input string.
function findEndFloor(floors, upFloorSymbol, downFloorSymbol)... |
I am writing a trivial continuous integration tool using node.js to learn the platform. So far it can download a project from Github, and unzip it into a random folder in a predefined dropfolder. But I'm pretty inexperienced in pure JavaScript and loosely typed languages in general and the code that I write looks very ... |
using System;
namespace Friendly_Bot
{
internal class Program
{
private static string[] Greetings = { "Hello, you have a", "Hey, you have a", "Hi, you have a" };
private static string[] Compliments = { "cool", "fashionable", "stylish" };
private static string[] Garments = { "coat.", "dr... |
As an exercise, I decided to program my own version of the game Pop the Lock for the iPhone. The look and functionality are essentially the same, though the controls are modified for playing on a computer.
I am looking for any feedback or criticism on my program's layout or overall flow. I also kind of hacked togethe... |
I am trying to implement substring in C. How efficient and standard is this code? I have a hard time understanding how C functions are usually meant to work, like how printf() returns an int or size_t.
size_t substring(char *destination, char const *string, int start, int len) {
// writes a substring to the destin... |
I have several very similar subclasses that I (think I) want to be stored in the same database table. Most of the fields are identical, with each subclass adding 1 or 2 custom fields. My code is using the Django ORM, but I think the question is more general than that.
Problem specification
The app is meant to simplify ... |
I'm working on a table component that is able to scroll through millions of lines of data. Not bad for the front end. The way I'm doing this is to only render a small table with 10 rows and then, when the user scrolls, I change the data in that table.
The table itself is not in a scrollable div because the entire html ... |
CodeEval FizzBuzz
Quick Description:
Take 1 command line argument of a file-path. This file will contain
test cases formatted as such 3 space separated numbers per line. For
numbers X, Y and Z you must print out all numbers between 1 and
Z, space separated, replacing all numbers divisible by X with 'F'
and all... |
FizzBuzz in VBA. Takes start and end numbers as arguments. Will handle any pair of integers to +- 2 Billion or so, determine whether the sequence is increasing or decreasing and output numbers to the immediate window.
Public Sub PrintFizzBuzz(ByVal startNum As Long, ByVal endNum As Long)
Dim currentNum As Long
... |
I've written a simple FizzBuzz in TSQL using some IF loops.
Here's a SEDE link to run it in your browser.
DECLARE @i int = 1
DECLARE @str varchar(8) = '';
WHILE @i <= 30 BEGIN
SET @str = ''
IF @i % 3 = 0
BEGIN
SET @str = 'FIZZ'
END
IF @i % 5 = 0
BEGIN
SET @str = @str + 'BUZZ'
... |
Before you close vote:
Yes, Scratch questions are okay.
Link to project on Scratch
For the hundredth fizzbuzz question, I'd thought I'd spruce it up a bit and post something new.
So, first make three variables named i, iterations and string:
And a list named ListOfFBs (FBs = FizzBuzzes)
Here is my main code:
Which... |
This is a simple binary search tree implementation written with C++'s templates feature I wrote to learn C++. What improvements would make this cleaner and better as far as C++ practices go, and are there any problems with implementing the algorithm?
#include <iostream>
#include <string>
using namespace std;
templat... |
I have quite a lengthy method that I know for sure can be optimized, yet I am not sure how to do it. The method is in my User model, and essentially gets the questions assigned to the user in the current week. Questions can be assigned to a variety of intervals, so it's important that for each week we get the right one... |
I am developing a plugin for intellij that basically monitors a log file and displays the data in a tool window within the IDE in real-time. I have managed to get it working but I would like to know the areas where I can improve on. I'm specifically interested in the structure of my code and the log file monitoring met... |
I would like to know an alternative, more elegant way to write the following methods.
I am especially not enthusiastic of the nested if statement or if for validate null values.
Now there are 3 if statement for null validation.
Any method:
private void LoadAlertas()
{
// *** OMITTED ***
... |
My current query:
select `t1`.* from `product_variant_values` as t1
inner join (
select `t1`.* from `product_variant_values` as t1
where (
(t1.`option_id` = 1 and t1.`value_id` = 1) or
(t1.`option_id` = 2 and t1.`value_id` = 4) or
(t1.`option_id` = 3 and t1.`value_id` = 7) )
group by t1.varia... |
I have a model:
class ColumnItsValues
{
public int PropertyID { get; set; }
public string ColumnName { get; set; }
public string ValueOfColumn { get; set; }
}
two collections:
List<ColumnItsValues> listColumns = new List<ColumnItsValues>()
{
new ColumnItsValues() {ColumnName="GUID", PropertyID=0, ValueO... |
I wrote this program to calculate a value from an energy function from a sequence of 1s and -1s. The problem here is to find the lowest possible fitness for a function (note that this is original function; in my implementation I pre calculate power of c c*c and put it in the thread so I avoid calling a method):
double... |
The following is my python solution of project euler 12.
The sequence of triangle numbers is generated by adding the natural
numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7
= 28.
The first ten terms would be:
1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
Let us list the factors of the first sev... |
For some reason, I completely lost my reasoning with this code. I can't hold this simple logic for too long in my head. Actually, I want to improve this code, making it a little concise. The if (so.scan_complete and force) or not so.scan_complete: is just not a KISS thing. Please any suggesion to optimize and concise i... |
Here is my Implementation. It is I think almost like algorithm.
public static uint[] CountingSort(uint[] A ,uint max)
{
uint[] B = new uint[A.Length];
int[] c = new int[max +1 ];
for (int j = 0; j < A.Length; j++)
c[A[j]]++;
for (int i = 1; i < ma... |
I am a new to Eigen, and I implemented a logistic regression model with it. It works but I don't know whether it is implemented in an efficient way.
#include <iostream>
#include <Eigen/Dense>
#include <cmath>
using namespace Eigen;
using namespace Eigen::internal;
using namespace Eigen::Architecture;
using namespace s... |
I'm working an open source project written in Python that is a wrapper to the Pushover API called py_pushover.
The main function of this wrapper is the push_message function which allows the user to push a notification. The API has 10 possible parameters with only 3 being required. I've handled those three required... |
How to count the solutions of the equation \$x \cdot y + x \cdot z + y \cdot z = n, (0 \leq n \leq 10^4)\$ with the constraint that \$x \geq y \geq z \geq 0\$ ?
To solve this i've isolated the z value and brute-forced the values of x and y. If the values x,y,z satisfy the constraint and equation than its a valid solut... |
I recently had submitted my bashscript for building an OS for review and got valuable feedback, so I rewrote the entire script for a makefile:
Makefile
# Make File for Bulding Ultron
# Sets up the Assembler
AS := nasm
ASFLAGS := -f elf
ASFILES := $(wildcard kernel/boot/*.s kernel/arch/*.s)
ASOBJECTS := $(ASFILES:.s=.... |
I am using classes for the first time. In this program I want the object to run infinitely so that any change in the MongoDB will trigger the function and do the necessary processing.
I am little confused about the using of the self. Please give me feedback on my code.Thanks!
class first_level:
def __init__(sel... |
I am trying to write a function that will count the occurrences of a pattern in a string without overlap. This is what I have right now.
size_t count(char *string, char *pat) {
size_t patternLength = strlen(pat);
size_t stringLength = strlen(string);
size_t count = 0;
char *compareString = malloc(patter... |
This is a rags-to-riches take on this question, specifically an improvement of my original answer there.
Copying my interpretation of the calculations involved from my answer:
Given a 70-character String for the Keirsey Temperament Sorter test, e.g.
"ABABABaABABABaABABABaABABABaABABABaABABABaABABABaABABABaABABABaABABA... |
I have a method which I use on occasion to convert strings (like enum and property names) to PascalCase for display.
It's fairly simple, so there's probably not much to comment on, but as usual I appreciate any advice on improving it.
/// <summary>
/// Converts a string of dash-separated, or underscore-separated words ... |
Below is the code I have for a RandomForest multiclass-classification model. I am reading from a CSV file and doing various transformations as seen in the code. I am planning to run this in a Spark cluster with lots of data (at least 6 million rows of data with 50 features). I can get sufficient amount of RAM and cores... |
First, I must humbly admit that I've been a developer for many years but I've almost never had to work as a front-end, Web UI developer. I've been given an opportunity to work for an organization as a front-end and back-end web developer and I'm having to learn about the in's-and-out's of HTML/CSS/JS code. This is my... |
I wanted to try and use the Sieve of Eratosthenes to find all prime numbers between some arbitrary bounds 1 <= m <= n. The simple implementation of the sieve does not consider the lower bound at all, it always starts from 1 (or actually from 2). So for a big enough n, simply creating an array would be impossible.
The a... |
I have this:
public void InfoAssignment()
{
//MessageBox.Show(firstName = firstNameBox.Text);
firstName = firstNameBox.Text;
lastName = lastNameBox.Text;
phoneNumber = phoneBox.Text;
address = addressBox.Text;
//Check for text in firstNameBox
if (!String.IsNullOrWhiteSpace(firstName))
... |
How do I make this go faster? It currently takes about 30 seconds on a 3gb file. I am using this to get a checksum from the file to compare it to Microsoft's official checksums. I am wondering if using a buffer would help and if so how should I do that?
public static String GetSHA1Hash(string fileName)
{
... |
I wrote this program for school (first year in college) and it works, but it's too slow. I wondered if anyone could help me optimize this a bit, because I've been trying and trying, but it just won't get better.
If I choose a lower limit of 5000 and an upper limit of 10000 it my program 10 times longer than my professo... |
Background: I'm trying to learn basic OOP with Python. I have this program I wrote to help my son practice math problems. It does addition, subtraction, multiplication, and division. He can choose easy, medium, or hard for each operator.
Here's an excerpt of the code. It's the "easy" addition function. (The "mediu... |
I have a program to read signal data from 120 files in a folder and performing the energy of the signal.
It works correctly, but execution time is more than 20 mins, so there may be a problem with the code. Can someone look into it and suggest possible methods to reduce the execution time?
import java.io.BufferedReade... |
I'm interested in learning how to create shell scripts with bash so here's one of my first exercises, taken from here. It is an extension of the problems Elementary - 4 and 5.
The goal of the program is to sum all multiples or ARG1 or ARG2 below the user's input number.
#!/bin/bash
echo "This program will find all the ... |
I have a MongoDB collection of product IDs/unique products attributes and a second collection of codes that relate to attributes common for products whose IDs are prefixed with those codes.
For example, two product IDs might be aaa17859 and aaa98542 so their code prefix is aaa.
I have several thousand codes, and the co... |
I have an array of objects where each object has two keys: key (k) and value (v). I need to make an object that would take values of k and collect corresponding values of v as a value of this key, an array of them.
So, for example, from an array
[{
k: 'a',
v: 0
}, {
k: 'a',
v: 1
}, {
k: 'b',
v: 2
}]
I need... |
I am writing a module that can access localStorage through a public API which exposes methods that allow string or array returns.
It doesn't feel as though I'm doing this in the most effective way. For example, I feel as though using:
var tudCache = getTud(); to grab the object from getTud() doesn't feel like the most ... |
Self explanatory, and all the functions contain descriptions of their specific problem statements.
Since this is project Euler, I would be particularly interested in any analysis of the functions' computational efficiency.
Option Explicit
Public Function ProjectEuler1() As Long
'/ Problem statement: sum all m... |
Inspired by Hosch250, TopinFrassi, Legato and the recent milestone of having our 100th fizzbuzz question on Code Review I decided to add an ArnoldC FizzBuzz to the collection.
I haven't found any best practices about the language, but I assume the code needs to be VERBOSE. For those unfamiliar with the language, a smal... |
I was given a homework and I have 2 solutions: one that uses this and other one that doesn't.
I tested both solutions on jsPerf but sometimes it says the version with this is faster or sometimes the other one. So I think I cannot really rely on jsPerf. Anyway, should performance be always the top priority?
By the way, ... |
This is my recursive program for the following function:
\$F(x) = G(x) - W(x)\$
\$G(x) = [G(x-1)+G(x-2)]^2\$
\$W(x) = [W(x-1)]^2 + [W(x-2)]^2\$
If x == 0 in either function G or function W, then return 0
If x == 1 in either function G or function W, then return 1
import java.math.BigInteger;
import java.io.PrintWrit... |
I am trying to work out a solution. I have to order the elements in the array a, such that a[0] is greater than a[1], a[1] is less than a[2], a[2] is greater than a[3], and so on...
Basically my method checks if the index is odd or even , and simultaneously makes a decision to swap elements to suit the criteria of th... |
I'm quite new to threading primitives in C# and was hoping you might be able to suggest improvements to this. I need to ensure that the XXX call below happens within the calling thread (XXX is a foreign call into a thread-unsafe library), so I used a queue here. It seems a bit like there should be a better primitive fo... |
Here I implement N-Ary tree in C#.
namespace ConsoleApplication1
{
public class tree {
public int info;
public tree child;
public tree siblings;
public tree(int data)
{
info = data;
}
}
public class NAryTree
{
public tree ROOT;
... |
Since it is quite a hurdle to manage dynamic arrays in C I wrote a simple generic wrapper to handle a pool of pointers. To prevent internal fragmentation when deleting and appending again I store the real indexes in a secondary index array. Do you see any flaws in my code? Would you have any suggestions ?
#ifndef __151... |
I would like to have some feedback on my code, basically because I have been spending a few hours visiting other options before I ended up with this one, so I'm not sure I'm clear enough to value it.
I have an API controller that gets and stores products in a memcached database, they will fall into one of the two categ... |
Is it fine to retry a web service call like this in Python? Would there be any scenarios the exception might not work the way we expect it? I expect it to continue only if it's fine, otherwise just retry, and if that doesn't work, just throw the error out.
def getblob(html):
num_of_retries = 2
time_interval = ... |
I was long a professional in COBOL, but noone ever dared comment my style. As the FizzBuzz seems fashion here, I made one. Verbose, of course, we're speaking about COBOL. I know I could have made in 15 lines, but decided instead to provide the full structure for a production program. Result makes 87 lines.
I'll be happ... |
I've done some code so you can obtain Object of any Class from Pool, take a look at it, is it safe? At least it works.
MultiPool class has method obtain with Class param, so can know from which inner-pool obtain Object.
import com.badlogic.gdx.utils.Pool;
import java.lang.reflect.Modifier;
import java.util.HashMap;
p... |
So there's a known bug in excel where applying named ranges via ribbon doesn't work properly (for 2010 and 2013 and possibly 2016). There was a question about it on superuser - Apply names in excel bugged?. I took a shot at it.
This code will find all of the named ranges in the book and then search a specified range f... |
This script converts the numbers to be at least 13 characters long (for UNIX_MS strings). For use with timestamps, I'm having issues with it being very slow. I wanted an alternative to grepping for one specific UNIX_MS timestamp and not finding it and then having to grep multiple more times.
For the output I wanted the... |
I wrote yet another optimized single-threaded Eratosthenes Sieve implementation in C:
erato.c
// #include <stdio.h>
#include <stdlib.h>
#define N 1000000000
#define num_t unsigned long
int main() {
register char *b = malloc(N * sizeof(char));
for(num_t i = 0; i ^ N; ++i)
b[i] = !(i & 1);
// print... |
I have complex objects containing nested objects. I need to check if a key exists anywhere in the nested object. I wrote this code as a makeshift solution. Is there any other way to search for the key?
function checkKey(obj, key) {
if(key in obj){
return obj[key];
}
else{
for (k in obj){
... |
I have this working code and was wondering how I can optimize it. Is there anything I can declare globally so it does not need to be be created over and over? This function is called around 30 times a second.
bmScreenBuffer is a global Bitmap.
Contents of drawScreen():
// Buffer - Get the main window handle to create 2... |
In the beginning, everything is defined to be of value 10, but I have to change them to suit them for different possible values, hence those are changing. I'm a (Im)mature C coder, hence there might be trivial mistakes. I would like to get feedback on how to improve it.
#include <stdio.h>
#include <stdlib.h>
#define... |
While I was writing this I had some thoughts and questions going through my head about if I was doing this in a good manner. For instance, is it good to use a StringTokenizer to loop through the words in the line I copied from the Scanner's input?
Write a method named coinFlip that accepts as its parameter a Scanner f... |
I am trying to read lines from a text file in Java, but there is a lot going on. Is this the best way to do this? I am especially concerned with resource leaks.
import java.io.*;
public class Filing {
public static void main(String[] args) throws FileNotFoundException, IOException {
FileReader fr = new Fil... |
I'm trying to learn a bit about Golang and decided to try out building an SSH address book command-line app. I used a YAML library to serialize and store data in a configuration file. The app has a few command-line options to view, delete, make, and run SSH address entries. It also runs the ssh command given an entry n... |
My goal is to make web page loading faster by bundling all the CSS files together. The web browser will then only have to load only CSS files. This will only run when the application is starting.
void function setupApplication() {
application.initialized = now();
...
var renderCSSFile = application.GWASSE... |
So I made a quick programme in F# to do FizzBuzz, I'm trying to learn more languages, so I figured I'd do something functional for a change. (Haskell is also on the list.)
FizzBuzz is pretty self-explanatory: every third value print Fizz, every fifth print Buzz (possible both if it's a multiple of 3 and 5).
[<EntryPoin... |
I am relatively new to programming and would love to get some feedback on the following section of my code.
class Gene:
def __init__(self, gene_symbol, gene_id):
# gene_symbol represents the abbreviated name of the gene (string)
# Example: 'RHO' (short for 'Rhodopsin')
self.gene_symbol = gen... |
Is there a better way to do this? That switch_status method seems like it could be made a lot more compact.
class Taxi
def initialize
@status = :available
end
def switch_status
if @status == :available
@status = :busy
else
@status = :available
end
end
end
t = Taxi.new
t.switch_st... |
I'm making a simple connect four game that I will eventually extend by creating an AI that the player can play against. Given that AI algorithms are reasonably complex, I find myself wanting to reduce the algorithmic complexity of my win-checker in order to maximize performance once the entire thing is built.
Currentl... |
I have a program that searches for prime numbers in an array specified by the user. The program starts by asking how big the user wants the array to be, then asks how many threads to split the computations.
I tested 1000 numbers, 10,0000, 100,000 and 1 million, and they all yielded results in a fairly reasonably time.... |
I am trying to work on writing readable code and reducing the amount of redundant code I write. I find this hard to do especially when it comes to algorithms. So, I wrote a quicksort program to practice.
Is there any way I can improve this? I know in terms of efficiency it could be better (instead of taking the leftmos... |
I have written a program which closely resembles the way contacts are added and dynamically sorted in ascending order in your phone or other device. Though I have used Integers instead of String, I was just wondering if this has any real world use and how I can improve it.
import java.util.*;
public class Ascending
{
... |
I just started to learn programming, going through a lot of different tutorials, trying out different programming languages and I stumble in the same sort of questions all over the place.
I give you an simple egg timer in bash I use for cooking.
#!/bin/bash
### varibales
min=$1
sec=$2
message=$3
### run
timer=$(($mi... |
I'm currently playing with D3.js.
While doing so I use this JSON-file as a data source: http://codepen.io/chriscoyier/pen/taqCe
Example of the structure:
{
"fathers" : [
{
"id" : 0,
"married" : false,
"name" : "Robert Wilson",
"sons" : null,
"daughters" : [
{
"age"... |
This code produces HTML from the results of a database query.
Self-taught, I have concerns about developing bad habits and I wrestle with the principles of OOP and MVC.
I would be grateful for your opinion on a number of issues:
The use of global. My HTML page is generated from a template which requires a config file ... |
I have a model that works, as far as I know, but it's so messy! I am very new to Java, so I'd really appreciate some help tidying up. In particular, a lot of my constructors are empty which is probably not good, and I'm not sure if I've made the right choices in terms of public, static, void etc for my methods. It prob... |
I'm writing an s-expression tokenizer in Rust.
I have the following code written, but it is not idiomatic Rust - it is quite ugly. TokenizerI is simply an interface with a body that is really of no import here other than to note that _s is unused (hence the underscore).
extern crate regex;
use regex::Regex;
use std::c... |
I have a mathematical function as shown below
$$ (h+1) * U(k,h) = \sum_{r=0}^k \sum_{s=0}^h (r + 1) * (k - r + 1) *
U(r + 1, h - s) * U(k - r + 1, s)\ + \sum_{r=0}^k \sum_{s=0}^h (k - r
+ 1) * (k - r + 2) * U(r, h - s) * U(k - r + 2, s)\,. $$
Base condition for U(k,h) is
$$ U(k,0) = (-1)^k/k! $$
I am using the f... |
I have adapted a VBA code to import all the XML files I have on a folder into Excel. I have tried to run the code with only two files and it takes about 30 seconds. Several minutes to import less than 20 files.
I need to import more than 200,000 files. Can you please help me on how to improve my code?
Sub ListFiles()
... |
In my application i keep repeating writing this pattern. I just cant figure out how to write it better. Coming to you for suggestions:
if ($_POST['x'] = 1) {add_remove($one, array($two,$three,$four,$five));}
if ($_POST['x'] = 2) {add_remove($two, array($one,$three,$four,$five));}
if ($_POST['x']... |
I'm trying to build an xliff for localization from 3 specific files: one contains a list of IDs, the other a list of source strings and the last, a list of translated strings.
Basically, each file contains 200,000 strings, and the process is taking so much time. How can I speed up this loop?
I use sed to replace < with... |
Is it considered bad practice to pass string literals as char*, when an array and not a c-string is expected by the function? From my code:
char ConsoleIO::GetNextChar(string prompt, char* choices, int numChoices) {
// Loop until valid input, or 10 times.
for (int i = 0; i < 10; i++) {
Write(prompt);
... |
I am building a GUI to display a digital clock face (four seven-segment displays), and I have a selector to switch between 12/24-hour formats. I have working code to show both formats, but it is messy. I am looking for a better solution for this section.
The obvious repetition is the section that displays the AM/PM ind... |
Here is a plunker of my working demo.
I have the following code which I have created for a subscription service for data through a webworker. I was wondering if I was following functional-reactive programming best practices and patterns on the webworker. I am new to RxJS and none of our team at work has ever used it, b... |
As detailed in this SO question, I'm using custom logic in a BTreeSet to automatically sort a foreign data type as elements are added to the container. Note that the Data type is used from another module in the actual implementation, so I can't just implement Ord for it, necessitating this approach.
I'm concerned that... |
There were a few recent questions which had a challenge like this:
The subway shop provides catering for meetings and other events. All
sandwich platters are $40 each. Cookie platters are $20 each.
Beverages are not included in catering service. Write a program that
prompts the user for the number of sandwich p... |
The problem is to find all divisors of a given integer n.
(It may be better to implement a true prime generator, rather than a fixed set, as discussed with examples here, but that was not my immediate concern. Also, I am aware that there are much faster algorithms to generate fixed number of prime numbers—I am avoiding... |
I want to condense down some of this, is there anything I can change to make it better or shorter?
It works now but I don't know what else I can change, are any of my if statements changeable to be shorter?
def main():
#displays company name and report
print("Helena Hockey Haven")
print("sales report")
... |
I am creating a miniature bulk email sender. I am using Postfix on Ubuntu with JavaMail. Here is the key part of the code:
public static void main(final String[] args){
final Connection selectConnection = DriverManager.getConnection(prop.getProperty("select_connection"));
final Statement stmt = selectConnection... |
I have written code to implement the nearest neighbour algorithm to produce a solution for the TSP problem
On my machine, the code takes roughly 10 seconds. Since this is so short, a lot of the profilers I have tried don't get a chance to record it properly. How do I profile this code effectively?
When I define the dis... |
I am trying to remove a key from a hash table, which is built using linear probing. Removing a key works fine but I know I need to rehash a portion of the table after the removal but my method down below is not quite efficient. It basically rehashes the whole table that is unnecessary. Is there anyway that I could impr... |
For an interview question, I was asked to do the following:
Given a dot separated domain name, reverse the domain elements.
Here are a few input/output examples:
codereview.stackexchange.com -> com.stackexchange.codereview
foo.bar -> bar.foo
a.. -> ..a
This was my proposed solution. I really feel like there's probab... |
Given a dot separated domain name, reverse the domain elements.
Example:
codereview.stackexchange.com -> com.stackexchange.codereview
google.com -> com.google
I just wanted some suggestions to improve my code. Or if you can suggest a better way, please do so.
package practice;
import java.util.Scanner;
import java.... |
Introduction
I am still learning both swift and ReactiveCocoa, and instead of directly applying it to one of my projects, I have instead worked a few hours on implementing a silly form with it.
My form has these elements:
Email
Password
Confirmation
Reset button
Submit button (not implemented)
There are three validat... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.