instruction stringlengths 71 71.9k |
|---|
The task at hand
I have previously asked about how optimizing Project Euler 1. See Generalized Project Euler 1: A sledgehammer to crack a nut. In this question I wanted to explore the next problem: Project Euler 2: Even Fibonacci numbers.
Even Fibonacci numbers
Each new term in the Fibonacci sequence is generated by a... |
I have created a simple Tic Tac Toe game using JavaScript and using jQuery. I have used bootstrap for the UI. I am just a beginner, so some feedback on the JavaScript element would be great.
$(document).ready(function(){
// true = player 1
// false = player 2
var pressedIndex;
var pressedElement;
var status... |
Below is a simple C++ abstraction over linux sockets, and a layer of abstraction over a synchronous poll call. The goal was to exploit move semantics to allow the Sockets to be used as value types.
socket.h
#pragma once
#include <cstdint>
#include <string>
class Socket {
public:
Socket(){}
virtual ~Socket();
... |
I am currently wondering if the following piece of Javascript code could be simplified? I would like to return the correct {},[],"" without having to pass a type as argument. Is it possible?
function getObjectProperty(object,field,type){
switch (type){
case "Array":
return object && object.hasOwnPrope... |
I need to ensure a method is executed only by one thread at a time. Contrary to what most of the synchronization primitives do, I don't need other threads to wait, I want them to return from the method immediately if it is already executed by another thread. Additional complexity is that the method uses async/await cal... |
I have made a generic pairing heap library in C. Pairing heaps are one of the several heap variants with better asymptotic running times than standard binary heaps (others include Fibonacci heaps and binomial heaps). However, pairing heaps are the only ones that really do better than binary heaps according to Wikiped... |
I am currently in the process of learning WPF Prism and I have four buttons that I want to all go to the same place but with a different value being passed depending on which button has been pressed.
Below is the code that I currently have.
ApplicationCommands.cs
public class ApplicationCommands
{
public static Co... |
I implemented a Python version of KMP followed by Princeton Prof Robert Sedgewick's discussion.
However, I got a Time Limit Exceeds error. Per leetcode's explanation, TLE indicates that the solution is correct but it is extremely inefficient when test case with huge input size.
If I understand TLE correctly, this means... |
A few days ago I found myself learning lolcode. It turns out it's (almost) a real language and capable of handling (pseudo-)serious problems. So, let's try some (pseudo-)serious code this time.
Project Euler 14
A Collatz sequence is defined for the set of positive integers:
n → n/2 (n is even)
n → 3n + 1 (n is odd)
Us... |
There are buttons on a page, each corresponding to a different code that needs to be sent to PubNub DSN, which is published to my home server to operate specific on/off commands for various lights in home. This is primarily a learning experience for now.
I currently have 4 basic buttons on page:
<section id="main" role... |
Problem:
In this problem I had to remove all vertices with degree one from a given graph in rounds and count how many rounds are required to remove all possible vertices with degree 1.
e.g. 1-2-3-4 Remove 1 and 4 in round 1. Remove 2 and 3 in round 2.
e.g. we can't Remove any vertex here. Total 0 rounds.
1---2
\ /
3... |
I have been using the w3 org's JavaScript Best Practices web page's examples for coding an object literal for a game.
It is my understanding that I should use this to keep all my variables and arrays that are not associated with/inside functions. I should then use methods to access and update the values and arrays.
I w... |
I'm working on a screen sharing project, and I receive a small block of images from a Socket constantly. I need to update them on a certain initial desktop bitmap I have.
After receiving every block, it copies its pixels according to a specific position (X and Y parameters), which is how the initial image gets updated.... |
Following on from my last question, I've been continuing to look at what information is available from the SE Data Explorer, I thought it would be interesting to know who else had favorited a question. Which led me to this query:
DECLARE @FavoriteType TINYINT = 5;
SELECT
Votes.UserId AS [User Link],
Vot... |
I wrote a simple JavaScript function to animate objects on my webpage to fade and slide in from the bottom of the screen when the user scrolls them into view. I did this by using JavaScript to add and remove a CSS class that animates the element to every element with the showOnScroll class.
Example element:
<content-c... |
bool isFileExist(const std::string& fileName)
{
return !!std::ifstream(fileName.c_str());
}
This is a function to check if a file exist. Are there non-obvious problems?
|
This is my sample code to convert a integer into string.
Is it very costly to do the multiple loops of [NSMutableString stringWithFormat:..]?
I.e should I just use appendString and get the NSString in reverse order and then do one for loop to reverse this "reverse string".
Is there any other faster/more elegant way?
NS... |
So this is part of my AVL tree implementation, namely the infix representation of the tree. Since I wanted to use a recursive method to stay close to the original algorithm and want to return a list, I have to store the values in a parameter.
The smelly part is in getInfix when I reference that parameter to return the ... |
A Junit test class is used to test the class LibraryCounter. Reflection was used to test the private methods. This made the code much more complicated.
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.junit.T... |
Thanks to this post, I was able to create a working piece of javascript that fits my needs. I have a div/ul/li based table where each "row" has 2 values that I want to have the sum for. Currently the code does exactly what I want, but somehow I have the feeling that the javascript is not coded in the most efficient way... |
This is my first actual python tool I've written and I'm certainly happy with the way it works, but I'm sure there's better ways to do things in the code. Any ideas on how to speed it up would also be nice too!
Code:
#!/usr/bin/python
import StringIO
import getopt
import hashlib
import sys
import os
print " "
print "P... |
I completed this problem for an interview and my solution as rejected; of course no reasons were provided.
I opted to use the nearest neighbour algo based on the timeframe allotted and having no indication of the average number of coordinates that will be fed to the function. I didn't want to use an exact solution tha... |
My code makes the four tests pass, but I'm worried I'm missing something. Is the code too simple and not encompassing enough? I'm just beginning to learn so any feedback is welcome!
Here's the Rspec followed by my code; notice there's no 1-100 requirement like on some other FizzBuzz challenges:
describe "fizzbuzz" do
... |
Background: I'm trying to learn C++ and I'm doing that by writing some programs by myself. I'm decent with C, but I'm having trouble translating to OOP paradigm. I'm reading from learncpp.com and a book called Thinking in C++.
I'm noticing that reading doesn't really help much as much as writing programs and running in... |
I don't know if it is any good. I've never done this, thus, I noticed it is kinda slow.
Can you suggest improvements? I may use it in actual software in the future.
private int secgen(int minvalue, int maxvalue)
{
Func<int, int, int, int> modular = (a, b, mod) =>
{
long rem;
... |
I would love some feedback on my linear finite state machine. I say linear, as it can only handle one state at a time.
I am also giving my method of how I -work- with the state machine, as I would love feedback on these bits also!
The things I wanted out of this, were:
to be able to add x states to the stack, and let ... |
How can the following code be made idiomatic in ELisp? Can the temporary f variable be removed?
(global-set-key [f3]
(lambda () (interactive)
(let ((f (ffap-file-at-point)))
(start-process "test" "output" "mpv" f))))
|
For an online screen, I had a question that would take in a vector of strings, and return a vector of strings indicating whether the input string was a valid combination of []{}(), where valid means the braces are matching and not interleaved. There are no empty string inputs.
For example, [(())] is valid, but ), {, an... |
Challenge
Write a program which reads a file containing Morse Code and outputs the conversion.
Specifications
The first argument is a path to a file.
The file contains multiple lines.
Each line is a string of morse code.
Each letter is separated by a space.
Each word is separated by two spaces.
Constraints
The... |
I'm implementing a function that behaves like getline() which reads a line from file descriptor and returns the results without \n. allowed functions, read(), free() and malloc. Please review my code.
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#ifndef GET_C_BUFF_SIZE
# define GET_C_BUFF_SIZE 1023
#endi... |
I've created a function to calculate the working minutes between two timestamps.
I class working minutes as those between 9am - 5pm and not on weekends or national holidays.
The holidays are those in the UK.
I think the function itself is quite quick, although generating the initial series probably takes a bit of time.... |
This is my first time building an Android app or even using Java in the first place. All of this code does work, but I'm hoping to optimize it or find out if things could be done more easily than how I've done them.
radio.java
package com.example.jacob.wutk;
import android.media.AudioManager;
import android.media.Medi... |
I wish to make a file to click on to do the 'usual' tasks I would do to clean/perform maintenance on my mother's computer when I'm not present. I made a script file and took a few command lines from Google. Am I on the right path?
<job>
<script language="VBScript">
Option Explicit
On Error Resume Next
Dim WshShell
Di... |
I'm new to HTML and programming in general and I want to make sure my code is organized and that I'm using the best practices while I go along.
So, I made this example layout I would like to convert to HTML5:
And this is the HTML5 code I created:
<!-- Solutions Section -->
<section id="Solutions">
<header>
<h1>T... |
def bfs(graph, root):
visited, queue = [], [root]
while queue:
vertex = queue.pop(0)
for w in graph[vertex]:
if w not in visited:
visited.append(w)
queue.append(w)
graph = {0: [1, 2], 1: [2], 2: []}
bfs(graph, 0)
Does this look like a correct impleme... |
I asked similar question at: https://stackoverflow.com/questions/38410982/superfast-regexmatch-in-large-text-file
from datetime import datetime
startTime = datetime.now()
f = open('data.txt', 'r')
t = f.read().splitlines()
paid = list(set(t))
with open('f.txt') as f:
for line in f:
for x in paid:
... |
I am using the below function for converting the accented character to a standard ASCII user name.
function transliterateString($txt) {
$transliterationTable = array('á' => 'a', 'Á' => 'A', 'à' => 'a', 'À' => 'A', 'ă' => 'a', 'Ă' => 'A', 'â' => 'a', 'Â' => 'A', 'å' => 'a', 'Å' => 'A', 'ã' => 'a', 'Ã' => 'A', 'ą' => 'a'... |
I'm creating a simple android app for pre-highschool students which teaches the very basics of addition or multiplication of integers or decimals.
The part of the program in this question is aimed at allowing them to practice without the need of a teacher giving them exercises and checking their results.
Note: This is ... |
I have this below Data Structure.
The output will be like
m - n - o - p - q - r - s -t
Please review the below code and let me know if any optimization can be done.
public class Application {
public static Node root = null;
public static Node temp = root;
public static Node anotherTemp;
public stat... |
I have code that loading bitmap from file. And searching for black rectangle(5*5). Can you help me to review it?
namespace TakeScreen
{
class Program
{
static void Main(string[] args)
{
List<List<Color>> Sequence = new List<List<Color>>();
for (int i = 0; i < 5; i++)
... |
Following on from my program to identify files that have common file sizes, I have developed an application that takes the output from that process and then compares each of the files that are the same size in order to identify duplicates which are then written to a '.matched' output file in the form <FullPathFile>|<Fu... |
I've written a new malloc implementation similar to dlmalloc and was hoping for feedback on it.
The goals for this library are:
Easy to read and maintain
Be more memory conserving
High efficiency and good performance
Portability
The documentation is here and the code could be found here.
/********************** mallo... |
I have written several subs which are then called from a main sub. Individual subs run very quickly, most are instantaneous (the DoFind sub takes a few seconds to run due to the large amounts of data in the table) however when I run the main sub it takes up to a minute to execute. Any ideas/tips on why this is the case... |
In order to test some software I've written, I need to write values to a test harness with OLE for Process Control (OPC). The problem is, for a larger range of values I'm generating points for (say 10000), this code can take 15 seconds to execute. I need it to work in under 1 second.
import OpenOPC
import argparse
im... |
I want to enter names, student numbers and student scores and display this information. I used arrays in this way:
#include "stdafx.h"
#include <iostream>
#include <string>
#define size 3
using namespace std;
class student{
public:
void vrod();
void dis();
int stno,score,i,n;
};
void student::vrod(){
cout<<... |
I wrote a bot for a Programming Puzzles & Code Gold King of the Hill type of challenge called "Spacewar!". The challenge was written by @El'endiaStarman. The bot is called "Spy".
The controller is hosted here, so take a look for the feel. The API is a bit long, so here's a link.
The bot's logic:
It runs away from the... |
I have the following piece of code which hides an element when a specified date was reached. I would like to get some tips about do's and don'ts.
Specifically, I'm interested in:
improvements brought to this code
avoid bad practices
And whatever you guys consider I should be careful about.
var Timer = (function(){
... |
I have this SELECT statement that inserts into a temp table and it is slow! Right now it takes ~1500 ms to run and only deals with ~7000 rows. As the data grows larger the longer it will take.
I am using SQL server 2014.
Is there anyway to improve performance of all these case and casts in the statement?
select a.... |
Iron's cookie and session middleware projects seem to be abandoned. I've put together implementations for them, along with a session flash provider. They seem to be working fine. They are all very small, so I'll paste them in their entirety below (each file is linked to a Github repo and each repository also contains a... |
I learned Bash a million years ago. I just wrote this simple script used to get the first lot of HTML comments from a file, and spit it out in order to create a README.md file.
It is just. So. Ugly. I read bits and pieces over the years, and I am sure it can be improved so much...
Here we go:
#!/bin/bash
IFS=''
active... |
I have this piece of Ruby code:
HTTPCLIENT = HTTPClient.new
def read_page(url)
HTTPCLIENT.get(url).body
end
The HTTPClient object is being created and declared as a constant, and thus it can be accessible by methods.
I would do this by declaring it as a global variable ($) or as a class variable (@), but I'm not su... |
I am trying to get active directory groups with their users, all while disposing of all IDisposable assets when they reach the end of their usefulness. The groups and users are passed into a method that extracts certain properties and adds them to ExpandoObjects. This requires a decent number of nested using blocks.
Si... |
As I stated in an answer comment on my previous question, the UserIterator has a much larger footprint than I think most people realize. This question is here to further explain the project, the UserIterator's role, and what I'm trying to achieve with this specific piece of the code.
If any of you have had experience w... |
My site was recently infected and running malicious scripts. Once I discovered this, I cleared everything, the hosting company re-initialized the VPS and I setup my site anew. This is how I run my PHP scripts currently. I have two objectives:
To keep my scripts from being directly accessible from the web
To never run ... |
This is the first real program I've written in Go so have at it! I wrote it because I use a tiling window manager that doesn't have any brightness control functionality (at least not that I know of).
package main
import (
"fmt"
"io/ioutil"
"log"
"net/http"
"strconv"
"strings"
"os"
)
func m... |
I recently asked for some feedback on my design for a syncronous wrapper around linux sockets and poll
Based on the feedback, I created a new (hopefully more idiomatic) design.
socket.h
#pragma once
#include <cstdint>
#include <string>
class Socket {
public:
Socket(){}
virtual ~Socket();
Socket(Socket &&o... |
This code (an implementation of the path finding Needleman-Wunsch algorithm), given two sequences, correctly aligns and calculates the similarity of them. For example, given two sequences:
AAA,CCC
or
AA,CA
it correctly aligns them as
---AAA
CCC---
and
-AA
CA-
respectively, while returning the similarity.
%... |
Having some trouble with a code I'm trying to refactor, where I need to go over a 'tree' of items, filter some invalid items, and create a new array of filtered items which takes properties from both parent and child objects.
To demo the problem I made a quick snippet -
const items = [
{
name: 'Shirley Hardin',
... |
I am working on a program that would generate swift classes/ structures for JSON file contents.
The link to the application is Json2Model in case you want to contribute directly.
I do not know a lot of Swift but this is what I came up with. These classes most likely will not hold any logic they are just data.
input.js... |
I made this program to find primes and twin pairs. I'd like feedback on anything from formatting to content to technique. In short: how would this be different if it was written by an experienced professional?
The program runs five methods:
getMax asks for an integer input which is the maximum number below which to fi... |
I am working with some wireless communication in Arduino. My data will be wirelessly received like so:
97
97
97
...
...
979797 is the address of the transmitter. I have written the following code to check the address first before processing the data. My main concern is speed of computation.
void printBuffer(const uin... |
Looking for suggestions on how to unit test a Spark transformation with ScalaTest. The test class generates a DataFrame from static data and passes it to a transformation, then makes assertion on the passing static data generated in the test class. (The transform creates a second column b defined as col("a").plus(5).... |
I've created a little hangman game. It's pretty simple, and not to exciting but I want to know if there's a way I could turn this little game into something more extravagant and more exciting. How can I take this delicate piece of crap machinery into something a little more fun and a bit more complicated? For example:
... |
Challenge
This is a solution of Project Euler 72 in Java.
How may proper reduced fractions \$\dfrac{n}{d}\$ are there, where \$n
< d \le 10^6\$?
Code
public long solve() {
int limit = 1000000;
int[] phi = IntStream.range(0, limit + 1).toArray();
long result = 0;
for (int i = 2; i <= limit; i++) {
if (ph... |
This week, in an ongoing job search, I was tasked with the following pre-screening question:
Make two simultaneous http requests. Use the language and library of your choice. Make sure the results are combined and resolve into a single return.
For this I chose JavaScript and jQuery, culminating in the following Gist ... |
I had a silly assignment:
You are given a binary file FLOATS.DAT of unknown length, type float
data has been written in it. Write a program which sorts the data in
the file (the output is a sorted file FLOATS.DAT). You need to sort it
without loading the file into memory, or by using a temporary file.
Use the ... |
I want to print a tree in a zigzag manner level-by-level. I'm wondering if there are any logic issues in my code and any further performance improvement ideas by using a smarter algorithm implementation.
class Node:
def __init__(self, value):
self.value = value
self.left = None
... |
My goal is to read from standard input, break up the input into words (Unicode letters and apostrophes), case-insensitively, and produce a report to standard output, where each line is a word followed by a space followed by its count. The output should be sorted by words.
This is my code:
using System;
using System.Tex... |
I have a to write a simple utility function that given a time in CST and a date in PST, tells if the date is today and if the current time is less than the cutoff (post converting cutoff to PST).
This is my attempt (highly childish but I seriously don't get Java date-time at all). If anyone could help me improve this c... |
I have a program which finds, well, a magic square of squares. The problem is, it's quite slow - it processes around 50 numbers in half a second when the number range is above 40,000.
Is there any way to improve this code?
from math import floor
# checksquare checks for the possibility of a set being a magic square.
... |
Sorry if it's a bit long... I tried to make it modular with methods, not sure if I overcomplicated it
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Learning
{
class Program
{
public static decimal principal;
public ... |
My teammate and I have a small discussion about the responsibility of a method. He thinks next method has two responsibilities and I think that only one.
private boolean validateUsername(String username) {
AccountValidationResult validationResult =
mAccountValidator.validate(username, new int[]{Account... |
Originally created for this answer on SO, I thought there was still room for improvement on the initial basic idea.
Also thought about using an extension method to make using syntax simpler.
Here is an updated version of the dynamic object wrapper. refined for this answer
public static class DynamicObjectWrapperExtensi... |
I'm trying to learn how to write better, more efficient JavaScript code and wanted to run this function I'd written by you and see if people can suggest an improved method.
It's basically a people filter based upon two variables.
Demo.
It works fine, but if additional categories come in (so far there are three) then th... |
I have a program that:
Takes a user specified string
Creates password from the string and previous, current, and next day
Encrypts the strings
Chops some middle characters from the strings (needed to be shorter password)
Returns a JSON object with 3 passwords
My main concern is that everything is almost repeated 3 ti... |
Inspired by my question
Simulating a random packet routing algorithm and printing packet statistics in Java
I decided to implement two more packet routing algorithms:
one that computes all the shortest paths in the network and routes each packet via a shortest path between the packet and its destination. The second al... |
I'm solving easy CodeEval challenges in Python 2.7. Usually my solutions use around 256 bytes of memory according to CodeEval. With Road Trip however while time used is still low (30-40ms), memory is >5881866 bytes. As I'm somewhat of a beginner, is there an easy way to decrease memory usage?
For each test case, which... |
After reading this old article from 2001 I have tried to implement the class from it using unique_pointer.
An author's claim is that C++ is not appropriate for large software projects because
My primary complaint against C++ is that the language is so complicated, and has enough booby-traps, that average and above-a... |
I made a simple assembly program to count the number of ones in a register. Since this is basically my first ever, I would like to hear what I can improve or if there are some major flaws in this one:
#PURPOSE: Simple program which counts the number of ones in the edx register and returns them as a status code
#INPUT... |
I wrote the code below to generate Code 128 barcodes, based on the specs.
Public Class UcBarCode 'Inherits UserControl
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
PictureBox1.Image = C128bmp("Teste123")
WebBrowser1.DocumentText = String.Format("<html><body><i... |
I recently started learning C++ about a week ago, and I made a bit of progress. In honor of Pokemon Go releasing, I decided to make a Pokedex with the original 151 Pokemon. So far I have 120 or so of them in there and it works PERFECTLY! (Thank goodness). I believe my code could be much more efficient and work better. ... |
Recently I have been busy with nodejs and I thought to create something like this Java input library, so I started with some rough code like below:
'use strict';
const readline = require('readline');
const fs = require('fs');
class StdIn {
constructor(opt_name) {
this.name = opt_name;
this.rs = this.name ? f... |
I'm working with an open-source library for processing and parsing genetic data in VCF and Tabix formats. It contains functions and classes that make it easy to read an index file (a Tabix) and load corresponding data from a compressed VCF.
It works asynchronously (unsurprisingly), however, and I'm not sure of the bes... |
This program is a practise exercise in using instance methods, and also in recursion which I struggle to get my head around. I want to know how my technique for the recursion could be improved, and if there's anything else which could be made more efficient.
The program creates a Rational object type (a fraction) which... |
This takes a field delimited by commas, and splits on the comma. The newly divided information is put in another field (created at the start of the program) called lob. Each part of the split is put in the lob field in a duplicate record of the original record from before the split. The primary key is ID which is au... |
This is the first version of my first HTML5 game. Beyond the standard features, I've added a high scores board which uses local storage to keep track of the scores.
You can move the snake with the arrow keys. Unlike the normal game, running into the wall doesn't kill the snake, only when it runs into itself. This will... |
As part of a (slightly) larger program, I needed to write a function that could take an arbitrarily large number and divide it by a small number. In this program, I will be dividing this number specifically by 2 or 5, but from my (rudimentary) testing, my function seems to work for larger divisors as well. All of the i... |
I'm creating a town plugin for the game Minecraft using the Bukkit API. It works fine and all, however I'm not satisfied with the quality of the code and I'd like to know how I can improve. I've been programming in Java for about a year and a half now, any advice is appreciated.
I have a few concerns
I'm not sure if I... |
I have the following function, and I have a hunch it can be written more concisely in Ruby.
def template_params
filtered_params = params[:template].permit!
filtered_params[:published] ||= false
filtered_params
end
The end result is that filtered_params has published: false if the params hash doesn't have publish... |
Would the following be the right way to do it in your opinion? Can you suggest a better alternative or, if not, is there something that can be done to make the existing version better?
ps -e | grep skype | cut -d" " -f1 | xargs kill -s term
|
Consider a .csv file that contains a set of video names like so:
"There are happy days","1204923"
"Beware of ignorance","589636"
"Bloody Halls MV","258933"
"Dream Theater - As I Am - Live in...","89526"
The intent of the code I built is to filter items in the csv depending on the list of excluded items. Therefore, if ... |
I'm looking for some improvements for my generic Roulette class. More information on how the class works is better described, here: https://en.m.wikipedia.org/wiki/Fitness_proportionate_selection
public class Roulette<T>
{
public string Name;
private Dictionary<T, double> _items;
/// <summary>
/// Cal... |
There are a lot similar questions out there. However, I wanted to get comments on my code. My implementation (as I believe) is simpler than the other complex ones as mine is \$O(n^2)\$.
My approach is simple:
Start with the biggest size of string
Check that string if its palindrome
Reduce the string size by 1 and chec... |
I want to upload a user's location to a server to send them a location-sensitive alert, so the location needs to be fairly accurate:
import Foundation
import CoreLocation
protocol LocationServiceDelegate {
func tracingLocation(currentLocation: CLLocation)
func tracingLocationDidFailWithError(error: NSError)
} ... |
This trait is meant to be a simple interface for tabular data from different file types, such as csv, excel, open office etc. Right now I'm only asking about some of the top level code for now and not the implementations. I'm worried that I might have made some poor design choices. But first let's get some type alia... |
I have created a utility to create scrolling parallax backgrounds.
// Backgrounds as array of objects. canvas id, speed, image url
var bgs = [{
id: 'sky',
speed: 1,
src: 'https://upload.wikimedia.org/wikipedia/commons/9/9f/Sky_back_layer.png'
}, {
id: 'middle',
speed: 3,
src: 'https://upload.wikimedia.org/w... |
Using Java 1.8, I created the following implementation to concat two int arrays:
public static int[] concat(int[] array1, int[] array2) {
return IntStream.concat(Arrays.stream(array1), Arrays.stream(array2)).toArray();
}
The unit test I created to test this looks like this:
int[] numbers1 = new int[] {1, 4, 3, 10,... |
Created the following method:
public static int max(int[] array) {
int max = Integer.MIN_VALUE;
for (int value : array) {
if (value > max) {
max = value;
}
}
return max;
}
Question(s):
I believe the Big O Notation for this implementation is O(n), am I right?
Since this is ... |
I solved bubble sort in an exam, but the examiner wasn't satisfied with the solution. Please tell me why my solution is unsatisfactory.
function bubbleSort(myArray){
var temp = undefined,isSwap = false;
for(var x = 0; x < myArray.length; x++){
if(((x+1) <= (myArray.length - 1)) && myArray[x] > myArray[x+1]){
... |
I have some code that filters an array with type (Suggestion|undefined)[] into an array with type Suggestion[], but I feel it does so very inelegantly:
const optionsProvider: AutocompletionProvider = () => {
const results: (Suggestion|undefined)[] = flagDescriptions.map(descriptions => {
let shortFlagWithAr... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.