Skip to content

Instantly share code, notes, and snippets.

View tkausch's full-sized avatar

Thomas Kausch tkausch

View GitHub Profile
@tkausch
tkausch / Queue.swift
Created January 26, 2022 22:55
Fast Queue implementation using array RingBuffer
import Foundation
public struct Queue<T> {
private var array: Array<T?>
private var availableSpaceCount: Int
private var readIndex: Int
@tkausch
tkausch / MaximumProductSubarray.swift
Created November 2, 2020 13:58
Maximum Product Subarray (smarter)
func maxProduct(_ nums: [Int]) -> Int {
guard nums.count > 0 else {
return 0
}
var maximum = nums.first!
var maxPositivEnding = nums.first!
var minNegativeEnding = nums.first!
@tkausch
tkausch / MaxSubarrayProduct.swift
Created November 2, 2020 13:00
Maximum Product Subarray problem
func maxProduct(_ nums: [Int]) -> Int {
guard nums.count > 0 else {
return 0
}
guard let first = nums.first, first != 0 else {
return max(0,maxProduct(Array(nums.dropFirst())))
}
@tkausch
tkausch / MaxSumSubArray.swift
Last active November 2, 2020 13:02
Maximum sum subarray
func maxSubArray(_ nums: [Int]) -> Int {
guard nums.count > 0 else {
return Int.min
}
var bestEndingSum = nums.first!
var maxSum = nums.first!
for num in nums[1..<nums.endIndex] {
bestEndingSum = max(bestEndingSum + num, num)
@tkausch
tkausch / TrimWhitespaceInString
Created October 23, 2020 15:10
How to trim whitespace in a string
let str = " Taylor Swift is £!?"
let trimmed = str.trimmingCharacters(in: .whitespacesAndNewlines)
@tkausch
tkausch / SearchString
Created October 23, 2020 15:08
How to run case insensitive search of string in another
if let range3 = string.range(of: "rain", options: .caseInsensitive) {
// match
} else {
// no match
}
@tkausch
tkausch / ReverseString.swift
Created October 23, 2020 15:05
How to reverse a string
let str = "Hello, world!"
let reversed = String(str.reversed())
print(reversed)
@tkausch
tkausch / RemovePrefix.swift
Created October 23, 2020 15:02
How to remove prefix from string
extension String {
func deletingPrefix(_ prefix: String) -> String {
guard self.hasPrefix(prefix) else { return self }
return String(self.dropFirst(prefix.count))
}
}
@tkausch
tkausch / AccessSingleLetterInString.swift
Created October 23, 2020 15:00
How to read single letter in a string
extension String {
subscript(i: Int) -> String {
return String(self[index(startIndex, offsetBy: i)])
}
}
@tkausch
tkausch / LoadStringFromFile.swift
Created October 23, 2020 14:57
How to load a string from a file in your bundle
if let filepath = Bundle.main.path(forResource: "example", ofType: "txt") {
do {
let contents = try String(contentsOfFile: filepath)
print(contents)
} catch {
// contents could not be loaded
}
} else {
// example.txt not found!
}