Recent Entries 10
- pattern minor 112d agoFunction to find the shortest word in an array, where not every element is a stringI wrote a solution for a codeCamp exercise: Write a function called `findShortestWordAmongMixedElements`. Given an array, `findShortestWordAmongMixedElements` returns the shortest string within the given array. Notes: - If there are ties, it should return the first element to appear in the given array. - Expect the given array to have values other than strings. - If the given array is empty, it should return an empty string. - If the given array contains no strings, it should return an empty string. Right now I essentially break this function into two parts. The filtering method—to just get the strings—and then `reduce` to find the shortest one among them. ``` function findShortestWordAmongMixedElements(arr) { var containsStrings = function(arr){ return arr.every(function(cv){ return Object.prototype.toString.call(cv) !== '[object String]'; }); }, shortestWord; if ((!(arr.length)) || ((containsStrings(arr)))) return ''; arr = arr.filter(function(e, i, a){ if (typeof e == 'string') { return e; } }); shortestWord = arr.reduce(function(prev, next) { if (prev.length < next.length) { return prev; } else if (prev.length === next.length){ return prev; } else { return next; } }); return shortestWord; } ``` My take is this is certainly readable which I like and I LOVE the helper function I made for the initial check which uses the `every` method. Since (at first) I spent a lot of time trying to do all the operations within the body of the callback for the filter—I feel this take is like I used flat head screw driver for every screw instead of a phillips...
- pattern major 112d agoPartitioning an array based on a condition in JavascriptUsing the array.filter function, I can efficiently pull out all elements that do or do not meet a condition: ``` let large = [12, 5, 8, 130, 44].filter((x) => x > 10); let small = [12, 5, 8, 130, 44].filter((x) => !(x > 10)); ``` However, in the example above, I'm iterating over the array twice and performing the same test each time. Is there a simple way to generate both 'large' and 'small' in a single pass over the array? In particular, if the callback to evaluate whether an element should be kept is expensive, I'd like to avoid calling it twice.
- pattern minor 112d agoFind the center of a red dot of an image in HaskellI try to find the center of all the red pixels contained in an image using `Haskell` and `repa`. My problem is, that the code is not fast enough, probably because I read the image with `repa-io` which returns an `Array Z DIM3 Word8`, but I was not able to figure out how to filter the repa array by how red the given pixels are. That's why I convert the array to a normal list, using `R.toList`. The rest of the calculations are then done using lists. Here is my code: ``` import Data.Array.Repa.Repr.ForeignPtr (F, fromForeignPtr, toForeignPtr) import Data.Array.Repa (Z(..), (:.)(..), DIM0, DIM1, DIM2, DIM3, Array(..), Source, Shape) import qualified Data.Array.Repa as R import Data.Array.Repa.IO.DevIL import Data.List import System.Environment (getArgs) main :: IO () main = do [path] Array r DIM3 a -> (Int, Int) findRedDot img = (median . fst $ splitted, median . snd $ splitted) where -- function returning the coordinates as a tuple, when the pixel -- is red enough, otherwise return (-1, -1) convert f (Z :. i :. j) = let r = f (Z :. i :. j :. 0) g = f (Z :. i :. j :. 1) b = f (Z :. i :. j :. 2) in if r > 237 && (g + b) Z :. w :. h) convert -- turns the DIM2 repa array into a default haskell list lst = R.toList packed p (-1, -1) = False p _ = True -- split up the list into x and y component splitted = splitUp $ filter p lst -- | split up a list of tuples into two lists splitUp :: [(Int, Int)] -> ([Int], [Int]) splitUp [] = ([], []) splitUp ((x, y):rest) = (x:(fst next), y:(snd next)) where next = splitUp rest -- | find the median of a numeric list median :: (Num a, Ord a) => [a] -> a median [] = -1 median l = sorted !! mid where len = length l mid = len `quot` 2 sorted = sort l ``` I did compile with `g
- pattern minor 112d agoGetting max and min values from ArrayMy code works; I am just seeing if there's an optimized way to write these methods or even better perhaps combine them (since majority of their contents look similar). ``` public class IntegerUtils { public static int getMaxValue(int[] array) { int value = Integer.MIN_VALUE; if (array.length value) { value = array[i]; } } return value; } public static int getMinValue(int[] array) { int value = Integer.MAX_VALUE; if (array.length <= 0) { throw new IllegalArgumentException("Array is empty."); } for (int i=0; i < array.length; i++) { if (array[i] < value) { value = array[i]; } } return value; } } ``` Here's my unit test (which works as well): ``` import org.junit.Test; public class IntegerUtilsTest { int[] array = new int[] {1, 2, 3, 58, 47, 229, 40}; @Test public void shouldBeMaxValue() { int maxValue = IntegerUtils.getMaxValue(array); assert(maxValue == 229); } @Test public void shouldBeMinValue() { int minValue = IntegerUtils.getMinValue(array); assert(minValue == 1); } @Test(expected = IllegalArgumentException.class) public void shouldBeIllegalArgumentException() { int[] emptyArray = new int[] {}; int maxValue = IntegerUtils.getMaxValue(emptyArray); int minValue = IntegerUtils.getMinValue(emptyArray); } } ``` Just seeking feedback regarding optimization and / or code elegance.
- pattern minor 112d agoConsole Address Book applicationI'm in my second week/second section of learning C# through Treehouse/on my own. I recently switched from learning Javascript and am looking for a review of my code. I believe I've tested everything and have refactored to get it as concise as I can. The project is fully functional and does the following: - Adds a new contact - Updates existing contacts - Checks for duplicate contacts - if contact is a duplicate it asks the user if they want to update - returns(prints to the console) new/updated contact to view - Removes existing contacts - Formats contacts (upper/lower case) ("oH, bILly") //=> Oh, Billy - Allows a user to quit a process at anytime - Allows user to view the entire list of contacts Some things I considered: - Using List - I wanted the practice with c# arrays since they differ from the javascript array literal - Adding a method that would allow a user to enter partial names and get a list of possible matches - Changing the switch(name) in Main() to an if/else to make it a bit more readable. ADDITIONAL NOTE: I think it is fairly self-documenting, but I wrote it so, if you have any questions please ask. And, ContainsEntry() was written by someone else. I think that covers it..here's my code: Contact class ``` namespace AddressBook { class Contact { public string Name { get; set; } public string Address { get; set; } public Contact(string name, string address) { Name = name; Address = address; } } } ``` AddressBook class ``` using System; namespace AddressBook { class AddressBook { public readonly Contact[] contacts; public AddressBook() { contacts = new Contact[2]; ; } public bool AddEntry(string name, string address) { if (!ContainsEntry(name)) { name = FormatContact(name); address = FormatContact(address); Contact AddContact = new Contact(name, address);
- pattern minor 112d agoReplace ' ' Spaces in a URL with a '%20' - Coding ChallengeThis was a small coding challenge proposed at my school. The problem is: Given a string (or URL), replace the white-spaces inside of the string with `%20`, but any spaces on the outside should not be included. For example, input `" Mr John Smith "` would return `"Mr%20John%20Smith"`. I have completed this challenge successfully using the code below. My question is, is there any way to improve the efficiency? I believe the complexity is currently \$O(2n) = O(n)\$ given the 2 for loops. I do not want to use any libraries or functions like `str.replace()`. But I'm assuming there is a better way than trimming and then counting the whitespace. ``` public class URL { /** * @description URLify ~ A small method that makes a string with spaces URL Friendly! * @param str * @param length * @return String */ public static String URLify(String str) { str = str.trim(); int length = str.length(); int trueL = length; if(str.contains(" ")) { for(int i = 0; i < length; i++) { if(str.charAt(i) == ' ') { trueL = trueL + 2; } } char[] oldArr = str.toCharArray(); char[] newArr = new char[trueL]; int x = 0; for(int i = 0; i < length; i++) { if(oldArr[i] == ' ') { newArr[x] = '%'; newArr[x+1] = '2'; newArr[x+2] = '0'; x += 3; } else { newArr[x] = oldArr[i]; x++; } } str = new String(newArr, 0, trueL); } return str; } public static void main(String[] args) { String str = " https://google.com/ testing .pdf "; str = URLify(str); System.out.print(str); } } ``` Note: I am looking for any criticism. I would really like to improve my skills in ge
- pattern minor 112d agoApply function to array of decimalsI am writing some code to transform an array of decimals so that they are discounted over time. I initially wrote the following code: ``` private decimal[] deflateArray(decimal[] items, decimal deflateRate) { decimal[] deflatedItems = new decimal[items.Count()]; decimal factorAdjustment = 1; for (int i = 0; i < items.Length; i++) { deflatedItems[i] = items[i] / factorAdjustment; factorAdjustment = factorAdjustment * (1 + deflateRate); } return deflatedItems; } ``` Then I realised that instead of having the `factorAdjustment` variable, I can just use to the power of: ``` private decimal[] deflateArray(decimal[] items, decimal deflateRate) { decimal[] deflatedItems = new decimal[items.Count()]; for (int i = 0; i < items.Length; i++) { deflatedItems[i] = items[i] / (decimal)Math.Pow((double)(1 + deflateRate), i); } return deflatedItems; } ``` As `Math.Pow()` only accepts and returns `double`s, I think it's easier to create a wrapper function for it: ``` private decimal PowerOf(decimal x, decimal y) { return (decimal)Math.Pow((double)x, (double)y); } ``` and then simplify: ``` private decimal[] deflateArray(decimal[] items, decimal deflateRate) { decimal[] deflatedItems = new decimal[items.Count()]; for (int i = 0; i < items.Length; i++) { deflatedItems[i] = items[i] / PowerOf(1 + deflateRate, i); } return deflatedItems; } ``` Then I realised that I really just want to transform the array and don't need a second array: ``` private void deflateArray(decimal[] items, decimal deflateRate) { for (int i = 0; i < items.Length; i++) { items[i] = items[i] / PowerOf(1 + deflateRate, i); } } ``` and then I can simplify this to: ``` private void deflateArray(decimal[] items, decimal deflateRate) { for (int i = 0; i < items.Length; i++) { items[i] /= PowerOf(1 + deflateRate, i); } } ``` so my final version is: ``` private v
- pattern minor 112d agoPrimitive String trimmer in CI just picked up C and am following through The C programming language. I've previously got experience with a lot of 'higher'-level languages, so when I saw this exercise in the book: Write a program to copy its input to its output, replacing each string of one or more blanks by a single blank. I thought I'd create a very basic and primitive trim-program that takes an input and removes all superfluous white-spaces (more than 1 in a row) and prints out a 'trimmed' string. As mentioned I just recently started and we haven't covered dynamic arrays yet, so I'm just using static ones. But I was hoping to get some feedback on my solution: ``` #include /* ** A primitive trimmer ** to remove any superflous ** whitespaces in a given ** string (input). */ int main () { /* ** Setting up the variables ** ** Working with static ** arrays since I haven't ** been introduced to dynamic. */ char input [100], output[100]; fgets(input, 100, stdin); int i = 0, k = 0; // Looping over input until hitting // an item containing a null-char. while (input[i] != '\0') { if (input[i] == ' ') { // hitting first space. int j = i + 1; // initiating temporary counter. if (input[j] != '\0') { // find index of first non-space // character after initial space. while (input[j] != '\0' && input[j] == ' ') { if (input[j] == ' ') { i++; // keep indexing input-index } j++; // keep incrementing temporary indexer. } } } output[k] = input[i]; // insert non-space item into output. i++; // increment input-indexer. k++; // prepare output-indexer for next non-space. } printf("%s", output); // print trimmed input. } ``` It's not going to be prett
- pattern minor 112d agoDe-linearize a 2d linearized grid and calculate distance between 2 pointsIn a simulation of mine, for which performance is paramount, I have the following bottleneck. I have a huge 2D grid of dimensions `width` and `height`, whose dimensions are stored in linearized form, i.e. positions at `x` and `y` are stored as one integer `x + y*width`. Every iteration I have to get thousands of such linearized coordinates, de-linearize an calculate distance between 2d coordinates. Currently, what I do is: ``` y1 = linPos1 / width; //int divided by int disregards remainders x1 = linPos1 - width * y1; y2 = linPos2 / width; //int divided by int disregards remainders x2 = linPos2 - width * y2; int xDiff = x2-x1; int yDiff = y2-y1; double distance = sqrt(xDiff*xDiff + yDiff*yDiff); ``` How could I improve upon that? What is the most performant way to take two of such integer values, retrieve back `x` and `y` and then calculate the 2D distance between said points? I am open to all suggestions, including SIMD instructions.
- snippet minor 112d agoConvert data (adding and sorting) with JavaScriptI have an array of data like this: ``` var data = [ ['a', 2010, 12], ['a', 2010, 20], ['a', 2011, 43], ['a', 2012, 25], ['a', 2012, 15], ['b', 2010, 40], ['b', 2012, 65], ['b', 2013, 20], ['b', 2013, 10], ['b', 2013, 15], ['c', 2010, 13], ['c', 2010, 17], ['c', 2011, 22], ['c', 2011, 32], ['c', 2011, 10], ['c', 2012, 45], ['c', 2013, 10], ['c', 2013, 20] ] ``` and each array data is [name, year, value]. What I want to do here is to add values when name and year are the same and then sort data by year and change the order by name, so I want to convert data to: ``` var newData = [ ['a', 2010, 32], ['b', 2010, 40], ['c', 2010, 30], ['a', 2011, 43], ['c', 2011, 64] ['a', 2012, 40], ['b', 2012, 65], ['c', 2012, 45], ['b', 2013, 45], ['c', 2013, 30] ] ``` I am doing this by taking multiple steps: ``` // find names var sortByName = []; var nameArr = []; var namesFound = {}; for(var i = 0; i < data.length; i++) { if(namesFound[data[i][0]]) { continue; } nameArr.push(data[i][0]); namesFound[data[i][0]] = true; } // sort data by name by creating an array for each name (2D array to 3D array) for (var i = 0; i < nameArr.length; i++) { var result = data.filter(function(arr) { return arr[0] == nameArr[i] }) sortByName.push(result) } // add values with a same year var newArr = sortByName.map(function(eachArr) { var sumBySameYear = eachArr.reduce(function(acc, arr) { if (acc.year === arr[1]) { acc.result[acc.result.length - 1][2] += arr[2]; } else { acc.result.push(arr); acc.year = arr[1] } return acc }, {result: [], year: null}); return sumBySameYear.result }); // 3D array to 2D array var multiToSingleArr = [].concat.apply([], newArr); // then sort new data by year and keep the order of name var newData = multiToSingleArr.slice().sort(function(a, b) { return a[1] - b[1] || a[0].localeCompare(b[0]); }); ``` I definitely feel like I am taking unnecessary steps here, so how can I make thi