instruction
stringlengths
71
71.9k
The method is in a new class and i use it from form1: In the top of the new class: public int numberOfPoints = 100; The class Init method: public void Init() { if (IsEmpty(bmpWithPoints) == true) { bmpWithPoints = GetBitmapWithEllipses(1.0f); } } Then the method: private Bitmap GetBitmapWithEllips...
This is the new code after the changes suggested by @Cody Gray in the last question: Calculate area and perimeter for shapes: polygon, circle, rectangle and triangle This is my project on inheritance and polymorphism. I got the main file from my teacher and built the project base on it. My base class is Shape. Polygon ...
I implemented the well-known knapsack problem and now I would like to improve it using list comprehension or lambda. I don't want to use NumPy. Could you help me? def get_optimal_value(capacity, weights, values): value = 0. numItems = len(values) valuePerWeight = sorted([[values[i] / weights[i], weights[i]]...
Am using the datasource which is from the MVC controller method "GetRepairIssues" in the client side to bind the options to the dropdownlist. The result comes as expected. I have to do it even better and optimistic. public JsonResult GetRepairIssues() { JsonResult result = null; try { var repairIss...
Description: Given a reference to the head of a doubly-linked list and an integer, create a new Node object having data value and insert it into a sorted linked list. Code: Node SortedInsert(Node head, int data) { Node current = head; Node previous = null; while (current != null && current.data < d...
The Controller code for the first app to post data to another app module Api module V1 class OrderApiController < ApiController def send_invoice_data response = Hash.new result = Hash.new debugger order = Order.includes(:status, :user, payment: [:status]).where(txnid: par...
I need to implement dijkstra's algorithm and I've done so using this Wikipedia page. I've done it both with priority queue and without. Both versions work 100% correct, however I need the faster one (priority queue one). The problem is that it isn't faster. My tests show "faster" one runs in more than double the time ...
I needed to write a simple function that could raise a value x to the n'th power. I found out I could write this function in 2 different ways: (defun power1 (x n) "Raise x to the n'th power" (cond ((zerop n) 1.0) ((< n 0.0) (/ 1.0 (reduce #'* (loop for i below (- n) collect x)))) ...
I have some Python code that generates all possible multiples and combinations of a given set of primes up to a certain limit. The code runs and does exactly what I intend it to do, now I am trying to optimize it in order to improve run-time. import math from collections import defaultdict import itertools lim = 10**1...
I've written a piece of chess software which does some validation checks (check, checkmate etc). I've not implemented some of the more exotic Chess moves (e.g. rooking, en passant, promotion). I've written the code for a platform where the STL is not available. Thus, std::vectorhas been deliberately avoided (I'm aware ...
I created small simple PHP Authentication API. I have a couple of scripts that I use for session, authentication and registration. Since I'm not an experienced backend and PHP developer, I wanted someone more experienced to review my scripts and tell me what I did wrong and what I can improve. I did not use any framewo...
I want to implement jquery.alphanumeric in HTML pattern, so I used a jQuery plugin from here. Can this be shortened or improved? <input type="text" char-allow="$#*" class="alpha"> <input type="text" char-allow="+-" class="numeric"> <input type="text" char-allow="&" class="alphanumeric"> <script> function setAlphaN...
I've made a memory test game in windows forms, where you need to find and match 2 cards with the same images. It has 3 difficulties : Easy - 4 different pairs of cards, no time limit, no mistakes limit. Medium - 8 different pairs of cards, no time limit, 8 mistakes limit. Hard - 16 different pairs of cards, 30 seconds...
I'm looking for a general review with emphasis on idiomaticness and error handling. extern crate byteorder; extern crate rand; use std::collections::hash_map::HashMap; use std::collections::BinaryHeap; use byteorder::{ReadBytesExt, WriteBytesExt, NativeEndian}; use std::{fmt, error, result, io, path, cmp, fs}; use st...
I have a worksheet that lists a person's name (column A; many duplicate names are in this column) with associated data (columns B through G). I have code below that takes this list of a ~ 1000 rows and then: Copies and pastes each row three times (to create four identical rows for each entry). Loops through the now ~4...
Unfortunately, my earlier question was put on hold due to "code that doesn't work", but I realised that there were holes in my question, so here it is again, revamped. You probably know the QuickSort algorithm, where you select a pivot and place elements lower than it on one side, and those bigger than it on the other....
I want to make the creation of the pack Uri for WPF resources more verbose so they are easier to read and less error-prone and I thought I implement it using the builder pattern. The base class for each builder (there are four of them) is the PackUriBuilder. It implements the UriKind logic, checks the path and requrie...
I've been on an adventure trying to learn NodeJs and put together a stack that I'd be happy to put into production if one day my team said to me "Let's build it in Node!". What we have here is your standard "Todo Webservice". Any and all feedback is appreciated, because I had never written more than 10 lines of JS prio...
I made a string class to be used as a replacement for std::string. It has all the find functions (find, rfind, find_first_of, ...), basic iterators (just begin and end, no reverse iterators), almost all the operators (+, +=, ==, [], <<), an insert, erase and substring function, c_str(), and it is dynamic. It is mostly ...
I tried to write some code namely "Circular doubly linked list" and I would like to use templates to do this. This is the first time I use templates and throws some exceptions. I would like to know if sth is badly writen, sth must be changed or I need to rewrite everything. Last but not least, what is the best framewor...
I am having a problem with my program: it does as required but largest_blanagram() is too slow. I'm not sure whether the best way to speed it up is (1) try to speed up blanagram(), which is being called a lot (2) figure out a way to call blanagram() less. I'm not sure how to go about either of these things particularly...
I have a system that can put and get messages from a messaging middleware (JMS), which is asynchronous. I need to provide an API that allows synchronous call, as in, when the API/method is called, it returns only when a response message is received or until a specified time out. In short, the calling thread needs to wa...
I made a Monte Carlo pi approximation program, that makes use of multithreading and a pseudorandom number generator I wrote (the one from big_wheel.hpp, which I tested using TestU01). Code: monte_carlo_pi.cpp: #include <iostream> #include <iomanip> #include <cstdlib> #include <cstdint> #include <cmath> #include <thread...
I am trying to do a self-join. I generated this migration to make a correct primary. This code works, but I'm not sure if this is the best way to do things. class CreateFeedstocks < ActiveRecord::Migration[5.0] def change create_table :feedstocks do |t| t.string :code t.float :measure_one t.fl...
The F# code below embodies the two specific questions I have. It is part of a working transformation utility, the entirety of which, including sample data, is in this gist: http://bit.ly/2i3kUwF. Generically, the task is: given a file of discrete records, compute a value for a subsequent record that depends on a value...
I was re-checking my answers for a Math paper on my laptop. I needed to verify my solution for a system of linear equations. Unfortunately, I found no quick way to do that. That's why I wrote a (hopefully) simple Python program (using NumPy) to do this job quickly. General comments on the code are appreciated. linearso...
I have written this code to invert a binary tree. Thus if the original tree is: Then the tree returned should be: /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class S...
I have coded a working Tic Tac Toe game tree generator. It doesn't only generate the game tree, it also applies minimax values to each node. The code works fine on a board that already has 2 or more played moves but slows down significantly for an empty board. I'm thinking of implementing alpha-beta pruning. I am, howe...
My method for sending emails with Send() is getting very slow when I send more than ten messages. Sample 1 (1 sec) 2 (2 sec) 3 (4 sec) 4 (8 sec) and so on... so I started to try SendAsync() public Boolean sendSMTPMail(string subject, string body, customer[] recipients, string attachmentFileName = null) { string c...
I am fairly new to programming and even newer to C++ but I am currently in a class for scientific computing, and our task from two weeks ago was to improve the speed of a primality test program. I regrettably do not have the original code because I wrote over it, but the long and short was that program selects 100,000 ...
Problem Write an algorithm to determine if all of the delimiters in an expression are matched and closed. {(abc)22}[14(xyz)2] should pass [ { ] } should fail { (x) } [ should fail Any advice of code functional bug, performance in terms of algorithm time complexity, code style are appreciated. delimiters = ['[', ']', ...
I wrote a Java program implementing Resenblatt’s perceptron Single Layer Network, Least Mean Square algorithm for Single Layer Network and Back-propagation algorithm (MLP) Network. I'm trying to write efficient and clean code. NeuralNetwork class package fcis.asu.neural; import java.util.Map; import lombok.Getter; im...
This is a simple implementation of Connect four in Java. It is working correctly so far. What I haven't done yet are the diagonals check and input validation. package game; import java.util.Scanner; //TODO check for diagonals, input validation public class Game { private char[][] gameBoard; private State gam...
There's a server which does the following: Receive request with transaction id Load corresponding transaction from storage. New transaction object is returned each time Process transaction Save updated transaction back to storage The task is to properly synchronize steps 2, 3 and 4. Since for each request new instanc...
The problem is old and simple but I wanted to try it in a different way. With some extra memory I have created an OOP-based solution. Hopefully it doesn't hurt in the interview. import java.util.*; import java.lang.*; import java.io.*; class Main { static class Solution { private int[] items; private List<In...
Given an integer, check if it's the power of two. class Main { static class Solution { private final boolean answer; Solution(int num) { if (num <= 0) { answer = false; } else if ((num & (num - 1)) == 0) { answer = true; } else { answer = false; }...
I've been working on another builder, this time for the DependencyProperty because it's object-based. This means that every parameter is an object and thus their usage is inconvenient (requires casting). In my experiment I tried to make its creation easier and at the same time generic. This is what it looks like. The...
few days ago i made small PHP Authentication API with all basic functionalities (log in, log out, registration, getting authenticated member) and i got suggestions that i should use prepared statements for better performance and SQL Injection defense, so i made some changes to my script and it looks like this, can anyo...
I wrote a script which retrieves YouTube videos from your favourite channels - channels you specify in a .txt file. Let me know what you think about it. Channel and Video classes import urllib.request import json import re from datetime import datetime, timedelta #************** apiKey = #Insert your Youtube API key. ...
I wrote a little program in C# that contains classes representing Items in RPG game. I wanted to have access to all inherited classes parameters from list contains parent Item class instances, so this is my code: using System; using System.Collections.Generic; public interface SpecialObject { int GetIntParameter ...
I wrote a method for validating properties based on passed conditions. It works well, but declaration takes more space than the actual condition. Is there any way to make it shorter? public virtual string Validate(string propertyName, params Tuple<Expression<Func<bool>>, string>[] predicates) { if (!ValidationPrope...
I recently wrote this C++ Logger API code for a game engine. It needs to be as fast as possible so I tried to postpone everything to compile-time using different template meta-programming tricks (for instance, static_if). Any advice, bug fixes or suggestions are welcome. Log.h: // Copyright(c) Matyas Yves Constans 2016...
I wrote a Java program that given a text message will print the encoded message. The problem is described in this link. Summary: We have to write a program that will encrypt a message that do not contain space character. Assuming that \$L\$ is the length of the message we have to put characters of this string in matri...
I've made 2 object pooling classes - MonoObjectPooler : MonoBehaviour - can hold a single bucket of pooled objects of 1 type. PolyObjectPooler : MonoBehaviour - can hold multiple buckets of pooled objects of different types. The object to pool information is store in a class PooledObject /// <summary> /// Information...
Elements of a matrix are given in sorted rows and columns. I want to find the element in an optimized way. First, I will get the last element of a row, which will determine if a number can exist in the current row. If the number I want to search for is greater than the last row's element, there is no point is searching...
In chess it is possible to place eight queens on the board so that no one queen can be taken by any other. Write a program that will determine all such possible arrangements for eight queens given the initial position of one of the queens. Input The first line of the input contains the number of datasets, and it...
I've been working on generating primes and prime products quickly to aid me in my research on prime numbers, their density, etc. The answer to my Large Number Limit Extravaganza question proved to be extremely useful in writing my programs. I have now expanded on this program to look at the difference in the amount of ...
I wrote this simple linked list in JavaScript. Feedback is welcome. function Node(data) { this.next = null; this.data = data; } function LinkedList() { this.length = 0; this.head = null; // add node with given value to the list. this.add = function (value) { var node = new Node(val...
The code loops to display "Hello, World!" ten times. I would like someone to criticize it. I know that's far from being good assembly but I only started learning it a few days ago and I would like to improve. Would it be better to use the %rax registers and syscall instead of int $0x80 ? .section .data hello: .string...
I need a collection/bag (something) that will hold some maximum number of running Task objects. Adding a new running Task to the collection should block the calling thread (there are many threads trying to add a task so it should be thread safe) until there is an available slot for the new Task to be added if the maxim...
Here is my simple program to pretty print a JSON object. I'm looking for advice of better pretty print solutions, functional bugs, code style and algorithm time/space complexity improvements. BTW, I have fixed all PEP8 issues I met with using Pycharm auto-annotation feature, there are some alerts on PEP8 which I think ...
I've made the Simon says game in Unity You start by guessing a pattern of 3 colors and each time you complete the pattern a new, random one, is generated and the length of the pattern is incremented by 1. The game utilises a custom generic collection I wrote CircularListNavigator<T>. I also have a question about it h...
This code provides a Tree abstraction. I would like to finalize the code structure only in tree directory, before starting implementation, because there are multiple conditional compilations, written at the function level. User code (testing) is yet to be attempted, as it is yet to fill the functions in Tree abstracti...
Fixed trade route with goods and prices and fixed cargo capacity. How can I optimize profit? No cost to trade or transport - just fixed capacity, route, and prices. All products use the same capacity, which is kind of artificial, but this is just a single pass starting with an empty vessel. It does a semi brute force o...
AN UPDATED VERSION with GitHub link is avalable HERE. I am trying to define a plug and play architecture which leverages stereotypical role implementations (Validator, Reader, Writer, Logger, Query, etc) by automatically instantiating associated services through a very limited use of Service Locator. Demo code: let's ...
I have been studying Java for 4 months and this project is what I came up with. I know I should make more classes and methods for quality but I am still learning. Please help to me if there is any simpler and cleaner ways to achieve the same results as this. import java.awt.FlowLayout; import javax.swing.JButton; impor...
What follows is a simplified version of a tentative implementation for a template-based set, named TemplateArgs. For the sake of clarity and focus on the question at hand, TemplateArgs was converted into a non-parameterized class, and its size and elements are hard-coded. It should be C++11-compliant and portable (any ...
There is backend which connects with IdentityServer using WsFederation. The backend is .NET Core project where there is a derived class from AuthenticationHandler. The issue is when the time of user's token is expired, the user should be signed out. I've implemented this in the following way: protected override async T...
Jesse loves cookies. He wants the sweetness of all his cookies to be greater than value K. To do this, Jesse repeatedly mixes two cookies with the least sweetness. He creates a special combined cookie with: sweetness = (1 * Least sweet cookie + 2 * 2nd least sweet cookie). He repeats this procedure until all the coo...
I have to implement a double linked list as an exercise for a further education. There are three interfaces which have to be implemented: IValueElement package schnittstellen; // schnittstellen == interfaces public interface IValueElement { public String getName(); public void setName (String paramName); p...
what do you think about this code? It's upgraded version of: Classes representing items in an RPG game using System; using System.Collections.Generic; public class Item { public string Name { get; protected set; } public int Cost { get; protected set; } public override string ToString() { ret...
This is a follow-up question to this one: AT&T Assembly - Basic loop & write The code loops to display "Hello, World!" ten times. I implemented the syscall instead of int $0x80, used a decrementing loop to avoid a useless instruction and commented the code. Is there any way to make it better? When debugging with GDB, i...
I have written a small function that will check a string to see if it contains a certain word. Depending on the word that is found first, the function will return the correct Enum value that needs to be used further down the line of the program. Would there be a better way to check a string to see if it contains a cert...
I've made a simple snake game in Unity and it has 3 different types of foods. Note - 5 blocks = 1 point This is a screenshot from the game here I'm colliding with myself and the game is restarted after that. As you can see the snake has a highlighted head (the light green block) and it consists of quite a lot smaller ...
Recently I implemented the Python's range() function in JavaScript. The function has three parameters: start, stop and step. The range includes elements from start and up to, but not including stop. The step parameter defaults to 1 and specifies the distance between two elements. It uses Proxy (an ECMAScript 6 feature)...
Inspired by Project Euler 14: Longest Collatz Sequence "Which starting number, under one million, produces the longest Collatz Sequence chain?" I wrote the following Java code: public static void main (String[] args) { int max = 0; int num = 0; int result = 0; List<Integer> num_array = new ArrayList<I...
Is it possible to improve this program somehow? It will probably be more convenient to suggest edits as forks of this Gist. (defpackage heart (:use :cl)) (in-package :heart) ;; Usage: ;; sbcl -l heart.lisp -e '(uiop:quit 0)' ;; (defun print-line (&rest args) (loop :for type :in args :by #'cddr :for num ...
I'm trying to cleanly grab some fields I need from an object. The scenario is this: I've got an object that is stored with certain 'extra' properties that exist because of the way we've set up our store in Redux. It'll look something like this: var formData = { account_name: 'SomeAccountName', custom_domain_name:...
Is there any legroom left for optimization (without switching to C)? static byte[] generateSound(double frequency, int sampleRate, int samples) { byte output[] = new byte[2 * samples]; int idx = 0; double _tone = 2 * Math.PI / (sampleRate / frequency); for (int i = 0; i < samples; ++i) { doub...
Is the following procedure good for shuffling data in general (not just for JavaScript)? function Shuffle(array) { var temp = null, len = array.length - 1, rnd = null; for (var i = len; i > 0; i--) { // Generate a random number in which does not exceeds the length of array. rnd = Math.floor(Math.r...
I've made a program to find the missing element (if there's one) in a sequential list: Program criteria: Returns -1 if a list is sequential, otherwise the missing element in a non-sequential list is returned. To perform binary search, we need a key to half the problem size. Here the key is to find the distance between...
I am implementing finite field arithmetic for some research purposes in C++. The field of order v, when a prime (and not a prime power), is just modular arithmetic modulo v. Otherwise, v could be a prime power, where the arithmetic is not straightforward. For simplicity, assume that files that contain the multiplicatio...
I've made code that scores each letter in a word you input according to the table below: 1: AEILNORSTU 2: DG 3: BCMP 4: FHVWY 5: K 8: JX 10: QZ I appreciate any feedback, but the main reason of this post concerns the charPoint method. Should I rewrite this using switch? Or is there an even better way to...
Any thoughts? print('*'*44+'\n****How Many Seconds Have You Been Alive****\n'+'*'*44) while True: try: print('\n--------------------------------------------') Age = int(input('\nHow old are you?: ')) if Age<1 or Age>90: print('(Input Error)*Enter Valid Age*') contin...
Inspired by this question I wrote a memoized form of the collatz sequence calculator. The idea was to cache the sequence lengths for as many sequences as possible, from 0 to some value. I managed to (on my PC) get that value up to 1427500000, which is a large number. I ran this particular calculator and it eventually c...
Is this an efficient way to compute the value of Pi, where the limit of j \$\propto\$ accuracy? PI = 0; for (var j = 1; j < 100; j+=2) PI += (4/j)*((j+1)%4?1:-1); The formula I used to write this is: $$\pi \equiv \frac{4}{1}-\frac{4}{3}+\frac{4}{5}-\frac{4}{7}+\cdots$$
How can I make my code better? function generateRandNum(min, max) { minimum = Math.ceil(min); maximum = Math.floor(max); return Math.floor(Math.random() * (maximum - minimum)) + minimum; } function generateNewPost(json_data) { var rand_num = generateRandNum(0, json_data.length); console.log("gener...
I was trying to write some simple data structures to practice ownership concepts in Rust: type Link<T> = Option<Box<Node<T>>>; struct Node<T> { elem: T, next: Link<T>, } struct List<T> { head: Link<T>, } pub struct Iter<'a, T: 'a> { next: Option<&'a Node<T>>, } impl<T> List<T> { pub fn new() -> ...
Here is my code for this problem. Any bugs, performance in terms of algorithm time complexity, code style advice are appreciated. This is a continued discussion from (Find smallest subset prefixes) and since it is new code, I post a new thread. Problem: Given a set of strings, return the smallest subset that contains ...
Online challenge on Hacker Rank. Problem Description Alice wrote a sequence of words in CamelCase as a string of letters, S , having the following properties: It is a concatenation of one or more words consisting of English letters. All letters in the first word are lowercase. For each of the subsequent words, t...
Problem statement Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero. Note: The solution set must not contain duplicate triplets. For example, given array S = [-1, 0, 1, 2, -1, -4], a solution set is: [ [-1,...
Online challenge on Hacker Rank. Problem Statement Steve has a string, S, consisting of n lowercase English alphabetic >letters. In one operation, he can delete any pair of adjacent letters with same >value. For example, string "aabcc" would become either "aab" or "bcc" >after operation. Steve wants to reduce as much...
Problem statement Professor GukiZ has hobby — constructing different arrays. His best student, Nenad, gave him the following task that he just can't manage to solve: Construct an \$n\$-element array, \$A\$, where the sum of all elements is equal to \$s\$ and the sum of absolute differences between each pair of...
This is my second attempt to create a strongly typed builder for the Dependency Property. I've improved the two main weaknesses of the previous version which were: Can specify only PropertyMatadata but not FrameworkPropertyMetadata Can coerce value but not cancel the operation with DependencyProperty.UnsetValue The ...
Please review my code for printing a Christmas Tree. The idea was to merge some functional programming ideas (immutability, streams) and OOP (every thing is a small object). I'm looking for a review focused on readability of the code. Here is a output from the code: * *** ***** ******* ********* An...
The challenge A ring is composed of n (even number) circles as shown in diagram. Put natural numbers 1,2,...,n into each circle separately, and the sum of numbers in two adjacent circles should be a prime. Note: the number of first circle should always be 1. Input \$n\quad (0 \lt n \le 16)\$ Output The output format i...
My code works as expected but I am not sure how to optimize the code. The purpose of the code is to find files with given parameters and copy them to a separate folder. import java.io.File; import java.io.IOException; import org.apache.commons.io.FileUtils; import javax.swing.JOptionPane; import java.io.File; import ja...
I am trying to keep the progression of the Review Queue Notifier moving forward. My next big move is to turn it into an extension for Chrome and FireFox and eventually Edge. I would like the Javascript for the code reviewed again to get me back into the groove of coding this extension/script. Here are the guts: $( doc...
Online challenge on Hacker Rank. The king has a string composed of lowercase English letters. Help him figure out whether any anagram of the string can be a palindrome or not. Input Format A single line which contains the input string. Constraints 1 <= length of string <= 10^5 Each character of the string is a lo...
Previous version is here. Sources are available on GitHub. I am trying to define a plug and play CQRS architecture which leverages stereotypical role implementations (Validator, Reader, Writer, Logger, Query, etc) by automatically instantiating associated services through a very limited use of Service Locator. Demo cod...
I created a view called PullView which adds a level of interactivity to UI components. PullViews can be pulled sort of like a rubber-band and bounce a little when released. The code for it is fairly simple. I would like comments on how to improve code structure, performance, etc. if possible. import Foundation import ...
Most properties have simple requirements so it should be possible to register their Dependency Property fields declaratively. I made a small experiment and it seems to work just fine. The first attempt supports DefaultValue and Validation attributes. It looks a little bit like JavaScript ;-) The new DependencyPropert...
I was reviewing for an interview and encountered the following question (and I'm paraphrasing): Suppose you're given a shuffled array of numbers containing all of the numbers between a min and a max, inclusive, with one number missing. For example, for an array of size 5, you could have something like 2, 5, 4, 1 (wher...
I've written this implementation of a binary search algorithm, and wanted to know if it was efficient and where I can improve. function search(el, list) { // list = list || LIST; var LIM = Math.ceil(Math.log2(list.length)), lb = 0, ub = list.length - 1, i; while (el !== list[i = ~~((...
I'm trying to make a simple app in C# that gets the weather data from http://openweathermap.org/api (OWM). Here attached are two classes that I use to initialize WeatherData for selected City and to download and parse XML data from OWM API. I would like to know your opinion on the structure of the classes and the way I...
The next post in my Checker series: The C# wrapper for my F# library to make it cleaner for these methods to be called from C# code. GeneralTypes.cs public enum Player { White, Black } public enum PieceType { Checker, King } public static class Extensions { public static Player Convert(this Checkers.T...
I put together a script which goes through all of the files in Google Drive, and writes a spreadsheet with all of the files with their name, containing folder, URL, and date last updated. function Start_Up() { var spreadsheet = SpreadsheetApp.getActiveSpreadsheet(); var sheet = spreadsheet.getActiveSheet(); shee...
(...as I learn Kotlin) I want to get the indices of the two numbers such that they add up to a specific target from a given array of integers. Solution: fun sum(values: Array<Int>, result: Int): Array<Int> { for ((i, e1) in values.withIndex()) { for ((j, e2) in values.drop(i + 1).withIndex()) { // ...or: values.d...
I have the following code which iterates through some divs of an array to show() them. I was wondering if there is any way to rewrite the for loop using filter(). Will this have a better performance over my initial code? var selectEnabledGenerators = function(generators) { //List of generator indexes to show va...
This is based on a programming challenge I recently solved. However, since the writer of the challenge asked me not to disclose the question and/or it's answer, I modified it a little. If it doesn't make sense: my mistake. The target is to find all numbers in a file and sum those. So if the following is found: Sed ut ...