How to resolve the algorithm McNuggets problem step by step in the Kotlin programming language

Published on 22 June 2024 08:30 PM

How to resolve the algorithm McNuggets problem step by step in the Kotlin programming language

Table of Contents

Problem Statement

Calculate (from 0 up to a limit of 100) the largest non-McNuggets number (a number n which cannot be expressed with 6x + 9y + 20z = n where x, y and z are natural numbers).

Let's start with the solution:

Step by Step solution about How to resolve the algorithm McNuggets problem step by step in the Kotlin programming language

The provided Kotlin code determines the maximum non-McNuggets number up to a certain limit. A McNuggets number is a number that can be formed using only 6, 9, and 20 as factors.

Here's how the code works:

  1. It initializes a Boolean array sv of size limit + 1, where limit is the maximum number to check. Initially, all elements in sv are set to false.

  2. It iterates through three nested loops to populate sv. For each combination of factors (6, 9, and 20), it checks if the resulting number (e.g., 6, 9, 12, 15, ...) is within the limit. If it is, it sets the corresponding element in sv to true.

  3. After populating sv, it starts another loop that iterates in reverse order from limit down to 0.

  4. For each number i in the reverse loop, it checks if sv[i] is false. If it is, it means that i cannot be formed using the factors 6, 9, and 20. Therefore, it prints that i is the maximum non-McNuggets number and terminates the program.

  5. If the loop completes without finding a non-McNugget number, it means that all numbers up to limit can be formed using the given factors. In that case, it doesn't print anything.

In the main function, it calls mcnugget(100) to find the maximum non-McNuggets number up to 100. The output will be "Maximum non-McNuggets number is 43".

Source code in the kotlin programming language

// Version 1.2.71

fun mcnugget(limit: Int) {
    val sv = BooleanArray(limit + 1)  // all false by default
    for (s in 0..limit step 6)
        for (n in s..limit step 9)
            for (t in n..limit step 20) sv[t] = true

    for (i in limit downTo 0) {
        if (!sv[i]) {
            println("Maximum non-McNuggets number is $i")
            return
        }
    }
}

fun main(args: Array<String>) {
    mcnugget(100)
}


  

You may also check:How to resolve the algorithm Read entire file step by step in the Scala programming language
You may also check:How to resolve the algorithm Smith numbers step by step in the MAD programming language
You may also check:How to resolve the algorithm Determine if a string is collapsible step by step in the BQN programming language
You may also check:How to resolve the algorithm Index finite lists of positive integers step by step in the 11l programming language
You may also check:How to resolve the algorithm Singleton step by step in the Kotlin programming language