skip to Main Content

I have trying to get the result of the 3 random number using random operators. This is what have done so far. Could anyone explain or show how i can do this

fun rightEquation(){

        var num5 = 1 + generator.nextInt(20)
        var num6 = 1 + generator.nextInt(20)
        var num7 = 1 + generator.nextInt(20)
        var num8 = 1 + generator.nextInt(20)

        var total = mutableListOf<String>()

        eq5 = "(" + num5 + "" + operation() + "" + num6 + ")" + operation() + "" + num7

    }

 fun operation(): String {

        return when (generator.nextInt(4)){
            0 -> "-"
            1 -> "+"
            2 -> "/"
            3 -> "*"
            else ->""
        }

2

Answers


  1. Since Kotlin 1.3, there’s a built-in method to fetch a random item from a list: random()

    fun rightEquation(): String {
      return "(${randomNumber()}${randomOperator()}${randomNumber()})${randomOperator()}${randomNumber()}"
    }    
    
    fun randomOperator(): String {
      val operators = listOf("-", "+", "/", "*")
      return operators.random()
    }
    
    fun randomNumber(): String {
       val number = 1 + generator.nextInt(20)
       return number.toString()
    }
    
    Login or Signup to reply.
  2. This will generate an equation and calculate the result of it:

    fun evaluate(str: String): Double {
    
      data class Data(val rest: List<Char>, val value: Double)
    
      return object : Any() {
    
        fun parse(chars: List<Char>): Double {
          return getExpression(chars.filter { it != ' ' })
            .also { if (it.rest.isNotEmpty()) throw RuntimeException("Unexpected character: ${it.rest.first()}") }
            .value
        }
    
        private fun getExpression(chars: List<Char>): Data {
          var (rest, carry) = getTerm(chars)
          while (true) {
            when {
              rest.firstOrNull() == '+' -> rest = getTerm(rest.drop(1)).also { carry += it.value }.rest
              rest.firstOrNull() == '-' -> rest = getTerm(rest.drop(1)).also { carry -= it.value }.rest
              else                      -> return Data(rest, carry)
            }
          }
        }
    
        fun getTerm(chars: List<Char>): Data {
          var (rest, carry) = getFactor(chars)
          while (true) {
            when {
              rest.firstOrNull() == '*' -> rest = getTerm(rest.drop(1)).also { carry *= it.value }.rest
              rest.firstOrNull() == '/' -> rest = getTerm(rest.drop(1)).also { carry /= it.value }.rest
              else                      -> return Data(rest, carry)
            }
          }
        }
    
        fun getFactor(chars: List<Char>): Data {
          return when (val char = chars.firstOrNull()) {
            '+'              -> getFactor(chars.drop(1)).let { Data(it.rest, +it.value) }
            '-'              -> getFactor(chars.drop(1)).let { Data(it.rest, -it.value) }
            '('              -> getParenthesizedExpression(chars.drop(1))
            in '0'..'9', ',' -> getNumber(chars)
            else             -> throw RuntimeException("Unexpected character: $char")
          }
        }
    
        fun getParenthesizedExpression(chars: List<Char>): Data {
          return getExpression(chars)
            .also { if (it.rest.firstOrNull() != ')') throw RuntimeException("Missing closing parenthesis") }
            .let { Data(it.rest.drop(1), it.value) }
        }
    
        fun getNumber(chars: List<Char>): Data {
          val s = chars.takeWhile { it.isDigit() || it == '.' }.joinToString("")
          return Data(chars.drop(s.length), s.toDouble())
        }
    
      }.parse(str.toList())
    
    }
    
    val num1 = (1..20).random()
    val num2 = (1..20).random()
    val num3 = (1..20).random()
    val op1 = listOf('+', '-', '*', '/').random()
    val op2 = listOf('+', '-', '*', '/').random()
    
    val equation = "( $num1 $op1 $num2 ) $op2 $num3"
    
    println("$equation = ${evaluate(equation)}")
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search