44 Views

1st December 2021

niv.yaron@gmail.com

Can someone assist me with the following , Im struggling with it for the last 3 days. 

I need some assistance with the following code ; Im trying to create an algorithm that prevents an e-wallet account from going into negative balance. The account should be debited for each purchase sequentially while the balance allows it.

first line is a single integer, second line is a sequence of integers representing payment and processed one by one.

import java.util.*
fun main() {
val scanner = Scanner(System.`in`)
val funds = scanner.nextInt()
val purchases = mutableListOf<Int>()
while (scanner.hasNextInt()) {
purchases += scanner.nextInt()
}
var sum = purchases.sum()
var index = purchases.lastIndex
while (funds < sum) {
sum -= purchases[index]
index--
}
when {
funds > purchases.sum() -> println("Thank you for choosing us to manage your account! Your balance is ${funds - purchases.sum()}.")
funds == purchases.sum() -> println("Thank you for choosing us to manage your account! Your balance is ${purchases.sum() - sum}.")
else -> println("Error, insufficient funds for the purchase. Your balance is $sum, but you need ${purchases.sum() - sum}.")
}
}

Im passinf all tests , but when I try funds as 5000 and payments as 1001, 1001, 1001, 1001, 1001 (one by one), Im failing to pass the test.

Answers
Write your answer

STILL GOT QUERIES?

Get a Live FREE Demo
  • Explore the trending and niche courses and learning maps
  • Learn about tuition fee, payment plans, and scholarships
  • Get access to webinars and self-paced learning videos