How to resolve the algorithm Fibonacci word step by step in the Swift programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Fibonacci word step by step in the Swift programming language

Table of Contents

Problem Statement

The   Fibonacci Word   may be created in a manner analogous to the   Fibonacci Sequence   as described here:

Perform the above steps for     n = 37. You may display the first few but not the larger values of   n. {Doing so will get the task's author into trouble with them what be (again!).} Instead, create a table for   F_Words   1   to   37   which shows:

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Fibonacci word step by step in the Swift programming language

Source code in the swift programming language

import Foundation

struct Fib: Sequence, IteratorProtocol {
  private var cur: String
  private var nex: String

  init(cur: String, nex: String) {
    self.cur = cur
    self.nex = nex
  }

  mutating func next() -> String? {
    let ret = cur

    cur = nex
    nex = "\(ret)\(nex)"

    return ret
  }
}

func getEntropy(_ s: [Int]) -> Double {
  var entropy = 0.0
  var hist = Array(repeating: 0.0, count: 256)

  for i in 0..<s.count {
    hist[s[i]] += 1
  }

  for i in 0..<256 where hist[i] > 0 {
    let rat = hist[i] / Double(s.count)
    entropy -= rat * log2(rat)
  }

  return entropy
}

for (i, str) in Fib(cur: "1", nex: "0").prefix(37).enumerated() {
  let ent = getEntropy(str.map({ Int($0.asciiValue!) }))

  print("i: \(i) len: \(str.count) entropy: \(ent)")
}


  

You may also check:How to resolve the algorithm Sorting algorithms/Permutation sort step by step in the Factor programming language
You may also check:How to resolve the algorithm Move-to-front algorithm step by step in the F# programming language
You may also check:How to resolve the algorithm 24 game step by step in the Falcon programming language
You may also check:How to resolve the algorithm Apply a callback to an array step by step in the Maxima programming language
You may also check:How to resolve the algorithm Digital root step by step in the Haskell programming language