How to resolve the algorithm Recaman's sequence step by step in the Scala programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Recaman's sequence step by step in the Scala programming language

Table of Contents

Problem Statement

The Recamán's sequence generates Natural numbers. Starting from a(0)=0, the n'th term a(n), where n>0, is the previous term minus n i.e a(n) = a(n-1) - n but only if this is both positive and has not been previousely generated. If the conditions don't hold then a(n) = a(n-1) + n.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Recaman's sequence step by step in the Scala programming language

Source code in the scala programming language

import scala.collection.mutable

object RecamansSequence extends App {
  val (a, used) = (mutable.ArrayBuffer[Int](0), mutable.BitSet())
  var (foundDup, hop, nUsed1000) = (false, 1, 0)

  while (nUsed1000 < 1000) {
    val _next = a(hop - 1) - hop
    val next = if (_next < 1 || used.contains(_next)) _next + 2 * hop else _next
    val alreadyUsed = used.contains(next)

    a += next
    if (!alreadyUsed) {
      used.add(next)
      if (next <= 1000) nUsed1000 += 1
    }
    if (!foundDup && alreadyUsed) {
      println(s"The first duplicate term is a($hop) = $next")
      foundDup = true
    }
    if (nUsed1000 == 1000)
      println(s"Terms up to $hop are needed to generate 0 to 1000")

    hop += 1
  }

  println(s"The first 15 terms of the Recaman sequence are : ${a.take(15)}")

}


  

You may also check:How to resolve the algorithm Handle a signal step by step in the AutoHotkey programming language
You may also check:How to resolve the algorithm Nested function step by step in the FreeBASIC programming language
You may also check:How to resolve the algorithm Hello world/Text step by step in the IBM Z HL/ASM programming language
You may also check:How to resolve the algorithm Wireworld step by step in the Go programming language
You may also check:How to resolve the algorithm Update a configuration file step by step in the J programming language