How do I insert an element at the correct position into a sorted array in Swift?

Here is a possible implementation in Swift using binary search (from http://rosettacode.org/wiki/Binary_search#Swift with slight modifications): extension Array { func insertionIndexOf(_ elem: Element, isOrderedBefore: (Element, Element) -> Bool) -> Int { var lo = 0 var hi = self.count – 1 while lo <= hi { let mid = (lo + hi)/2 if isOrderedBefore(self[mid], elem) { … Read more

Sort Objects in Array by date

Using Swift 4 & Swift 3 let testArray = [“25 Jun, 2016”, “30 Jun, 2016”, “28 Jun, 2016”, “2 Jul, 2016”] var convertedArray: [Date] = [] var dateFormatter = DateFormatter() dateFormatter.dateFormat = “dd MM, yyyy”// yyyy-MM-dd” for dat in testArray { let date = dateFormatter.date(from: dat) if let date = date { convertedArray.append(date) } } … Read more

How to pass array as an argument to a function in Bash

[*] You cannot pass an array, you can only pass its elements (i.e. the expanded array). #!/bin/bash function f() { a=(“$@”) ((last_idx=${#a[@]} – 1)) b=${a[last_idx]} unset a[last_idx] for i in “${a[@]}” ; do echo “$i” done echo “b: $b” } x=(“one two” “LAST”) b=’even more’ f “${x[@]}” “$b” echo =============== f “${x[*]}” “$b” The other … Read more

In MATLAB, when is it optimal to use bsxfun?

There are three reasons I use bsxfun (documentation, blog link) bsxfun is faster than repmat (see below) bsxfun requires less typing Using bsxfun, like using accumarray, makes me feel good about my understanding of MATLAB. bsxfun will replicate the input arrays along their “singleton dimensions”, i.e., the dimensions along which the size of the array … Read more

Can min/max of moving window achieve in O(N)?

O(N) is possible using Deque data structure. It holds pairs (Value; Index). at every step: if (!Deque.Empty) and (Deque.Head.Index <= CurrentIndex – T) then Deque.ExtractHead; //Head is too old, it is leaving the window while (!Deque.Empty) and (Deque.Tail.Value > CurrentValue) do Deque.ExtractTail; //remove elements that have no chance to become minimum in the window Deque.AddTail(CurrentValue, … Read more

Creating Indicator Matrix

The thing about an indicator matrix like this, is it is better if you make it sparse. You will almost always be doing a matrix multiply with it anyway, so make that multiply an efficient one. n = 4; V = [3;2;1;4]; M = sparse(V,1:n,1,n,n); M = (3,1) 1 (2,2) 1 (1,3) 1 (4,4) 1 … Read more