I wrote this function with recursion in Kotlin, it's just for academic purposes.
But I have a problem, when the condition is true, the execution is not interrupted. It's as if it ignores the return command and keeps iterating.
I have seen it in debug, that when the condition is true it goes through there and then continues.
Anyone knows how to solve this?
In this capture, see the debugger in the return true statement, but the function don't exit.
Here is the function:
// The inputArray must be sorted in order to apply the binary search.
fun binarySearch(inputArray: Array<Int>, itemToSearch: Int) : Boolean {
// This print is for see the interactions in the search
println()
inputArray.forEach {
print("$it,")
}
if (inputArray.size > 1) {
if (itemToSearch == inputArray[(inputArray.size / 2) - 1]) {
return true
}
if (itemToSearch > inputArray[(inputArray.size / 2) - 1]) {
binarySearch(inputArray.copyOfRange(inputArray.size / 2, inputArray.size), itemToSearch)
} else {
binarySearch(inputArray.copyOfRange(0, inputArray.size / 2), itemToSearch)
}
}
return false
}
Here is the call:
val result = binarySearch(arrayOf(1,2,3,4,5,6,7,8,9,10,11,12,13,14,16,17,18,19,20,21,22,23), 16)
You need to return the result of the recursion, like
return binarySearch(inputArray.copyOfRange(inputArray.size / 2, inputArray.size), itemToSearch)
so in total:
// The inputArray must be sorted in order to apply the binary search.
fun binarySearch(inputArray: Array<Int>, itemToSearch: Int) : Boolean {
// This print is for see the interactions in the search
println()
inputArray.forEach {
print("$it,")
}
if (inputArray.size > 1) {
if (itemToSearch == inputArray[(inputArray.size / 2) - 1]) {
return true
}
if (itemToSearch > inputArray[(inputArray.size / 2) - 1]) {
return binarySearch(inputArray.copyOfRange(inputArray.size / 2, inputArray.size), itemToSearch)
} else {
return binarySearch(inputArray.copyOfRange(0, inputArray.size / 2), itemToSearch)
}
}
return false
}
Related
I wanted to create a program that displays all valid arrangements for n couple of parentheses. The output should be an array sorted in ascending order of ASCII values. The following is the function that needs to be used.
fun solution(n: Array<String>): Array<String> {
}
I tried it using this, but cannot make it fit the above function,
fun balancedBracket(result: String,
size: Int,
open: Int,
close: Int): Unit
{
if (close == size)
{
// When get the result of parentheses in given size
println(result);
return;
}
if (open < size)
{
// Add open parentheses
this.balancedBracket(result + "(",
size, open + 1, close);
}
if (open > close)
{
// Add close parentheses
this.balancedBracket(result + ")",
size, open, close + 1);
}
}
Input: n = 3
Output: ["((()))","(()())","(())()","()(())","()()()"]
Please help.
fun printParentheses(size: Int) {
fun inner(chars: String, size: Int, open: Int, close: Int) {
if (close == size) {
println(chars)
return
}
if (open < size) {
inner("$chars(", size, open + 1, close)
}
if (open > close) {
inner("$chars)", size, open, close + 1)
}
}
if (size > 0) {
inner("", size, 0, 0)
}
}
printParentheses(3)
The problem I'm working on accepts a number string and will output the product of the odd or even numbers in the string. While the product of purely number string is working fine, my code should also accept strings that is alphanumeric (ex: 67shdg8092) and output the product. I'm quite confused on how I should code the alphanumeric strings, because the code I have done uses toInt().
Here's my code:
fun myProd(Odd: Boolean, vararg data: Char): Int {
var bool = isOdd
var EvenProd = 1
var OddProd = 1
for (a in data)
{
val intVal = a.toString().toInt()
if (intVal == 0)
{
continue
}
if (intVal % 2 == 0)
{
EvenProd *= intVal
}
else
{
OddProd *= intVal
}
}
if(bool == true) return OddProd
else return EvenProd
}
Use toIntOrNull instead of toInt. It only converts numeric string
val intVal = a.toString().toIntOrNull()
if (intVal == null || intVal == 0) {
continue
}
Starting from Kotlin 1.6 you can also use a.digitToIntOrNull().
P.S. Your method could be also rewritten in functional style
fun myProd(isOdd: Boolean, input: String): Int {
return input.asSequence()
.mapNotNull { it.toString().toIntOrNull() } // parse to numeric, ignore non-numeric
.filter { it > 0 } // avoid multiplying by zero
.filter { if (isOdd) it % 2 != 0 else it % 2 == 0 } // pick either odd or even numbers
.fold(1) { prod, i -> prod * i } // accumulate with initial 1
}
` enum outofBound: Error
{
case NegativeNumber
case OutOfLimit
}
func sqareRoot(Number: Int) throws -> String
{
if Number < 10
{
throw outofBound.NegativeNumber
}
if Number > 100
{
throw outofBound.OutOfLimit
}
else
{
let number1 = Double (Number / 4)
print(number1)
let number2 = Double (number1 / 2)
print(number2)
return "number2"
}
}
do
{
let Result = try sqareRoot(Number: 3600)
}
catch outofBound.NegativeNumber
{
print("Please provide positive number")
}
catch outofBound.OutOfLimit
{
print("please provide less than 1000 number")
}
catch
{
print("unkonw errors occured")
}
print(squareRoot(Number: 2500))
print(squareRoot(Number: 3600))
print(squareRoot(Number: 4))
`
it gives this suggestion I am not getting it please help me.
{
No calls to throwing functions occur within 'try' expression
'catch' block is unreachable because no errors are thrown in 'do' block
}
try something like this:
func test() {
do {
let result = try sqareRoot(Number: 3600)
print("result: \(result)")
}
catch (let error) {
switch error {
case outofBound.NegativeNumber:
print("Please provide >= 10 number")
case outofBound.OutOfLimit:
print("please provide <= 100 number")
default:
print("error: \(error)")
}
}
// test print
print(try? sqareRoot(Number: 25))
}
func sqareRoot(Number: Int) throws -> String {
if Number < 10 {
throw outofBound.NegativeNumber
}
if Number > 100 {
throw outofBound.OutOfLimit
}
else {
let number1 = Double (Number / 4)
print("number1 \(number1)")
let number2 = Double (number1 / 2)
print("number2 \(number2)")
return String(number2)
}
}
For example I have such a simple task: count all raws and columns which have all zeros in 2D array.
So for
0 0 0
0 0 0
1 0 1
answer is 2 raws and 1 column.
I can make it just like that for raws: var cntRaws = a.count { it.all { el -> el == 0 } }, but how to solve it for columns in same way?
val x = Array<IntArray>(3) { IntArray(3) { 0 } }
x[2][0] = 1
x[2][2] = 1
val raws = x.count { it.sum() == 0 }
val columns = (x.indices)
.map { columnIndex -> x.map { it[columnIndex] } }
.count { it.sum() == 0 }
println("total raws:$raws")
println("total col:$columns")
I couldn't think of any idomatic / functional style to do this, but I came up with an idea just create a lazily evaluated swapping function that swaps the columns with rows when it wants to pull without creating a new list.
fun <T> List<List<T>>.swapped() = sequence {
var index = 0
while (index < size) {
yield(map { it[index] })
index++
}
}
fun main() {
val list = listOf(
listOf(0, 0, 0),
listOf(0, 0, 0),
listOf(1, 0, 1)
)
val cntRows = list.count { it.all { el -> el == 0 } }
val cntCols = list.swapped().count { it.all { el -> el == 0 } }
println("cntRows: $cntRows")
println("cntCols: $cntCols")
}
I tried my best to optimize it and do it in same O(n*m) steps as done with the regular row counting, since Sequences are lazily evaluated.
This is a functional way of doing it that works if all rows are the same size:
fun <T>List<List<T>>.rowToColumn() = (0 until first().size).map{row -> (0 until size).map {col-> this[col][row] }}
The program aims to use a loop to check if the index of a iterator variable meets certain criteria (i.g., index == 3). If find the desired index, return Some(123), else return None.
fn main() {
fn foo() -> Option<i32> {
let mut x = 5;
let mut done = false;
while !done {
x += x - 3;
if x % 5 == 0 {
done = true;
}
for (index, value) in (5..10).enumerate() {
println!("index = {} and value = {}", index, value);
if index == 3 {
return Some(123);
}
}
return None; //capture all other other possibility. So the while loop would surely return either a Some or a None
}
}
}
The compiler gives this error:
error[E0308]: mismatched types
--> <anon>:7:9
|
7 | while !done {
| ^ expected enum `std::option::Option`, found ()
|
= note: expected type `std::option::Option<i32>`
= note: found type `()`
I think the error source might be that a while loop evaluates to a (), thus it would return a () instead of Some(123). I don't know how to return a valid Some type inside a loop.
The value of any while true { ... } expression is always (). So the compiler expects your foo to return an Option<i32> but finds the last value in your foo body is ().
To fix this, you can add a return None outside the original while loop. You can also use the loop construct like this:
fn main() {
// run the code
foo();
fn foo() -> Option<i32> {
let mut x = 5;
loop {
x += x - 3;
for (index, value) in (5..10).enumerate() {
println!("index = {} and value = {}", index, value);
if index == 3 {
return Some(123);
}
}
if x % 5 == 0 {
return None;
}
}
}
}
The behaviour of while true { ... } statements is maybe a bit quirky and there have been a few requests to change it.