Skip to content

Instantly share code, notes, and snippets.

@airspeedswift
Forked from sketchytech/Swift Generic Functions
Last active August 29, 2015 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save airspeedswift/ef336843211a7c68be4d to your computer and use it in GitHub Desktop.
Save airspeedswift/ef336843211a7c68be4d to your computer and use it in GitHub Desktop.
// SORTED SET - removes duplicates and orders a sequence that adopts the RangeReplaceableCollectionType protocol
var arr = [1,22,22,34,3,3,5,6]
var arrStr = ["bee","ant","tree","ant","fox","rabbit","fox"]
sortedSet(arr, [Int]()) // returns [1,3,5,6,22,34]
sortedSet(arrStr, [String]()) // returns ["ant","bee","fox","rabbit","tree"]
// INSERT - insert a sequence in a type that adopts RangeReplaceableCollectionType at an Index
var str = "Hello, playground"
var arr = [1,2,3,4,5,6,6,5,4,3]
insert(&arr, [1,2,3], 5)
insert(&str, "HI THERE!", 7)
// DELETE DUPLICATES in a type that adopts RangeReplaceableCollectionType
deleteDuplicates([1,2,2,3,2,4,5,6,6], [Int]()) // returns [1,2,3,4,5,6]
deleteDuplicates("Hello, playground", String()) // returns "Helo, paygrund"
// sample string for testing performance of deleteDuplicates
let s = "Mr. Sherlock Holmes. BEING A REPRINT FROM THE REMINISCENCES OF JOHN H. WATSON, M.D., LATE OF THE ARMY MEDICAL DEPARTMENT. In the year 1878 I took my degree of Doctor of Medicine of the University of London, and proceeded to Netley to go through the course prescribed for surgeons in the Army. Having completed my studies there, I was duly attached to the Fifth Northumberland Fusiliers as assistant surgeon. The regiment was stationed in India at the time, and before I could join it, the second Afghan war had broken out. On landing at Bombay, I learned that my corps had advanced through the passes, and was already deep in the enemy’s country. I followed, however, with many other officers who were in the same situation as myself, and succeeded in reaching Candahar in safety, where I found my regiment, and at once entered upon my new duties. The campaign brought honours and promotion to many, but for me it had nothing but misfortune and disaster. I was removed from my brigade and attached to the Berkshires, with whom I served at the fatal battle of Maiwand. There I was struck on the shoulder by a Jezail bullet, which shattered the bone and grazed the subclavian artery. I should have fallen into the hands of the murderous Ghazis had it not been for the devotion and courage shown by Murray, my orderly, who threw me across a pack-horse, and succeeded in bringing me safely to the British lines. Worn with pain, and weak from the prolonged hardships which I had undergone, I was removed, with a great train of wounded sufferers, to the base hospital at Peshawar. Here I rallied, and had already improved so far as to be able to walk about the wards, and even to bask a little upon the veranda, when I was struck down by enteric fever, that curse of our Indian possessions. For months my life was despaired of, and when at last I came to myself and became convalescent, I was so weak and emaciated that a medical board determined that not a day should be lost in sending me back to England. I was despatched, accordingly, in the troopship Orontes, and landed a month later on Portsmouth jetty, with my health irretrievably ruined, but with permission from a paternal government to spend the next nine months in attempting to improve it. I had neither kith nor kin in England, and was therefore as free as air—or as free as an income of eleven shillings and sixpence a day will permit a man to be. Under such circumstances I naturally gravitated to London, that great cesspool into which all the loungers and idlers of the Empire are irresistibly drained. There I stayed for some time at a private hotel in the Strand, leading a comfortless, meaningless existence, and spending such money as I had, considerably more freely than I ought. So alarming did the state of my finances become, that I soon realized that I must either leave the metropolis and rusticate somewhere in the country, or that I must make a complete alteration in my style of living. Choosing the latter alternative, I began by making up my mind to leave the hotel, and take up my quarters in some less pretentious and less expensive domicile. On the very day that I had come to this conclusion, I was standing at the Criterion Bar, when someone tapped me on the shoulder, and turning round I recognized young Stamford, who had been a dresser under me at Bart’s. The sight of a friendly face in the great wilderness of London is a pleasant thing indeed to a lonely man. In old days Stamford had never been a particular crony of mine, but now I hailed him with enthusiasm, and he, in his turn, appeared to be delighted to see me. In the exuberance of my joy, I asked him to lunch with me at the Holborn, and we started off together in a hansom. “Whatever have you been doing with yourself, Watson?” he asked in undisguised wonder, as we rattled through the crowded London streets. “You are as thin as a lath and as brown as a nut.” I gave him a short sketch of my adventures, and had hardly concluded it by the time that we reached our destination. “Poor devil!” he said, commiseratingly, after he had listened to my misfortunes. “What are you up to now?”"
// FINDS - find multiple Elements in a Collection
finds([1,2,3,4,4,5,5,6], 4) // returns [3,4]
finds("lllllllllll", "l") // returns [0,1,2,3,4,5,6,7,8,9,10]
finds(["one","two","one"], "one") // returns [0,2]
func sortedSet<S: RangeReplaceableCollectionType where S.Generator.Element: Comparable>(seq:S, obj:S)-> [S.Generator.Element] {
let s = reduce(seq, obj){
ac, x in contains(ac,x) ? ac : ac + [x]
}
let set = sorted(s){$0<$1}
return set
}
func insert<S:RangeReplaceableCollectionType, I: SignedIntegerType where I == S.Index.Distance, S.Generator.Element: Equatable>(inout seq:S, ins:S, ind:I) {
// use of abs() prevents a negative value causing the insertIndex to be before the startIndex
var insertIndex = advance(seq.startIndex, abs(ind), seq.endIndex)
for c in ins {
insert(&seq, c, atIndex: insertIndex)
insertIndex = advance(insertIndex, 1)
}
}
func deleteDuplicates<S: ExtensibleCollectionType where S.Generator.Element: Equatable>(seq:S)-> S {
return reduce(seq, S()){
ac, x in contains(ac,x) ? ac : ac + [x]
}
}
// specialised version for when collection contains a hashable element
func deleteDuplicates<C: ExtensibleCollectionType where C.Generator.Element: Hashable>(domain: C) -> C {
var h: [C.Generator.Element:Int] = [:]
var acc = C()
for elem in domain {
if h.updateValue(1, forKey: elem)==nil {
acc.append(elem)
}
}
return acc
}
func finds<C: CollectionType, E: Equatable where E == C.Generator.Element>(haystack:C, needle:E) -> [C.Index] {
var startInd = haystack.startIndex, arr = Array<C.Index>()
do {
if haystack[startInd] ==
needle
{
arr.append(startInd)
}
startInd = advance(startInd,1)
}
while startInd != haystack.endIndex
return arr
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment