instruction
stringlengths
71
71.9k
I am working on an API that is mostly intended to be used interactively/little scripts. There are some classes with methods that could act slightly differently depending on the intention of the user, I have explored several options and would like to get some feedback on caveats, and alternative options. I will use a si...
I have a class with a data member that needs to be rounded up to a 2 digit integer, irrespective of the number of the input digits. For example: roundUpto2digit(12356463) == 12 roundUpto2digit(12547984) == 13 // The 5 rounds the 12 up to 13. Currently my code looks like: int roundUpto2digit(int cents){ // convert...
We use this class quite a bit for boilerplate / glue that allows web services and applications to call databases. This code is very important, and I'd like to ensure I'm getting the best performance possible. Any and all feedback is welcome! If there is a better / more efficient way of doing something, please let me kn...
I have a binary file with alternating uint8 and uint64 data stamps. I read those in by using the following line: clicks = np.fromfile(filename, dtype=[('time','u8'),('channel','u2')]) This works well and fast enough. Now i want to go though the array and set the time values to the time difference with respect to the l...
I'm trying to output the percentage of certainty of two comparatives data. Here's the resulting code: /** * Original code from https://vwo.com/js/significanceCalculator.js */ function calculatePValue (c_t, c_c, v_t, v_c) { var d1 = 0.0498673470, d2 = 0.0211410061, d3 = 0.0032776263, d4 = 0...
If classes provide __slots__ and at the same time inherit from another class also providing __slots__, there is no straightforward way to access and list each and every slot of the class. Especially when you consider chaining of inheritance. I've written this meta-class that adds the __all_slots__ property, listing all...
This, again, is a very simple code. This is my 2nd polyglot question and this time I've tried to do something that I miss sometimes in Javascript. PHP has the array_sum() function, but Javascript has no direct equivalent. So, I decided to make one that works with both languages! Here is the code: function sum_array() {...
I've made a small project from my institute. I've got 5 classes, in 4 of the classes (Teachers, Students, Group, Subject). I've got a constructor and get&set methods. In the main class I've got an all functional realization. How can I make this code better and easier to use? package com.company; import java.util.*; p...
I have an app that uses HTML5 video and our customer still needs to support IE8 - Gross. Anyway, I came up with this directive in AngularJS for embedding a SWF object for when I need to fallback to Flash. It works fine so far, but I would like to see if there is anything I can do to improve it. Can anyone see a case wh...
I'm trying to separate logic from the controller, so I created this Upload class. It is not a big class, just a class so that the controller doesn't know about the logic and stuff like that. <?php namespace Dnianas\Uploads; class Photo { /** * The image filename. * @var string */ protecte...
I am trying to make sure my client-side code does not send another request before it receives a reply. To the best of my knowledge the code I will post is supposed to do this but I am still getting a -1 for $return. The AJAX request repeatedly gets the echoed value of a function which is using a batch file to get the s...
I took a test on Codility for coding the minimum number of frog jumps to reach from position x to position y: A small frog wants to get to the other side of the road. The frog is currently located at position X and wants to get to a position greater than or equal to Y. The small frog always jumps a fixed distance,...
I came across this post which explains the copy and swap idiom. However I could not find this idiom applied to classes that have base classes. Following is my attempt of a copy-swap idiom applied to class constructors and assignment operators. In the following code class employee inherits from class human - The constru...
I wrote a quick and dirty auto-clicker for the StackEgg. Any comments, both on code and effectiveness? function doRound() { var stats = []; $(".egg-stat").each(function () { // Find the number of hearts for each stat. var title = $(this).attr("title"); title && stats.push(parseInt(title,...
Inspired by this question on Stack Overflow, I wrote a function that returns the length of a list made of numbers that are divisible by their own sum of digits inside a range: -- Returns the digits of a positive integer as a list, in reverse order. -- This is slightly more efficient than in forward order. digitsRev :: ...
Given an array of ints, return a string identifying the range of numbers. Example: Input arr - [0 1 2 7 21 22 1098 1099] Output - "0-2,7,21-22,1098-1099" Is there any improvement possible in this implementation? #include<iostream> #include<vector> #include<algorithm> #include<sstream> std::string range_creator...
I have been writing a Simple Port scanner in C, once I got it to work I decided I wanted to make it faster because it takes a very long time for it to get done with scanning all of the ports.Is there anything I can improve on in my code to make it faster? Here is my Code : #include <string.h> #include <stdio.h> #inclu...
I thought of a simple way to hash a string. By taking the ASCII decimal value of each character, multiplying it by 10, and adding all of the values computed together for each character in a string. Is there a name for this algorithm? I highly doubt I was the first one to think of this. Compiled with gcc -Wall -Wextra -...
I'm trying to solve this problem. Given a sequence \$B=B_0,B_1,\ldots,B_{N−1}\$ for each query \$(P,K)\$, find the minimum \$S\$ s.t. there are at least \$K\$ entries in \$B\$ that satisfies \$\left|P−i\right| \le S\$ \$B_i \le S\$ where \$B_i\$ denotes the \$i^{th}\$ entry of \$B\$. Input The first line contain...
I got bored and decided to make a merge sort from scratch. I like everything, except for my "merging" of the two arrays into a sorted array inside the for loop. I had several bugs that I had to iron out, which were along the lines of if subArray1 or subArray2 ran out of elements, checking them caused ArrayOutOfBounds...
I have a seat allocation algorithm for an airplane 30 x 6 seats. The plane is 'split' front (1 - 15) and back (16 -30), right (A,B,C) and left (D,E,F). I am placing passengers in window seats front right centre (15A) first then back left centre (16F) followed by (15F) followed by (16A). This will continue for single pa...
Basically, we came up with this task at work. I was wondering if there's a shorter and cleaner way of doing the following in some other language (or even improving what I did with Ruby). We have a folder. In this folder we have files (images only, /w .jpg extension). The names of the images are random strings such as: ...
I want to change the task edit form of the workflow when an approver wants to approve/reject a task. Please review and suggest improvements or any other possible solution with an explanation. public void createTask1_MethodInvoking(object sender, EventArgs e) { createTask1_TaskId1 = Guid.NewGuid(); ...
I'm trying to make a simple app to help me store data about food to use this database in a future diet application. What can I do to improve the code? What part of code should I make a class etc.? #include <iostream> #include <vector> #include <string> #include <map> #include <iterator> using ...
The following is a program to shred files securely: #include <iostream> #include <sstream> #include <string> #include <fstream> #include <vector> #include <cstdio> #include <cstdlib> #define BOOST_FILESYSTEM_NO_DEPRECATED #include <boost/filesystem.hpp> using namespace std; using namespace boost::filesystem; static...
I created a jQuery plugin that converts a text field to a 3 drop down, datepicker. It allows the user to select a Day, Month and Year rather than type the date in an input box. The original input element is hidden and a callback function is provided where the user can format the value for the input box. The id and name...
I'm learning Java, and would really appreciate any tips on how to improve this code. It's just a simple date validation class. import java.util.Map; import java.util.HashMap; class DateValidator { private int day; private int month; private int year; private enum Months { JANUARY(1, 31), FEBR...
I am testing what knowledge I have with the FizzBuzz tests in Java. This is the one I just completed: Given a string str, if the string starts with "f" return "Fizz". If the string ends with "b" return "Buzz". If both the "f" and "b" conditions are true, return "FizzBuzz". In all other cases, return the string unchang...
Given two strings, find the common characters. Is there better implementation for this problem? #include<iostream> #include<string> #include<algorithm> std::string find_intersection(std::string & first, std::string & second) { std::sort(std::begin(first),std::end(first)); std::sort(std::begin(second), std::e...
Although I have been coding in PHP for a while now I am trying to go back to basics with some things to make sure by understanding and methods are the most efficient. I have the following snippet... if (!empty($_GET['location'])) { $location = $_GET['location']; } else { $location = ''; ...
I'm looking to improve my code as seen in the demo link below. The code displays a list in a tooltip. The tooltip is accessed by hovering over the last element of the main list. Here's the demo. The ultimate objective is to wrap only one of the below list item in the code in a JS for loop which will dynamically create ...
I am trying to write an REST API using php from scratch which I am gonna use to play with Angular.js. It is working fine now and I need your opinions on the things I have done in this code to improve myself. NOTE: I am not going to use the below code in production and I am not recommending anyone. I am just trying to l...
I try to make a middleware stack system in the rack way (but not for HTTP request). Here is the main class: class MiddlewareStack def self.stack middleware @middlewares ||= [] @middlewares << middleware end def self.middlewares @middlewares end def self.next payload next_middleware = @midd...
I was having a chat with a friend about data structures (as you do), and that, and his love of portmanteaus meant that he came up with a Quack - A queue and a stack, stuck together in the dumbest way, as it just gives you a tuple of the front and back items. I thought that it might be at least possibly useful if it was...
I'm fairly new to object oriented programming here and am trying to get my head around the best way to go about creating Users and Validating them in the system. My first attempt is below and my main questions apart from does it all seem correct is in regards passing a validator class to the save function and pros/cons...
I would like you to review the solution I came up with to the following scenario: In attempting to model a generic Repository object (that receives a generic type parameter) to interface with my data store, I created an abstract RepositoryBase class, that receives a DbContext parameter in the constructor, and implemen...
I have a C library written by a third-party company. It calculates photo positions on a book page, position of a photo inside an area (which part of the photo to crop), it fills a book with random photos... I have created a .Net wrapper around the C library. I'm very new to C++ so I don't know the conventions (naming, ...
I have a string array: def invoices = [LEDES98BI V2, LINE|INVOICE_DATE|INVOICE_NUMBER|INVOICE_TOTAL, 1|20150301|INV-Error_Test1|22, 2|20150301|INV-Error_Test1|24, 3|20150301|INV-Error_Test2|26, 4|20150301|INV-Error_Test2|28,] I tried to convert it to HasMap<String, List<List>> with key as invoice numbers(INV-Error_Tes...
I'm trying to implement a suffix array for use in programming competitions. I'm using the CodeForces example and trying to "make it my own" so I can make sure I understand it and feel better about using it. Here's what I have so far: struct SuffixArray { vector<int> sa, pos, tmp; int n, gap; SuffixArray(st...
I have just started learning data structures and for the past two days I was going through linked lists. I have implemented the basic/common operations on the linked lists and I would love for some feedback and discuss best practices. P.S: I will also try the STL method, but for starters I did this. /* A list of th...
I'm hoping for a little bit of a code review to ensure I am doing UTF-8 right. I am developing a "csv_fixer" that allows a user to select the encoding of the file so we can correctly handle encoding errors. Also, there is a choice to skip this, in which case I am just removing the fields that have encoding errors. So ...
I have an application that runs hourly, and I want to use it to also send an email at the start of the day of the first Monday of the month. I searched and found information to help me code what I needed, and all my tests pass, but I want to make sure that I am testing for all edge cases and that I am also being a goo...
In my current project I develop a responsive site which has only on desktop a fixed width. Otherwise it's fluid. My client or rather my art director ;) want's fluid bullets with horizontal and vertical centered content on the site. To illustrate that I created a dabblet. Here is my HTML for the bullet: <div class="ib">...
Disclaimer: This question is very much like the one posted here. I gathered some opinions about my options from the answer there. Here, I just want validation about the choices I'm deciding to stick to and see what people think about the decisions specifically. Also, gather suggestions about other parts of the code I'm...
I need to convert a list of dictionaries to a dictionary of dictionaries, with a particular item as the new key. This is the way I'm currently doing it: >>> a [{'bar': 'baz', 'id': 'foo'}, {'bar': 'baz', 'id': 'qux'}] >>> { item['id']:{ sub_item:item[sub_item] for sub_item in item if sub_item != 'id' } ...
Is there a cleaner way of doing this? I'm using filter_input to first check for valid input, then using it again to assign the variable. Also, my condition in if/else seems quite long. $optionsMonth = array('options'=>array('min_range'=>1, 'max_range'=>12)); $optionsYear = array('options'=>array('min_range'=>1900, 'max...
Is the below a good solution for an observer to monitor multiple subjects. My only fear is that if an observer was monitoring a wide range of subjects then the update method could get quite large checking each instance to see what type it is but I can't think of another way to implement this: Journalist Subject cla...
My program fetches input from a RabbitMQ or Amazaon SQS-like queue. There is not always input available in the queue. If a message is available, it triggers work. If that work is successful, message needs to be deleted so that work is not repeated. If work is unsuccessful, message needs to be made visible again, ...
Here's an implementation of finding the minimum element in a rotated array using binary search (one that is sorted in ascending order, and all elements are distinct). Please let me know of any improvements that can be made to it. import java.util.List; public class RotatedArray { /** * Finds and returns the i...
I'm a C++/Python developer attempting to learn JavaScript, but I'm struggling to write clean code. I've read that async.waterfall and Promises are two ways to flatten the code a bit, but my implementation seems far more inflated than what I've grown accustomed to using Python. Is there anything that I can do to refac...
I have a CommunicationStateMachine object that's attached to my channels. It keeps track of who's turn it is to speak, how far along the conversation the server and client are, things like the client ID, all bytes read to date, the ByteBuffer etc. My previous version of this server did some checks in the Selector thr...
I want to write unit-test to my code. However, while writing it, it seems all I can verify is that one method or the other were called once. My class is a manager that execute verification flow. It calls many checkers\verifiers - so they have the real logic. How can I test such "verification flow" code? public Alternat...
I am trying to build a high performance socket server and this is what I have come up with so far. Can anyone please review my code and see if I can make any improvements on it? // State object for reading client data asynchronously public class StateObject { // Client socket. public Socket workSocket = null; ...
Problem Statement This is a challenge from HackerRank: You are given N sticks, where each stick has the length of a positive integer. A cut operation is performed on the sticks such that all of them are reduced by the length of the smallest stick. Suppose we have six sticks of the following lengths: 5 4 4 2 2 8 T...
<script> <?php unset($data0); unset($data1); unset($data2); $sth = $dbh->prepare(" SELECT a, b, c FROM t "); $sth->execute(); ?> Morris.Line({ element: 'morris-line-chart', data: [ <?php while ($row = $sth->fetch()) { ?> { m: '<?php echo $row['0']; ?>', a: <?php echo $row['1']; ?>, b: <?php echo $row['2...
I read through and implemented the advice I received yesterday. I would, once again, really like some input on how this can be improved. e.g. encapsulation, interfaces, abstract classes etc.. Right now, it's one class. import java.util.Map; import java.util.HashMap; class DateValidator { private static DateVali...
I'm looking for suggestions to improve my accordion code. Someone could also use it as a starter for their code. Here's the demo. var Calendar = function(o) { //Store div id this.divId = o.ParentID; // Days of week, starting on Sunday this.DaysOfWeek = o.DaysOfWeek; ...
Am trying to update the Map<String,List<Map<String,String>>> invoices with the invoiceErrors as below InvoiceError // is an entity with below attributes { String errorMessage, String invoiceNumber } ErrorMessage invoiceNumber ------------- ...
I have the below script which returns CSS files based on production or development environment. The development section is fine; but for production I have to do 2 loops to get the files. Is there a cleaner/better way? function get_css_files() { $CI =& get_instance(); $return = array(); $css_files = array( ...
Lets preface this by saying that when it comes to javascript, I am a hack. I make what I need happen by cobbling together crappy, inefficient, redundant code. I want to get better. Recently I was asked if I could make a set of elements on a page sort-able by price, A-Z and Z-A. The code on the page looks something like...
I'm tempted to write a new kind of smart pointer which, I believe, is less intrusive than boost::intrusive_ptr and has the same memory footprint. The code for the smart pointer, which I called less_intrusive_ptr, is shown below (the boost version used is 1.57.0): #include <utility> #include <boost/intrusive_ptr.hpp> #i...
I've received a request at work and the senior developer is away on vacation so I can't ask him. The request was to truncate lengthy article titles while maintaining readability. In other words, don't simply chop a word in half and add an ellipsis. I wrote an extension method that looks for punctuation and establishes ...
Recently, as part of an interview, I was given a (seemingly) simple code prompt: To simulate a Bank with 5 customers and one teller, allowing them to deposit to and withdraw from their accounts, but with each customer on its own thread while only allowing one to access the teller at any given time. I've a CompSci degr...
I was just curious to know what you think about this website I'm designing. I would just like any constructive feedback that you might have. http://jackatron.web44.net/music/ @import url(http://fonts.googleapis.com/css?family=Lato); html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote,...
I've used the typical INT array sort function found all over the internet for years, but I've also had a need to sort other items in an array, or even to just simple take an Array of multiple types of items and get it in order for later readability. Thus leading me to the smartSort method I list below. If I've anything...
I was wondering why replace is not in base. I thought, it's because it must be easy to implement with standard combinators. Although I do not like prefix syntax of Applicative I wrote it this way: replace a b = map (bool <$> id <*> (const b) <*> (== a)) And was slightly surprised after seeing replace in Data.List.Util...
I created a simple login system using just sessions but having to login every time gets annoying. That is why I'm no trying to save the sessions to my database linked to the user's account. I will first show my code and than ask a few questions. First file which is the new file I created is this one named sessiontest.p...
This is my attempt at writing a generic NSMapTable with weak keys and strong values (after your feedback I'll be trying to write Strong-Key/Weak-Value and Weak-Key/Weak-Value variants to have the complete functionality of NSMapTable with generics). To my knowledge it works correctly. public class WeakKeyDictionary<K: A...
I'm new to C and I've been working on some code for a project for school. This was the finished result and now that I'm done it, I came back and tried making it better. So I was wondering, how would I make this printAvgCalPerGroup simplified? #include "diary.h" void printTotalCal(Food * list) { int total = 0; ...
I am trying to bridge the gap between the database context and routes that are stored in the database. The factory is designed so that when used in other assemblies, you are forced to use the database context which is known to contain the DbSet which can provide the required data to populate the route. In the assembly ...
I have just started learning coding and am trying to clean up a website that I am making. Everything is functional, but I imagine there is a better way write everything that is there, because a good chunk of it is repeated each time (the part with mouseover and mouseout) Is there a way to create a command like mouseove...
Is this approach considered good practice, or should I create separate router.delete functions for all my routes? Please, explain why. router.delete('/delete-:object', function(req, res) { var query; var id = req.body.id; switch (req.params.object) { case 'news' : query = queries['news_dele...
I'm taking part in this Daily Challenge on http://www.reddit.com/r/dailyprogrammer/comments/29zut0/772014_challenge_170_easy_blackjack_checker/ Basically, you have to develop a program that runs two blackjack players and outputs the winner, the user has no input on the player's choices - basically it's all AI based. I'...
The problem in question is a coding challenge from Hackerrank: Problem Statement You are given an integer N. Find the digits in this number that exactly divide N (division that leaves 0 as remainder) and display their count. For N=24, there are 2 digits (2 & 4). Both of these digits exactly divide 24. So our ans...
This program is a payroll using calculate two types of employee. Two overloaded functions for two type of employee (hourly and salaried). There must be one pass-by-value, one pass-by-reference, and two pass-by-reference using pointer. All the variable must be local. There are 3 files of this project. Interface clas...
I am creating a class object which must inherit from numpy ndarrays. I perform an isinstance check and an array.shape check with the __new__ method. Is it alright to have it here, or should it be elsewhere? I saw suggestions to create an exceptions class to accompany it, but it doesn't seem necessary... maybe prefer...
I'm working on a C# implementation of a tree class. The tree will be used wherever I need to store data in a tree format. (Application Menu, File Infos etc.). Therefore, the tree should support a lot of different use cases. I think my implementation is ok… but I'm not sure. I never implemented a tree before and I also ...
I have a simple function that takes an Integer n and return a string representing the array from 1..n. nthLine :: Integer -> String nthLine n = intercalate " " $ map show [1..n] The main function takes input n from the user and prints the nthLine out to screen: getInteger :: String -> Integer # This seems redunda...
I made this mini life simulation thing. I got the idea from the Eloquent JavaScript textbook, and just kinda ran with it. I've been programming for a little less than year and this is probably the largest thing I've made to date, so I'm looking for a little feedback. If there's anything you see that can be improved, pl...
I am creating simple web api/ SPA application using EntityFramework, IUnitOfWork, Repository pattern, Unity DI along with Asp.net Identity. Unity configuration public static void RegisterTypes(IUnityContainer container) { // TODO: Register your types here container.RegisterType<DataConte...
Here is a search implementation for my tree. It searches each node in a breadth-first manner first, but it goes deeper in a depth-first manner, in the event it needs to go deeper. I know there may be multiple identical items in the tree (well, not my current use of it, but I still need to presume that), so it just re...
I'm designing a login portal that has one angularjs page that displays/processes data queried from a database. I'm relying on a few php pages (a loginpage.php [verifies credentials/loads session variables], a check.php [page that is included in all php pages, verifies session variables are 'okay'], and a getter.php [qu...
You are given 3 strings: text, pre_text and post_text. Let L be a substring of text. For each substring L of text, we define pattern_score as follows: pre_text_pattern_score = highest n, such that first n characters of L are equal to the last n characters of pre_text and occur in the same exact order. post_t...
I'm developing an iOS Application in Swift that uses Google Cloud Endpoints as its backend. For now, I've just written the code for the user to login with his Gmail account and I've refactored it as much as possible but the callback chain is making me nervous. The reason I'm worried is because firstly, I'm fairly new t...
I feel the best way to learn is practice. I have written a simple Blackjack game in Python which supports multiple-players and functionality like Hit, Stand, Surrender, Split and Double_Down. I need some help to review my code, in order to remove any redundant code, simplify the implementation, and improve the code qua...
I watched bunch of videos about swing and GUI in general and created my first component (correct me if it is not one). JPanel class: package gui.pane; import javax.swing.*; import javax.swing.event.EventListenerList; import java.awt.*; import java.text.DateFormatSymbols; import java.util.ArrayList; import java.util.C...
I have this visual mod for a javax.swing.JProgressBar: import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.GridLayout; import java.awt.Toolkit; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JProgre...
As one of my first C programs I want to read in a matrix and compute its determinant. I don't pose limits on the size of the matrix and this makes things more complicated. Version 0 #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #define ROW_LENGTH 8 #define CHUNK 32 typedef struct { ...
Question: Smallest positive number that is evenly divisible by all of the numbers from 1 to 20? I tackle the problem with reference to how I solved #3, which is using the prime_division method in the Prime class. I have created an array of prime_divisions for 2..20. The array looks like this: [[2, 1], [3, 1], [2, 2],...
I've got a base class GraphUIControl which is inherited by 4 child classes: BubbleGraphUIControl BatchGraphUIControl LineGraphUIControl StackedGraphUIControl I sometimes put all my GraphUIControl in the same List<GraphUIControl> for some obscure reasons. I wanted to order my list (first by Graph type, then by name) s...
I want to know if there is any redundancy in the code or if it is missing something. I ran it with several different choices and it works fine but I still want to know are there any more subtle implementations in parts or in full. import java.io.*; class data{ String name; int roll; int age; public data(String a,int b...
I am a beginner to PHP programming. I wanted to make a 2D array that would store the values of a table into the array. Below is the Frankenstein code I created (every time I wanted to achieve a task I researched a solution, so this is a bunch of solutions plus my own doing put together). I would be really grateful if ...
I've been building a simple C# server-client chat-style app as a test of my C#. I've picked up code from a few tutorials, and extended what's there to come up with my own server spec. In this post (the second will be the client), I'd like to get some feedback on the server. To me, the code seems bulky and as if it coul...
I've been experimenting with some old code that needs refactoring in places and was testing if there was any improvement to iis threads etc by uploading file asynchronously (Server Side). I'm using jQuery file upload client side. The original code [HttpPost] public ActionResult UploadDocument( HttpPostedFileBase upload...
I've written a stable implementation of insertion sort, that sorts an array in ascending order. Please let me know of any improvements/optimisations that can be made. import java.util.List; public class InsertionSort { public static void start(List<Integer> arrayToSort){ for(int i = arrayToSort.size() - 1;...
Here's an implementation of selection sort, that sorts an array in ascending order. Please let me know of any improvements/optimisations that can be done. import java.util.List; public class SelectionSort { public static void start(List<Integer> arrayToSort){ for(int i = 0; i < arrayToSort.size(); i++) { ...
First and second post on the same subject. This is such a great way to learn. Once again I'm open to suggestions. I have implemented almost all of the suggestions from before, which have resulted in the code looking like this: import java.util.Set; import java.util.HashSet; import java.util.Arrays; import java.util.re...
Question: Difference between the Sum of squares from 1 to 100 and the square of sums of 1 to 100. Answer in Ruby: range.inject(:+) ** 2 - range.map{|x| x ** 2}.inject(:+) This one seems pretty straightforward but welcome any improvements to make it more elegant!
Problem 1: Sum the even numbers for the first n fibonacci numbers Solution: def fib(k): """Compute kth fibonacci number. >>> fib(1) 0 >>> fib(2) 1 >>> fib(11) 55 """ def recursive_fib(prev, curr, k): if k - 1 == 0: return curr else: return...
I'm trying to write a function explodeBy: explodeBy :: Int -> [Int] -> [Int] explodeBy n arr = foldr (\x acc-> (take n.repeat) x ++ acc ) [] arr This works as follows: λ> explodeBy 2 [1,2,3] [1,1,2,2,3,3] The above uses list concatenation, so I tried writing a more efficient version: explodeBy2 n arr = foldr (\x acc...