Thread 1: EXC_BAD_ACCESS (code=2, address=0x16d0f3ff0) - ios

I am developing an app (in XCode Version 11.2 and Swift 4.2) in which I fill in a LinkedList and after working with it, removing the elements that compose it produces the Thread 1 error: EXC_BAD_ACCESS (code = 2, address = 0x16d0f3ff0). The error occurs even without working with the items in the list, simply by adding them and trying to eliminate them the error already occurs. The tests I am doing with an iPhone with IOS version 11.4.1
The implementation of the LinkedList is as follows:
import Foundation
public class Node<T> {
var value: T
var next: Node<T>?
weak var previous: Node<T>?
init(value: T) {
self.value = value
} // init
} // Node
public class LinkedList<T> {
private var head: Node<T>?
private var tail: Node<T>?
public private(set) var count: Int = 0
public init() { } // init
public var isEmpty: Bool {
return self.head == nil
} // isEmpty
public var first: Node<T>? {
return self.head
} // first
public var last: Node<T>? {
return self.tail
} // last
public func nodeAt(index: Int) -> Node<T>? {
if index >= 0 {
var node = self.head
var i = index
while node != nil {
if i == 0 {
return node
} // if
i -= 1
node = node!.next
} // while
} // if
return nil
} // nodeAt
public func removeAll() {
self.head = nil
self.tail = nil
self.count = 0
} // removeAll
public func remove(node: Node<T>?) -> String {
if isEmpty {
return String("ERROR: Empty list, nothing to remove.")
} // if
guard node != nil else {
return String("ERROR: Invalid node, nothing to remove.")
} // guard
let prev = node?.previous
let next = node?.next
if next != nil && prev == nil {
self.head = next
next?.previous = nil
} else if next != nil && prev != nil {
prev?.next = next
next?.previous = prev
} else if next == nil && prev != nil {
self.tail = prev
prev?.next = nil
} // if
node?.previous = nil
node?.next = nil
self.count -= 1
return String("Successfully removed node: \(node!.value)")
} // remove
func enqueue(value: T) {
let newNode = Node(value: value)
if let tailNode = self.tail {
newNode.previous = tailNode
tailNode.next = newNode
} else {
self.head = newNode
} // else
self.tail = newNode
self.count += 1
}
func enqueue_first(value: HexRecord) {
let newNode = Node(value: value)
if let headNode = self.head {
newNode.next = headNode
headNode.previous = newNode
}
self.head = newNode
self.count += 1
}
func dequeue() -> T? {
let element = self.head?.value
self.head = self.head?.next
self.count -= 1
return element
}
} // LinkedList
The nodes of the same are of the HexRecord type:
public class HexRecord
{
private var length: Int = 0
private var address: Int64 = 0
private var type: Int32 = 0
private var data = [UInt8] ()
private var checksum: UInt8 = 0
init()
{
}
public func getAddress() -> Int64 {
return address;
}
public func getType() -> Int32 {
return type;
}
public func getData() -> [UInt8] {
return data;
}
public func getLength() -> Int {
return length;
}
public func getChecksum() -> UInt8 {
return checksum;
}
public func setAddress(address: Int64) {
self.address = address;
}
public func setData(data: [UInt8]) {
self.data = data;
}
public func setLength(length: Int) {
self.length = length;
}
public func setType(type: Int32) {
self.type = type;
}
public func setChecksum(checksum: UInt8) {
self.checksum = checksum;
}
}
It is used as follows:
func tratar_registros() {
var records = LinkedList<HexRecord>();
....
let data_line: HexRecord? = try parseRecord(line: line) // parseRecord convert String to HexRecord
if (data_line != nil)
{
records.enqueue(value: data_line!)
}
....
records.removeAll(); //Thread 1: EXC_BAD_ACCESS (code=2, address=0x16d0f3ff0)
} // Thread 1: EXC_BAD_ACCESS (code=2, address=0x16d0f3ff0) if there is no line records.removeAll();
With the debugger I see that the error occurs when assigning the value nil to self.head. Just before self.head has correct values, it becomes nil and the error is skipped before reaching the next instruction (within the removeAll function)
In the Debug Navigator, in the stackTrace the last 2 functions where the error is seen:
libobjc.A.dylib`_object_remove_assocations:
0x180d11eec <+0>: sub sp, sp, #0x70 ; =0x70
-> 0x180d11ef0 <+4>: stp x26, x25, [sp, #0x20] //Thread 1 error: EXC_BAD_ACCESS (code = 2, address = 0x16d0f3ff0)
0x180d11ef4 <+8>: stp x24, x23, [sp, #0x30]
libswiftCore.dylib`_swift_release_:
0x104e18d1c <+180>: bl 0x104e1a37c ; bool swift::RefCounts<swift::SideTableRefCountBits>::doDecrement<(swift::PerformDeinit)1>(unsigned int)
-> 0x104e18d20 <+184>: ldp x29, x30, [sp], #0x10. //Thread 1 error: EXC_BAD_ACCESS (code = 2, address = 0x16d0f3ff0)
0x104e18d24 <+188>: ret
Does someone have idea how to resolve it?
Thanks!

In my case, this error occurred when when I created a circular reference.
I created a Column object, and in the column initializer it counted out of how many columns were to be created. In order to count that list, that getter initialized an array of Columns.

It was solved by changing the removeAll method of the LinkedList, for the following:
public func removeAll() {
while head != nil {
removeTail()
}
}
public func removeTail() {
guard let tail = tail else {return}
if let prev = tail.previous {
prev.next = nil
self.tail = prev
} else {
self.head = nil
self.tail = nil
}
count -= 1
if count < 0 { count = 0}
}

Related

iOS- Chatto framework chat deletion

I have been using the Chatto framework for working in a chat application. Everything works fine. Now I want to delete a chat message from DataSource which is SlidingDataSource class. The indexing of the array is being handled with some properties like windowOffset itemsOffset windowCount along with the array's count. If anyone has used delete operation in Chatto, Please explain the properties or provide a simple function to delete will be helpful.
Thank you. I am attaching the data source code here..
import Foundation
import Chatto
public enum InsertPosition {
case top
case bottom
}
public class SlidingDataSource<Element> {
private var pageSize: Int
private var windowOffset: Int
private var windowCount: Int
private var itemGenerator: (() -> Element)?
private var items = [Element]()
private var itemsOffset: Int
public var itemsInWindow: [Element] {
let offset = self.windowOffset - self.itemsOffset
return Array(items[offset..<offset+self.windowCount])
}
public init(count: Int, pageSize: Int, itemGenerator: (() -> Element)?) {
self.windowOffset = count
self.itemsOffset = count
self.windowCount = 0
self.pageSize = pageSize
self.itemGenerator = itemGenerator
self.generateItems(min(pageSize, count), position: .top)
}
public convenience init(items: [Element], pageSize: Int) {
var iterator = items.makeIterator()
self.init(count: items.count, pageSize: pageSize) { iterator.next()! }
}
private func generateItems(_ count: Int, position: InsertPosition) {
// swiftlint:disable:next empty_count
guard count > 0 else { return }
guard let itemGenerator = self.itemGenerator else {
fatalError("Can't create messages without a generator")
}
for _ in 0..<count {
self.insertItem(itemGenerator(), position: .top)
}
}
public func insertItem(_ item: Element, position: InsertPosition) {
if position == .top {
self.items.insert(item, at: 0)
let shouldExpandWindow = self.itemsOffset == self.windowOffset
self.itemsOffset -= 1
if shouldExpandWindow {
self.windowOffset -= 1
self.windowCount += 1
}
} else {
let shouldExpandWindow = self.itemsOffset + self.items.count == self.windowOffset + self.windowCount
if shouldExpandWindow {
self.windowCount += 1
}
self.items.append(item)
}
}
public func hasPrevious() -> Bool {
return self.windowOffset > 0
}
public func hasMore() -> Bool {
return self.windowOffset + self.windowCount < self.itemsOffset + self.items.count
}
public func loadPrevious() {
let previousWindowOffset = self.windowOffset
let previousWindowCount = self.windowCount
let nextWindowOffset = max(0, self.windowOffset - self.pageSize)
let messagesNeeded = self.itemsOffset - nextWindowOffset
if messagesNeeded > 0 {
self.generateItems(messagesNeeded, position: .top)
}
let newItemsCount = previousWindowOffset - nextWindowOffset
self.windowOffset = nextWindowOffset
self.windowCount = previousWindowCount + newItemsCount
}
public func loadNext() {
guard !self.items.isEmpty else { return }
let itemCountAfterWindow = self.itemsOffset + self.items.count - self.windowOffset - self.windowCount
self.windowCount += min(self.pageSize, itemCountAfterWindow)
}
#discardableResult
public func adjustWindow(focusPosition: Double, maxWindowSize: Int) -> Bool {
assert(0 <= focusPosition && focusPosition <= 1, "")
guard 0 <= focusPosition && focusPosition <= 1 else {
assert(false, "focus should be in the [0, 1] interval")
return false
}
let sizeDiff = self.windowCount - maxWindowSize
guard sizeDiff > 0 else { return false }
self.windowOffset += Int(focusPosition * Double(sizeDiff))
self.windowCount = maxWindowSize
return true
}
#discardableResult
func replaceItem(withNewItem item: Element, where predicate: (Element) -> Bool) -> Bool {
guard let index = self.items.firstIndex(where: predicate) else { return false }
self.items[index] = item
return true
}
func contains(item: Element, where predicate: (Element) -> Bool ) -> Bool {
guard let _ = self.items.firstIndex(where: predicate) else { return false }
return true
}
//FIXME: Add delete method here, don't know the use off itemOffset, windowOffset, windowCount
// func delete(item: Element, where predicate: (Element) -> Bool ) {
// self.items.removeAll(where: predicate)
// }
}
I have raised a question in their Github repo. Here is the solution they answered.
when delete or add a new element in data source you need to -1 or +1 to offset. If offset is 0 - do nothing.
Originial answer link

Detect percentage of time main thread is used

I am trying to detect the percentage of time that the Main thread is busy so I can log this metric when a user is using the app. Currently, the closest thing I can find is the user_time from basic_info with the help from an answer here but how can i know what thread is being used and if its the main thread? Then from here how can i tell how much of that time as a percentage of the apps total run time for that session?
So i managed to figure this out using the following:
class MainThreadAnalyser {
typealias SumTotal = (total: Double, elements: Double)
private var threadPercentages = [Double]()
private let timeIntervalSeconds: Double
init(timeIntervalSeconds: Double) {
self.timeIntervalSeconds = timeIntervalSeconds
if #available(iOS 10.0, *) {
self.startCPUMonitoring(timeIntervalSeconds: self.timeIntervalSeconds)
}
}
func getAverageCpuUsage() -> Double? {
let sumTotal = threadPercentages.reduce((total: 0, elements: 0)) { (sum, item) -> SumTotal in
var result = sum
if item > 0 {
result.total += item
result.elements += 1
}
return result
}
return sumTotal.elements > 0 ? sumTotal.total / sumTotal.elements : nil
}
#available(iOS 10.0, *)
private func startCPUMonitoring(timeIntervalSeconds: Double) {
Timer.scheduledTimer(withTimeInterval: timeIntervalSeconds, repeats: true) { [weak self] _ in
guard let strongSelf = self else { return }
if let cpuUsage = strongSelf.cpuUsage() {
strongSelf.threadPercentages.append(cpuUsage)
}
}
}
private func cpuUsage() -> Double? {
var kernReturn: kern_return_t
var taskInfoCount: mach_msg_type_number_t
taskInfoCount = mach_msg_type_number_t(TASK_INFO_MAX)
var tinfo = [integer_t](repeating: 0, count: Int(taskInfoCount))
kernReturn = task_info(mach_task_self_, task_flavor_t(TASK_BASIC_INFO), &tinfo, &taskInfoCount)
if kernReturn != KERN_SUCCESS {
return -1
}
var threadArray: thread_act_array_t? = UnsafeMutablePointer(mutating: [thread_act_t]())
var threadCount: mach_msg_type_number_t = 0
defer {
if let threadArray = threadArray {
vm_deallocate(mach_task_self_, vm_address_t(UnsafePointer(threadArray).pointee), vm_size_t(threadCount))
}
}
kernReturn = task_threads(mach_task_self_, &threadArray, &threadCount)
if kernReturn != KERN_SUCCESS {
return -1
}
var totalCPU: Double?
if let threadArray = threadArray {
for index in 0 ..< Int(threadCount) {
var threadInfoCount = mach_msg_type_number_t(THREAD_INFO_MAX)
var thinfo = [integer_t](repeating: 0, count: Int(threadInfoCount))
kernReturn = thread_info(threadArray[index], thread_flavor_t(THREAD_BASIC_INFO),
&thinfo, &threadInfoCount)
if kernReturn != KERN_SUCCESS {
return -1
}
if index == 0 {
let cpuUse = thinfo[4]
totalCPU = Double(cpuUse/10)
}
}
}
return totalCPU
}
}
The main thread is being used constantly while the app is in the foreground.
So you can schedule a timer in applicationDidBecomeActive and invalidate in applicationWillResignActive and get the accumulated seconds whenever you want.

LinkedList in swift with node as structure

Can anyone tell me how to create a linked-list in swift with node as structure and linked-list as class.
I tried to create a node Node with reference to itself and faced a error "value type 'Node' cannot have a stored property that references itself"
for resolving it i created one more class Next
and now I am unable to proceed further.
You can not make node as a "struct" since Swift treats Struct and Enums as value types and Classes as reference type.
When you make the LinkedList Class you would very likely create a reference to your node structure. Now struct being a value type, capturing self for value types is dangerous practice and discouraged.
Therefore I would suggest you to create Node as Class and make use of the various access specifiers in Swift to achieve the abstraction you are trying to.
For more details on capturing self in value types you can refer to https://github.com/Wolox/ios-style-guide/blob/master/rules/avoid-struct-closure-self.md.
Details
Xcode 11.3.1, Swift 5.1
Base Interface
Nodeable protocol
import Foundation
protocol Nodeable: class {
associatedtype Value
var value: Value { get set }
var next: Self? { get set }
init(value: Value, next: Self?)
}
// MARK: Extensions
extension Nodeable where Self.Value: Equatable {
static func == (lhs: Self, rhs: Self) -> Bool { lhs.value == rhs.value }
}
extension Nodeable where Self: AnyObject {
var retainCount: Int { CFGetRetainCount(self as CFTypeRef) }
}
extension Nodeable where Self: CustomStringConvertible {
var description: String { return "{ value: \(value), next: \(next == nil ? "nill" : "exist") }" }
}
LinkedListable protocol
import Foundation
protocol LinkedListable where Node.Value == Value {
associatedtype Node: Nodeable
associatedtype Value
var firstNode: Node? { get set }
var lastNode: Node? { get set }
init()
}
extension LinkedListable {
var firstValue: Value? { return firstNode?.value }
var lastValue: Value? { return lastNode?.value }
var isEmpty: Bool { return firstNode == nil }
}
// MARK: Initializers
extension LinkedListable {
init(_ array: [Value]) {
self.init()
array.forEach { append(newLast: $0) }
}
init(copyValuesFrom linkedList: Self) {
self.init()
if linkedList.isEmpty { return }
linkedList.forEachNode { append(newLast: $0.value) }
}
init(copyReferencesFrom linkedList: Self) {
self.init()
firstNode = linkedList.firstNode
lastNode = linkedList.lastNode
}
}
// MARK: Iteration
extension LinkedListable {
func node(at index: Int) -> Node? {
if isEmpty { return nil }
var currentIndex = 0
var resultNode: Node?
forEachWhile {
if index == currentIndex { resultNode = $0; return false }
currentIndex += 1
return true
}
return resultNode
}
func forEachWhile(closure: (Node) -> (Bool)) {
var currentNode = self.firstNode
while currentNode != nil {
guard closure(currentNode!) else { return }
currentNode = currentNode?.next
}
}
func forEachNode(closure: (Node) -> ()) {
forEachWhile { closure($0); return true }
}
}
// MARK: Add/Get values
extension LinkedListable {
func value(at index: Int) -> Value? { node(at: index)?.value }
// MARK: Add new node to the end of list
mutating func append(newLast value: Value) {
let newNode = Node(value: value, next: nil)
if firstNode == nil {
firstNode = newNode
lastNode = firstNode
} else {
lastNode?.next = newNode
lastNode = lastNode?.next
}
}
}
LinkedListable protocol extensions
// MARK: CustomStringConvertible
extension LinkedListable where Self: CustomStringConvertible {
var description: String {
var values = [String]()
forEachNode { values.append("\($0.value)") }
return values.joined(separator: ", ")
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// MARK: ExpressibleByArrayLiteral
extension LinkedListable where Self: ExpressibleByArrayLiteral, ArrayLiteralElement == Value {
init(arrayLiteral elements: Self.ArrayLiteralElement...) { self.init(elements) }
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// MARK: Sequence
extension LinkedListable where Self: Sequence {
typealias Iterator = LinkedListableIterator<Node>
func makeIterator() -> LinkedListableIterator<Node> { return .init(firstNode) }
}
struct LinkedListableIterator<Node>: IteratorProtocol where Node: Nodeable {
private var currentNode: Node?
init(_ firstNode: Node?) { self.currentNode = firstNode }
mutating func next() -> Node.Value? {
let node = currentNode
currentNode = currentNode?.next
return node?.value
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// MARK: Collection
extension LinkedListable where Self: Collection, Self.Index == Int, Self.Element == Value {
var startIndex: Index { 0 }
var endIndex: Index {
guard !isEmpty else { return 0 }
var currentIndex = 0
forEachNode { _ in currentIndex += 1 }
return currentIndex
}
func index(after i: Index) -> Index { i+1 }
subscript(position: Index) -> Element { node(at: position)!.value }
var isEmpty: Bool { return firstNode == nil }
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
extension LinkedListable where Self: MutableCollection, Self.Index == Int, Self.Element == Value {
subscript(position: Self.Index) -> Self.Element {
get { return node(at: position)!.value }
set(newValue) { node(at: position)!.value = newValue }
}
}
Usage
implementation of a Node class
import Foundation
final class LinkedListNode<Value>: Nodeable {
var value: Value
var next: LinkedListNode?
init(value: Value, next: LinkedListNode?) {
self.value = value
self.next = next
}
}
extension LinkedListNode: Equatable, CustomStringConvertible where Value: Equatable {}
Implementation of a List class (option 1)
class BaseLinkedList<Value>: LinkedListable where Value: Equatable {
typealias Node = LinkedListNode<Value>
var firstNode: LinkedListNode<Value>?
weak var lastNode: LinkedListNode<Value>?
required init() { }
}
Manipulations with List class (option 1)
var linkedList = BaseLinkedList(["one", "two", "three"])
linkedList = BaseLinkedList(copyReferencesFrom: linkedList)
linkedList = BaseLinkedList(copyValuesFrom: linkedList)
var node = linkedList.firstNode!
print("node value: \(node.value) \(String(describing: node.next))")
node = linkedList.lastNode!
print("node value: \(node.value) \(String(describing: node.next))")
print("isEmpty: \(linkedList.isEmpty)")
linkedList.append(newLast: "four")
linkedList.forEachNode { print($0.value) }
linkedList.forEachNode { print($0.value) }
print("node at index 3: \(String(describing: linkedList.node(at: 3)))")
print("value at index 5: \(String(describing: linkedList.value(at: 4)))")
Implementation of a List class (option 2)
class LinkedList<Value>: BaseLinkedList<Value> where Value: Equatable {}
extension LinkedList: CustomStringConvertible, ExpressibleByArrayLiteral, Sequence, Collection, MutableCollection {}
Manipulations with List class (option 2)
var linkedList = LinkedList(arrayLiteral: "one", "two", "three")
print(linkedList)
print(linkedList.map { $0 + "!" })
print(linkedList.reduce("", { "\($0)_\($1)" }))
linkedList[2] = "five"
print(linkedList[2])
print(linkedList.count)
Some unit tests
import XCTest
// MARK: Test basic List functionality
class TestBasicList: XCTestCase {
typealias LinkedList = BaseLinkedList<Int>
// typealias Value = Int
private var linkedList: LinkedList!
private var possibleValues: [LinkedList.Value] { [1, 2, 3, 4] }
override func setUp() { linkedList = LinkedList() }
func testInitListFromArray() {
TestBasicList.assertCollectionsContainsSameValues(linkedList: LinkedList(possibleValues), array: possibleValues)
}
func testInitListByCopyingValuesFromAnotherList() {
linkedList = .init(possibleValues)
let copiedLinkedList = LinkedList(copyValuesFrom: linkedList)
assertCollections(linkedList1: linkedList, linkedList2: copiedLinkedList, containEqualValues: true)
assertCollections(linkedList1: linkedList, linkedList2: copiedLinkedList, containsSameReferencesToNodes: false)
}
func testInitListByCopyingElementsReferencesFromAnotherList() {
linkedList = .init(possibleValues)
let copiedLinkedList = LinkedList(copyReferencesFrom: linkedList)
assertCollections(linkedList1: linkedList, linkedList2: copiedLinkedList, containEqualValues: true)
assertCollections(linkedList1: linkedList, linkedList2: copiedLinkedList, containsSameReferencesToNodes: true)
}
func testPushFunctionality() {
possibleValues.forEach { linkedList.append(newLast: $0) }
TestBasicList.assertCollectionsContainsSameValues(linkedList: linkedList, array: possibleValues)
}
func testRandomAccess() {
linkedList = .init(possibleValues)
(0 ..< possibleValues.count).forEach {
XCTAssertEqual(possibleValues[$0], linkedList.node(at: $0)?.value)
}
}
private func assertCollections(linkedList1: LinkedList, linkedList2: LinkedList, containEqualValues: Bool) {
var values1 = [LinkedList.Value]()
linkedList1.forEachNode { values1.append($0.value) }
var values2 = [LinkedList.Value]()
linkedList2.forEachNode { values2.append($0.value) }
if containEqualValues {
XCTAssertEqual(values1, values2)
} else {
XCTAssertNotEqual(values1, values2)
}
}
private func assertCollections(linkedList1: LinkedList, linkedList2: LinkedList, containsSameReferencesToNodes: Bool) {
var values1 = [LinkedList.Node]()
linkedList1.forEachNode { values1.append($0) }
var values2 = [LinkedList.Node]()
linkedList2.forEachNode { values2.append($0) }
var areSame: Bool!
for i in 0 ..< values1.count {
areSame = values1[i] === values2[i]
if containsSameReferencesToNodes {
XCTAssertTrue(areSame)
} else {
XCTAssertFalse(areSame)
}
}
}
}
extension TestBasicList {
class func assertCollectionsContainsSameValues<List: LinkedListable>(linkedList: List, array: [List.Value]) where List.Value: Equatable {
var values = [List.Value]()
linkedList.forEachNode { values.append($0.value) }
XCTAssertEqual(values, array)
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// MARK: Sequence
class LinkedListSequence<Value>: BaseLinkedList<Value>, Sequence where Value: Equatable {}
protocol LinkedListSequenceTestable {
typealias Value = Int
typealias LinkedList = LinkedListSequence<Value>
var linkedList: LinkedList { get set }
var possibleValues: [Value] { get}
}
extension LinkedListSequenceTestable {
func _testFilter() {
XCTAssertEqual(linkedList.filter ({ $0 % 2 == 0 }),
possibleValues.filter({ $0 % 2 == 0 }))
}
func _testMap() {
guard let num = possibleValues.first else { return }
XCTAssertEqual(linkedList.map({ $0 + num}), possibleValues.map({ $0 + num}))
}
func _testCompactMap() {
let array1 = linkedList.compactMap { value -> String? in
if value % 2 != 0 { return "\(value)" }
return nil
}
let array2 = possibleValues.compactMap { value -> String? in
if value % 2 != 0 { return "\(value)" }
return nil
}
XCTAssertEqual(array1, array2)
}
func _testReduce() {
let result1 = linkedList.reduce(LinkedList.Element()) { $0 + $1 }
let result2 = possibleValues.reduce(LinkedList.Element()) { $0 + $1 }
XCTAssertEqual(result1, result2)
}
func _testForEach() {
var values1 = [LinkedList.Value]()
linkedList.forEach { values1.append($0) }
var values2 = [LinkedList.Value]()
possibleValues.forEach { values2.append($0) }
XCTAssertEqual(values1, values2)
}
}
class TestLinkedListSequence_nonEmpty: XCTestCase, LinkedListSequenceTestable {
var linkedList = LinkedList()
var possibleValues: [Value] { [1, 2, 3, 4] }
override func setUp() { linkedList = LinkedList(possibleValues) }
func testFilter() { _testFilter() }
func testMap() { _testMap() }
func testCompactMap() { _testCompactMap() }
func testReduce() { _testReduce() }
func testForEach() { _testForEach() }
}
class TestLinkedListSequence_oneElement: TestLinkedListSequence_nonEmpty {
override var possibleValues: [Value] { [1] }
}
class TestLinkedListSequence_empty: TestLinkedListSequence_nonEmpty {
override var possibleValues: [Value] { [] }
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// MARK: Collection
class LinkedListCollection<Value>: BaseLinkedList<Value>, Sequence, Collection where Value: Equatable {}
protocol LinkedListCollectionTestable {
associatedtype Value: Equatable
typealias LinkedList = LinkedListCollection<Value>
var linkedList: LinkedList { get set }
var possibleValues: [Value] { get}
}
extension LinkedListCollectionTestable {
func _testCount() {
XCTAssertEqual(linkedList.count, possibleValues.count)
}
func _testIsEmpty() {
XCTAssertEqual(linkedList.isEmpty, possibleValues.isEmpty)
XCTAssertEqual(LinkedList().isEmpty, [].isEmpty)
}
func _testIndexes() {
for i in 0 ..< linkedList.count {
XCTAssertEqual(linkedList.index(after: i), possibleValues.index(after: i))
}
}
}
class TestLinkedListCollection_nonEmpty: XCTestCase, LinkedListCollectionTestable {
typealias LinkedList = LinkedListCollection<Int>
var linkedList = LinkedList()
var possibleValues: [LinkedList.Value] { [1, 2, 3, 4] }
override func setUp() { linkedList = LinkedList(possibleValues) }
func testCount() { _testCount() }
func testIsEmpty() { _testIsEmpty() }
func testIndexes() { _testIndexes() }
}
class TestLinkedListCollection_oneElement: TestLinkedListCollection_nonEmpty {
override var possibleValues: [LinkedList.Value] { [1] }
}
class TestLinkedListCollection_empty: TestLinkedListCollection_nonEmpty {
override var possibleValues: [LinkedList.Value] { [] }
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// MARK: RangeReplaceableCollection
class LinkedListMutableCollection<Value>: BaseLinkedList<Value>, Sequence, Collection, MutableCollection where Value: Equatable & Comparable {}
protocol LinkedListMutableCollectionTestable {
associatedtype Value: Equatable & Comparable
typealias LinkedList = LinkedListMutableCollection<Value>
var linkedList: LinkedList { get set }
var possibleValues: [Value] { get}
}
extension LinkedListMutableCollectionTestable {
func _testSorted() {
XCTAssertEqual(linkedList.sorted(by: { $0 > $1 }),
possibleValues.sorted(by: { $0 > $1 }))
}
func _testSubscriptReading() {
for (index, value) in possibleValues.enumerated() {
XCTAssertEqual(linkedList[index], value)
}
}
func _testSubscriptWriting() {
var list = linkedList
var testArray = possibleValues
TestBasicList.assertCollectionsContainsSameValues(linkedList: linkedList, array: testArray)
for (index, value) in possibleValues.reversed().enumerated() {
testArray[index] = value
list[index] = value
XCTAssertEqual(linkedList[index], testArray[index])
}
print(testArray)
TestBasicList.assertCollectionsContainsSameValues(linkedList: linkedList, array: testArray)
}
}
class TestLinkedListMutableCollection_nonEmptyCollection: XCTestCase, LinkedListMutableCollectionTestable {
typealias LinkedList = LinkedListMutableCollection<Int>
var linkedList = LinkedList()
var possibleValues: [LinkedList.Value] { [1, 3, 2, 4] }
override func setUp() { linkedList = LinkedList(possibleValues) }
func testSorted() { _testSorted() }
func testSubscriptReading() { _testSubscriptReading() }
func testSubscriptWriting() { _testSubscriptWriting() }
}
class TestLinkedListMutableCollection_oneElement: TestLinkedListMutableCollection_nonEmptyCollection {
override var possibleValues: [LinkedList.Value] { [1] }
}
class TestLinkedListMutableCollection_empty: TestLinkedListMutableCollection_nonEmptyCollection {
override var possibleValues: [LinkedList.Value] { [] }
}
Custom LinkedList Type
Xcode 10.2.1, Swift 5.0
My LinkedList type implements all of the following protocols:
CustomStringConvertible
ExpressibleByArrayLiteral
Sequence
Collection
MutableCollection
RangeReplaceableCollection
BidirectionalCollection
As well, it keeps its node type private so the user never needs to know anything of its existence.
This implementation is a doubly linked list so to efficiently enable bidirectional traversal.
Code:
public struct LinkedList<Element> {
private var headNode: Node?
private var tailNode: Node?
public private(set) var count: Int = 0
private var id = ID()
public init() { }
fileprivate class ID {
init() { }
}
}
//MARK: - LinkedList Node
extension LinkedList {
fileprivate class Node {
public var value: Element
public var next: Node?
public weak var previous: Node?
public init(value: Element) {
self.value = value
}
}
}
//MARK: - Initializers
public extension LinkedList {
private init(_ nodeChain: (head: Node, tail: Node, count: Int)?) {
guard let chain = nodeChain else {
return
}
headNode = chain.head
tailNode = chain.tail
count = chain.count
}
init<S>(_ sequence: S) where S: Sequence, S.Element == Element {
if let linkedList = sequence as? LinkedList<Element> {
self = linkedList
} else {
self = LinkedList(chain(of: sequence))
}
}
}
//MARK: Chain of Nodes
extension LinkedList {
// Creates a chain of nodes from a sequence. Returns `nil` if the sequence is empty.
private func chain<S>(of sequence: S) -> (head: Node, tail: Node, count: Int)? where S: Sequence, S.Element == Element {
var iterator = sequence.makeIterator()
var head, tail: Node
var count = 0
guard let firstValue = iterator.next() else {
return nil
}
var currentNode = Node(value: firstValue)
head = currentNode
count = 1
while let nextElement = iterator.next() {
let nextNode = Node(value: nextElement)
currentNode.next = nextNode
nextNode.previous = currentNode
currentNode = nextNode
count += 1
}
tail = currentNode
return (head: head, tail: tail, count: count)
}
}
//MARK: - Copy Nodes
extension LinkedList {
private mutating func copyNodes(settingNodeAt index: Index, to value: Element) {
var currentIndex = startIndex
var currentNode = Node(value: currentIndex == index ? value : currentIndex.node!.value)
let newHeadNode = currentNode
currentIndex = self.index(after: currentIndex)
while currentIndex < endIndex {
let nextNode = Node(value: currentIndex == index ? value : currentIndex.node!.value)
currentNode.next = nextNode
nextNode.previous = currentNode
currentNode = nextNode
currentIndex = self.index(after: currentIndex)
}
headNode = newHeadNode
tailNode = currentNode
}
#discardableResult
private mutating func copyNodes(removing range: Range<Index>) -> Range<Index> {
id = ID()
var currentIndex = startIndex
while range.contains(currentIndex) {
currentIndex = index(after: currentIndex)
}
guard let headValue = currentIndex.node?.value else {
self = LinkedList()
return endIndex..<endIndex
}
var currentNode = Node(value: headValue)
let newHeadNode = currentNode
var newCount = 1
var removedRange: Range<Index> = Index(node: currentNode, offset: 0, id: id)..<Index(node: currentNode, offset: 0, id: id)
currentIndex = index(after: currentIndex)
while currentIndex < endIndex {
guard !range.contains(currentIndex) else {
currentIndex = index(after: currentIndex)
continue
}
let nextNode = Node(value: currentIndex.node!.value)
if currentIndex == range.upperBound {
removedRange = Index(node: nextNode, offset: newCount, id: id)..<Index(node: nextNode, offset: newCount, id: id)
}
currentNode.next = nextNode
nextNode.previous = currentNode
currentNode = nextNode
newCount += 1
currentIndex = index(after: currentIndex)
}
if currentIndex == range.upperBound {
removedRange = Index(node: nil, offset: newCount, id: id)..<Index(node: nil, offset: newCount, id: id)
}
headNode = newHeadNode
tailNode = currentNode
count = newCount
return removedRange
}
}
//MARK: - Computed Properties
public extension LinkedList {
var head: Element? {
return headNode?.value
}
var tail: Element? {
return tailNode?.value
}
}
//MARK: - Sequence Conformance
extension LinkedList: Sequence {
public typealias Element = Element
public __consuming func makeIterator() -> Iterator {
return Iterator(node: headNode)
}
public struct Iterator: IteratorProtocol {
private var currentNode: Node?
fileprivate init(node: Node?) {
currentNode = node
}
public mutating func next() -> Element? {
guard let node = currentNode else {
return nil
}
currentNode = node.next
return node.value
}
}
}
//MARK: - Collection Conformance
extension LinkedList: Collection {
public var startIndex: Index {
return Index(node: headNode, offset: 0, id: id)
}
public var endIndex: Index {
return Index(node: nil, offset: count, id: id)
}
public var first: Element? {
return head
}
public var isEmpty: Bool {
return count == 0
}
public func index(after i: Index) -> Index {
precondition(i.listID === self.id, "LinkedList index is invalid")
precondition(i.offset != endIndex.offset, "LinkedList index is out of bounds")
return Index(node: i.node?.next, offset: i.offset + 1, id: id)
}
public struct Index: Comparable {
fileprivate weak var node: Node?
fileprivate var offset: Int
fileprivate weak var listID: ID?
fileprivate init(node: Node?, offset: Int, id: ID) {
self.node = node
self.offset = offset
self.listID = id
}
public static func ==(lhs: Index, rhs: Index) -> Bool {
return lhs.offset == rhs.offset
}
public static func <(lhs: Index, rhs: Index) -> Bool {
return lhs.offset < rhs.offset
}
}
}
//MARK: - MutableCollection Conformance
extension LinkedList: MutableCollection {
public subscript(position: Index) -> Element {
get {
precondition(position.listID === self.id, "LinkedList index is invalid")
precondition(position.offset != endIndex.offset, "Index out of range")
guard let node = position.node else {
preconditionFailure("LinkedList index is invalid")
}
return node.value
}
set {
precondition(position.listID === self.id, "LinkedList index is invalid")
precondition(position.offset != endIndex.offset, "Index out of range")
// Copy-on-write semantics for nodes
if !isKnownUniquelyReferenced(&headNode) {
copyNodes(settingNodeAt: position, to: newValue)
} else {
position.node?.value = newValue
}
}
}
}
//MARK: LinkedList Specific Operations
public extension LinkedList {
mutating func prepend(_ newElement: Element) {
replaceSubrange(startIndex..<startIndex, with: CollectionOfOne(newElement))
}
mutating func prepend<S>(contentsOf newElements: __owned S) where S: Sequence, S.Element == Element {
replaceSubrange(startIndex..<startIndex, with: newElements)
}
#discardableResult
mutating func popFirst() -> Element? {
if isEmpty {
return nil
}
return removeFirst()
}
#discardableResult
mutating func popLast() -> Element? {
if isEmpty {
return nil
}
return removeLast()
}
}
//MARK: - BidirectionalCollection Conformance
extension LinkedList: BidirectionalCollection {
public var last: Element? {
return tail
}
public func index(before i: Index) -> Index {
precondition(i.listID === self.id, "LinkedList index is invalid")
precondition(i.offset != startIndex.offset, "LinkedList index is out of bounds")
if i.offset == count {
return Index(node: tailNode, offset: i.offset - 1, id: id)
}
return Index(node: i.node?.previous, offset: i.offset - 1, id: id)
}
}
//MARK: - RangeReplaceableCollection Conformance
extension LinkedList: RangeReplaceableCollection {
public mutating func append<S>(contentsOf newElements: __owned S) where S: Sequence, Element == S.Element {
replaceSubrange(endIndex..<endIndex, with: newElements)
}
public mutating func replaceSubrange<S, R>(_ subrange: R, with newElements: __owned S) where S: Sequence, R: RangeExpression, Element == S.Element, Index == R.Bound {
var range = subrange.relative(to: indices)
precondition(range.lowerBound.listID === id && range.upperBound.listID === id, "LinkedList range of indices are invalid")
precondition(range.lowerBound >= startIndex && range.upperBound <= endIndex, "Subrange bounds are out of range")
// If range covers all elements and the new elements are a LinkedList then set references to it
if range.lowerBound == startIndex, range.upperBound == endIndex, let linkedList = newElements as? LinkedList {
self = linkedList
return
}
var newElementsCount = 0
// There are no new elements, so range indicates deletion
guard let nodeChain = chain(of: newElements) else {
// If there is nothing in the removal range
// This also covers the case that the linked list is empty because this is the only possible range
guard range.lowerBound != range.upperBound else {
return
}
// Deletion range spans all elements
if range.lowerBound == startIndex && range.upperBound == endIndex {
headNode = nil
tailNode = nil
count = 0
return
}
// Copy-on-write semantics for nodes and remove elements in range
guard isKnownUniquelyReferenced(&headNode) else {
copyNodes(removing: range)
return
}
// Update count after mutation to preserve startIndex and endIndex validity
defer {
count = count - (range.upperBound.offset - range.lowerBound.offset)
}
// Move head up if deletion starts at start index
if range.lowerBound == startIndex {
// Can force unwrap node since the upperBound is not the end index
headNode = range.upperBound.node!
headNode!.previous = nil
// Move tail back if deletion ends at end index
} else if range.upperBound == endIndex {
// Can force unwrap since lowerBound index must have an associated element
tailNode = range.lowerBound.node!.previous
tailNode!.next = nil
// Deletion range is in the middle of the linked list
} else {
// Can force unwrap all bound nodes since they both must have elements
range.upperBound.node!.previous = range.lowerBound.node!.previous
range.lowerBound.node!.previous!.next = range.upperBound.node!
}
return
}
// Obtain the count of the new elements from the node chain composed from them
newElementsCount = nodeChain.count
// Replace entire content of list with new elements
if range.lowerBound == startIndex && range.upperBound == endIndex {
headNode = nodeChain.head
tailNode = nodeChain.tail
count = nodeChain.count
return
}
// Copy-on-write semantics for nodes before mutation
if !isKnownUniquelyReferenced(&headNode) {
range = copyNodes(removing: range)
}
// Update count after mutation to preserve startIndex and endIndex validity
defer {
count += nodeChain.count - (range.upperBound.offset - range.lowerBound.offset)
}
// Prepending new elements
guard range.upperBound != startIndex else {
headNode?.previous = nodeChain.tail
nodeChain.tail.next = headNode
headNode = nodeChain.head
return
}
// Appending new elements
guard range.lowerBound != endIndex else {
tailNode?.next = nodeChain.head
nodeChain.head.previous = tailNode
tailNode = nodeChain.tail
return
}
if range.lowerBound == startIndex {
headNode = nodeChain.head
}
if range.upperBound == endIndex {
tailNode = nodeChain.tail
}
range.lowerBound.node!.previous!.next = nodeChain.head
range.upperBound.node!.previous = nodeChain.tail
}
}
//MARK: - ExpressibleByArrayLiteral Conformance
extension LinkedList: ExpressibleByArrayLiteral {
public typealias ArrayLiteralElement = Element
public init(arrayLiteral elements: ArrayLiteralElement...) {
self.init(elements)
}
}
//MARK: - CustomStringConvertible Conformance
extension LinkedList: CustomStringConvertible {
public var description: String {
return "[" + lazy.map { "\($0)" }.joined(separator: ", ") + "]"
}
}
//MARK: - Equatable Conformance
extension LinkedList: Equatable where Element: Equatable {
public static func ==(lhs: LinkedList<Element>, rhs: LinkedList<Element>) -> Bool {
for (a, b) in zip(lhs, rhs) {
guard a == b else {
return false
}
}
return true
}
}
If you'd like to use this type fully-documented in your own project, feel free to download it or add it as a dependency with Swift PM by checking out my LinkedList GitHub repository.
This is not really a good question for Stack Overflow, but I will answer anyway. Here is a super basic implementation of a singly linked list:
class Node {
let value: Int
var next: Node?
init(value: Int, next: Node? = nil) {
self.value = value
self.next = next
}
}
class LinkedList {
let head: Node
init(node: Node) {
self.head = node
}
convenience init(nodeValue: Int) {
self.init(node: Node(value: nodeValue))
}
func addNode(node: Node) {
var current: Node = self.head
while current.next != nil {
current = current.next!
}
current.next = node
}
func addNode(withValue value: Int) {
self.addNode(node: Node(value: value))
}
}
let list = LinkedList(nodeValue: 4)
list.addNode(withValue: 3)
list.addNode(withValue: 8)
//The list is now [ 4 ]->[ 3 ]->[ 8 ]
Hopefully I can clarify a few points.
Can anyone tell me how to create a linked-list in swift with node as
structure and linked-list as class.
The node essentially is the structure. As other people have pointed out, a linked list is nothing more than a very basic data type (often called a Node) that holds a value and a reference to another Node.
The code posted above is a linked list:
class Node {
let value: Int
var next: Node?
init(value: Int, next: Node? = nil) {
self.value = value
self.next = next
}
}
Think of a link in a chain. This is your Node.
Think of a couple of links together. This is your linked list.
My point here is that there is nothing additional. By having the ability to make a single Node, you have the ability to make a linked list (just a bunch of Nodes connected).
I tried to create a node Node with reference to itself and faced a
error "value type 'Node' cannot have a stored property that references
itself"
Others have explained why this won't work.
for resolving it i created one more class Next and now I am unable to
proceed further.
Please don't do this. Your next node is just another Node. This is completely unnecessary.
Sometimes you will see a linked list class that holds a Node. This is just to help you manipulate the list a little easier. So when you say
linked-list as class
I'm pretty sure you're just referring to a collection of functions that help manipulate your list. These can just as easily be standalone functions that take a Node and operate on it.
For instance to add a link to the chain you can have a function add(value: Value, to list: Node). A function like this may or may not exist on some arbitrary LinkedList class. It often does but probably should not.
func append(_ node: Node, to list: Node) {
var current = list
while let nextNode = current.next {
current = nextNode
}
current.next = node
}
Hope this helps!
Checked on XCode 10 playground - Swift 4.2
class Node {
let value: Int
var next: Node?
init(value: Int, next: Node? = nil) {
self.value = value
self.next = next
}
}
class LinkedList {
let head: Node
init(node: Node) {
self.head = node
}
convenience init(nodeValue: Int) {
self.init(node: Node(value: nodeValue))
}
func addNode(node: Node) {
var current: Node = self.head
while current.next != nil {
current = current.next!
}
current.next = node
}
func addNode(withValue value: Int) {
self.addNode(node: Node(value: value))
}
func traverse() -> [Int]{
var results: [Int] = []
var current: Node = self.head
while current.next != nil {
current = current.next!
results.append(current.value)
}
return results
}
}
let list = LinkedList(nodeValue: 4)
list.addNode(withValue: 3)
list.addNode(withValue: 8)
list.addNode(withValue: 8)
list.addNode(withValue: 8)
list.addNode(withValue: 8)
list.traverse()
A workaround that I can think of is to describe the linked list node as a protocol and then create a struct that confirms that protocol
protocol LinkedNode {
var value: Int { get }
var next: LinkedListNode? { get }
}
struct Node: LinkedNode {
let value: Int
let next: LinkedListNode?
}
let linkedList = Node(value: 2, next: Node(value: 4, next: nil))

Recursive n Queens on nxn chess board implementation in Swift

I am trying to create a recursive Swift implementation for the solution of the classic puzzle: "How can we distribute n queens on a chess grid of n × n so that no queen can threaten another".
With existing code I encountered the following problems:
Code does not produce all the solutions for n<=8
Code does not product ANY solution for n>=9
Can't seem to compare solutions for n=8 (8x8) and larger because I compute the hash for each Solution class (board) by shifting bits which represent existence of queen or empty tile:
public override var hash: Int {
var hash = 0
for i in 0...self.board.count-1 {
for j in 0...self.board.count-1 {
if self.board[i][j].state == .Queen {
hash |= 1
hash <<= 1
} else {
hash <<= 1
}
}
}
return hash
}
when board is >8x8 value gets corrupted as it is larger than 64 bits (swift Int is Int64). What's a good solution for that?
My current code:
import UIKit
public typealias Board = Array<Array<Cell>>
#objc protocol QueenPlacementDelegate : class {
func solutionsFound(numOfSolutions : Int)
}
class QueenPlacement: NSObject {
var boardView : TTTBoardView?
var boardSize : Int = 0
var solutions : Set<Solution>?
weak var delegate : QueenPlacementDelegate?
private var startCondX : Int = 0
private var startCondY : Int = 0
func start() {
if boardSize == 0 {
print("Board size was not initialized")
return
}
self.solutions = Set<Solution>()
var done = false
self.startCondX = 0; self.startCondY = 0;
while (!done) {
let solution = Solution(boardSize: self.boardSize)
let board = solution.board
self.placeQueen(startCondX, yLoc: startCondY, board: board)
let solutionBoard = self.findSolutionForBoard(board)
if self.numOfQueensOnBoard(solutionBoard) == self.boardSize {
print("solution found")
solution.board = solutionBoard
self.solutions!.insert(solution)
}
done = self.advanceStartConditionsAndCheckIfDone()
if (done) {
if self.solutions!.count > 0 {
self.delegate!.solutionsFound(self.solutions!.count)
}
}
}
}
func advanceStartConditionsAndCheckIfDone() -> Bool {
startCondX++
if startCondX >= self.boardSize {
startCondX = 0
startCondY++
if startCondY >= self.boardSize {
return true
}
}
return false
}
func placeQueen(xLoc : Int, yLoc : Int, board : Board) {
board[xLoc][yLoc].state = .Queen
}
func findSolutionForBoard(board : Board) -> Board
{
let queensPlaced = self.numOfQueensOnBoard(board)
if queensPlaced == self.boardSize {
return board
}
else
{
for i in 0...self.boardSize-1 {
for j in 0...self.boardSize-1 {
if self.canPlaceQueen(xLoc: i, yLoc: j, board: board) {
self.placeQueen(i, yLoc: j, board: board)
}
}
}
let newQueensPlaced = self.numOfQueensOnBoard(board)
// recursion exit conditions: could not place any new queen
if newQueensPlaced > queensPlaced {
self.findSolutionForBoard(board)
} else {
return board
}
}
return board
}
func numOfQueensOnBoard(board : Board) -> Int {
var queensPlaced = 0
for i in 0...self.boardSize-1 {
for j in 0...self.boardSize-1 {
if board[i][j].state == .Queen {
queensPlaced++
}
}
}
return queensPlaced
}
func canPlaceQueen(xLoc xLoc : Int, yLoc : Int, board: Board) -> Bool {
for i in 0...self.boardSize-1 {
if board[i][yLoc].state == .Queen {
return false;
}
if board[xLoc][i].state == .Queen {
return false;
}
}
var x : Int
var y : Int
x = xLoc; y = yLoc;
while ++x < self.boardSize && ++y < self.boardSize {
if board[x][y].state == .Queen {
return false
}
}
x = xLoc; y = yLoc;
while --x >= 0 && ++y < self.boardSize {
if board[x][y].state == .Queen {
return false
}
}
x = xLoc; y = yLoc;
while ++x < self.boardSize && --y >= 0 {
if board[x][y].state == .Queen {
return false
}
}
x = xLoc; y = yLoc;
while --x >= 0 && --y >= 0 {
if board[x][y].state == .Queen {
return false
}
}
return true
}
// singleton!
static let sharedInstance = QueenPlacement()
private override init() {}
}
What is wrong here?
P.S.
for easier reading - full code repo can be found here
It's not an answer in a way that I don't know what is the problem with your version, but here is another one (looks working as I tested it), a little bit simplier (based on Scala By Example - The N-Queens Problem).
func queens(n: Int) -> [[Int]] {
guard n > 3 else {
return [[Int]]()
}
func placeQueens(k: Int) -> [[Int]] {
guard k > 0 else {
return [[-1]] //stupid hack to let the app go to the for-loop in the * marked place
}
var res = [[Int]]()
for var q in placeQueens(k - 1) { //* marked place
if let first = q.first where first == -1 { //this is for removing the hacky -1
q.removeAll()
}
for column in 1...n {
if isSafe(column, queens: q) {
var solution = q
solution.append(column)
res.append(solution)
}
}
}
return res
}
return placeQueens(n)
}
func isSafe(column: Int, queens: [Int]) -> Bool {
for (index, q) in queens.enumerate() {
let dy = (index + 1) - (queens.count + 1)
let dx = q - column
let isDiagonal = dy * dy == dx * dx
if q == column || isDiagonal {
return false
}
}
return true
}
And if you want to draw the solutions out:
func drawTable(table: [Int]) -> String {
var res = ""
table.forEach {
for column in 1...table.count {
if $0 == column {
res += "X "
} else {
res += ". "
}
}
res += "\n"
}
return res
}
And
queens(4).forEach {
print(drawTable($0))
}
Computing the 73712 solutions of n = 13 took some minutes, above that you would probably run out of memory this way.

Queue implementation in Swift language

I m trying to implement Queue collection type in Swift platform. I have got some problems about peek, poll and offer functions. When I try to use these functions in my code, it fails. Do you have any advice or true algorithm for that?
import Foundation
class Node<T> {
var value: T? = nil
var next: Node<T>? = nil
var prev: Node<T>? = nil
init() {
}
init(value: T) {
self.value = value
}
}
class Queue<T> {
var count: Int = 0
var head: Node<T> = Node<T>()
var tail: Node<T> = Node<T>()
var currentNode : Node<T> = Node<T>()
init() {
}
func isEmpty() -> Bool {
return self.count == 0
}
func next(index:Int) -> T? {
if isEmpty() {
return nil
} else if self.count == 1 {
var temp: Node<T> = currentNode
return temp.value
} else if index == self.count{
return currentNode.value
}else {
var temp: Node<T> = currentNode
currentNode = currentNode.next!
return temp.value
}
}
func setCurrentNode(){
currentNode = head
}
func enQueue(key: T) {
var node = Node<T>(value: key)
if self.isEmpty() {
self.head = node
self.tail = node
} else {
node.next = self.head
self.head.prev = node
self.head = node
}
self.count++
}
func deQueue() -> T? {
if self.isEmpty() {
return nil
} else if self.count == 1 {
var temp: Node<T> = self.tail
self.count--
return temp.value
} else {
var temp: Node<T> = self.tail
self.tail = self.tail.prev!
self.count--
return temp.value
}
}
//retrieve the top most item
func peek() -> T? {
if isEmpty() {
return nil
}
return head.value!
}
func poll() -> T? {
if isEmpty() {
return nil
}else{
var temp:T = head.value!
deQueue()
return temp
}
}
func offer(var key:T)->Bool{
var status:Bool = false;
self.enQueue(key)
status = true
return status
}
}
Aside from the bugs, there are a couple of things about your implementation that you probably want to change to make it more Swift-like. One is it looks like you're replicating the Java names like poll and offer – these names are (IMHO) a little strange, and partly related to needing to have two functions, an exception-throwing version and a non-exception version. Since Swift doesn't have exceptions, you can probably just name them using the conventional names other Swift collections use, like append.
The other issue is that your implementation incorporates traversing the queue into the queue itself. It's better to do this kind of traversal outside the collection than mix the two. Swift collections do this with indexes.
Here's a possible Swift-like queue implementation. First, the node and base queue definition:
// singly rather than doubly linked list implementation
// private, as users of Queue never use this directly
private final class QueueNode<T> {
// note, not optional – every node has a value
var value: T
// but the last node doesn't have a next
var next: QueueNode<T>? = nil
init(value: T) { self.value = value }
}
// Ideally, Queue would be a struct with value semantics but
// I'll leave that for now
public final class Queue<T> {
// note, these are both optionals, to handle
// an empty queue
private var head: QueueNode<T>? = nil
private var tail: QueueNode<T>? = nil
public init() { }
}
Then, extend with an append and dequeue method:
extension Queue {
// append is the standard name in Swift for this operation
public func append(newElement: T) {
let oldTail = tail
self.tail = QueueNode(value: newElement)
if head == nil { head = tail }
else { oldTail?.next = self.tail }
}
public func dequeue() -> T? {
if let head = self.head {
self.head = head.next
if head.next == nil { tail = nil }
return head.value
}
else {
return nil
}
}
}
At this point, you're almost done if all you want to do is add and remove. To add traversal, first create an index type, which is a simple wrapper on the node type:
public struct QueueIndex<T>: ForwardIndexType {
private let node: QueueNode<T>?
public func successor() -> QueueIndex<T> {
return QueueIndex(node: node?.next)
}
}
public func ==<T>(lhs: QueueIndex<T>, rhs: QueueIndex<T>) -> Bool {
return lhs.node === rhs.node
}
Then, use this index to conform to MutableCollectionType:
extension Queue: MutableCollectionType {
public typealias Index = QueueIndex<T>
public var startIndex: Index { return Index(node: head) }
public var endIndex: Index { return Index(node: nil) }
public subscript(idx: Index) -> T {
get {
precondition(idx.node != nil, "Attempt to subscript out of bounds")
return idx.node!.value
}
set(newValue) {
precondition(idx.node != nil, "Attempt to subscript out of bounds")
idx.node!.value = newValue
}
}
typealias Generator = IndexingGenerator<Queue>
public func generate() -> Generator {
return Generator(self)
}
}
From conforming to collection type, you get a whole load of stuff for free:
var q = Queue<String>()
q.append("one")
q.append("two")
for x in q {
println(x)
}
isEmpty(q) // returns false
first(q) // returns Optional("one")
count(q) // returns 2
",".join(q) // returns "one,two"
let x = find(q, "two") // returns index of second entry
let counts = map(q) { count($0) } // returns [3,3]
Finally, there's 3 more protocols that are good to conform to: ExtensibleCollectionType, Printable and ArrayLiteralConvertible:
// init() and append() requirements are already covered
extension Queue: ExtensibleCollectionType {
public func reserveCapacity(n: Index.Distance) {
// do nothing
}
public func extend<S : SequenceType where S.Generator.Element == T>
(newElements: S) {
for x in newElements {
self.append(x)
}
}
}
extension Queue: ArrayLiteralConvertible {
public convenience init(arrayLiteral elements: T...) {
self.init()
// conformance to ExtensibleCollectionType makes this easy
self.extend(elements)
}
}
extension Queue: Printable {
// pretty easy given conformance to CollectionType
public var description: String {
return "[" + ", ".join(map(self,toString)) + "]"
}
}
These mean you can now create queues as easily arrays or sets:
var q: Queue = [1,2,3]
println(q) // prints [1, 2, 3]
There are a lot of little issues regarding the internal consistency of your model:
When you first instantiate a new Queue, you are initializing head, tail and current to three different Node objects (even though nothing's been queued yet!). That doesn't make sense. Personally, I'd be inclined to make those three properties optional and leave them as nil until you start enqueuing stuff.
By the way, when you start using optionals for these properties, many of the other methods are simplified.
It looks like you're trying to implement a doubly linked list. So, when you dequeue, you need to not only update the Queue properties, but you also need to update the next pointer for the next item that will be dequeued (because it still will be pointing to that item you already dequeued). You don't want your linked list maintaining references to objects that have been dequeued and should be removed.
When you dequeue the last item, you really should be clearing out head and tail references.
You're implementing a doubly linked list, without regard to the object ownership model. Thus, as soon as you have more than one item in your list, you've got a strong reference cycle between nodes and if not remedied, this will leak if there are still objects in the queue when the queue, itself, is deallocated. Consider making one of the references weak or unowned.
I'd suggest keeping this simple (just enqueue and dequeue). The concept of poll and offer may make sense in terms of an arbitrary linked list, but not in the context of a queue. The implementations of poll and offer are also incorrect (e.g. poll calls deQueue which removes the tail, but the object you return is the head!), but I presume you'd just remove these functions altogether. Likewise, I do not understand the intent of current in the context of a queue.
I'd suggest you make Queue and Node conform to Printable. It will simplify your debugging process.
The following is code of a playground consisting of a queue implemented with an array and a queue implemented with nodes. There are substantial performance differences between the two but if you going to be iterating through a queue you might want to use one with an array.
import UIKit // for NSDate() used in testing)
// QUEUE WITH ARRAY IMPLEMENTATION (For ease of adaptibility, slow enque, faster deque):
struct QueueArray<T> {
private var items = [T]()
mutating func enQueue(item: T) {
items.append(item)
}
mutating func deQueue() -> T? {
return items.removeFirst()
}
func isEmpty() -> Bool {
return items.isEmpty
}
func peek() -> T? {
return items.first
}
}
// QUEUE WITH NODE IMPLEMENTATION (For performance, if all you need is a queue this is it):
class QNode<T> {
var value: T
var next: QNode?
init(item:T) {
value = item
}
}
struct Queue<T> {
private var top: QNode<T>!
private var bottom: QNode<T>!
init() {
top = nil
bottom = nil
}
mutating func enQueue(item: T) {
let newNode:QNode<T> = QNode(item: item)
if top == nil {
top = newNode
bottom = top
return
}
bottom.next = newNode
bottom = newNode
}
mutating func deQueue() -> T? {
let topItem: T? = top?.value
if topItem == nil {
return nil
}
if let nextItem = top.next {
top = nextItem
} else {
top = nil
bottom = nil
}
return topItem
}
func isEmpty() -> Bool {
return top == nil ? true : false
}
func peek() -> T? {
return top?.value
}
}
// QUEUE NODES TEST
let testAmount = 100
var queueNodes = Queue<Int>()
let queueNodesEnqueStart = NSDate()
for i in 0...testAmount {
queueNodes.enQueue(i)
}
let queueNodesEnqueEnd = NSDate()
while !queueNodes.isEmpty() {
queueNodes.deQueue()
}
let queueNodesDequeEnd = NSDate()
// QUEUE ARRAY TEST
var queueArray = QueueArray<Int>()
let queueArrayEnqueStart = NSDate()
for i in 0...testAmount {
queueArray.enQueue(i)
}
let queueArrayEnqueEnd = NSDate()
while !queueArray.isEmpty() {
queueArray.deQueue()
}
let queueArrayDequeEnd = NSDate()
// QUEUE NODES RESULT:
print("queueEnqueDuration: \(queueNodesEnqueEnd.timeIntervalSinceDate(queueNodesEnqueStart)), Deque: \(queueNodesDequeEnd.timeIntervalSinceDate(queueNodesEnqueEnd))")
// QUEUE ARRAY RESULT:
print("queueArrayEnqueDuration: \(queueArrayEnqueEnd.timeIntervalSinceDate(queueArrayEnqueStart)), Deque: \(queueArrayDequeEnd.timeIntervalSinceDate(queueArrayEnqueEnd))")
Queue with Array
struct Queue<T> {
private var list = [T]()
var isEmpty: Bool { return self.list.isEmpty }
var front: T? { return self.list.first }
mutating func enqueue(_ item: T) {
self.list.append(item)
}
mutating func dequeue() -> T? {
guard self.isEmpty == false else { return nil }
return self.list.removeFirst()
}
}
Swift 4 simple Stack for any type; string, int, array, etc.
struct Stack<Element> {
var items = [Element]()
mutating func push(_ item: Element) {
items.append(item)
}
mutating func pop() -> Element {
return items.removeLast()
}
mutating func peek() -> Element {
return items.last!
}
mutating func pushFirst(_ item: Element) {
items.insert(item, at: 0)
}
}
example with strings:
let names = ["Bob", "Sam", "Sue", "Greg", "Brian", "Dave"]
//create stack of string type
var stackOfStrings = Stack<String>()
//add to bottom of stack
for stringName in names {
stackOfStrings.push(stringName)
}
//print and remove from stack
for stringName in names {
print(stringName)
stackOfStrings.pop(stringName)
}
//add to top of stack
for stringName in names {
stackOfStrings.pushFirst(stringName)
}
//look at item in stack without pop
for stringName in names {
//see what Top item is without remove
let whatIsTopItem = stackOfStrings.peek(stringName)
if whatIsTopItem == "Bob" {
print("Best friend Bob is in town!")
}
}
//stack size
let stackCount = stackOfStrings.items.count
more info here:
https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Generics.html

Resources