Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,940 questions

51,877 answers

573 users

How to shift letters in a string x times by giving a slice of shifts in Scala

1 Answer

0 votes
object ShiftLettersProgram {

  /*
   string = "aaa"
   After shifting the first 1 letter by 1 = "baa"
   After shifting the first 2 letters by 2 = "dca"
   After shifting the first 3 letters by 3 = "gfd"
   result = "gfd"
  */

  def shiftLetters(str: String, shifts: Array[Int]): String = {
    val size = shifts.length
    val arr = str.toCharArray

    for (i <- (0 until size).reverse) {
      if (i + 1 < size) {
        shifts(i) += shifts(i + 1)
      }

      shifts(i) = shifts(i) % 26

      var asciiCode = str.charAt(i).toInt - 'a'.toInt
      asciiCode = asciiCode + shifts(i)

      if (asciiCode > 25) {
        asciiCode = asciiCode - 26
      }

      arr(i) = ('a'.toInt + asciiCode).toChar
    }

    arr.mkString
  }

  def main(args: Array[String]): Unit = {
    var str = "aaa"
    val shifts = Array(1, 2, 3)

    str = shiftLetters(str, shifts)

    println(str)
  }
}




/*
run:

gfd

*/

 



answered Dec 4, 2025 by avibootz

Related questions

...