Valid Triangle: Error getting sum of two sides less then the third? - kotlin

Getting wrong output While trying to check the validity of a triangle where condition is ** sum of two side should be greater then the third** on 3 random integers between 0 to 20. Below output suggest two sides are greater then the third but showing "Not a valid triangle".
fun main() {
var a = (Math.random() * 20).toInt()
var b = (Math.random() * 20).toInt()
var c = (Math.random() * 20).toInt()
var validTriangle = "length $a,$b,$c"
if (a + b > c && b + c > a && a + c > b) {
println("Valid Triangle")
} else {
println("Not a valid Triangle")
}
println(validTriangle)
The below output suggests sum of two side(13,6) should be > third side(4)
which is 19 so answer should be "valid triangle" but it is not showing that
Output:
Not a valid Triangle
length 13,6,4

Related

print n times number from 1. Need print (1 2 2 3 3 3 4)

I can't figure out how to solve the following problem: there is a number n. Output the numbers to the console in order separated by a space, but so that the next digit in the iteration is output as many times as it is a digit, and at the same time so that there are no more than n digits in the output. Сan anyone suggest the correct algorithm?
example: have n = 7, need print (1 2 2 3 3 3 4) in kotlin
what i try:
var n = 7
var count = 1
var i = 1
for (count in 1..n) {
for (i in 1..count) {
print(count)
}
}
}
var n = 11
var count = 1
var i = 1
var size = 0
// loop# for naming a loop in kotlin and inside another loop we can break or continue from outer loop
loop# for (count in 1..n) {
for (i in 1..count) {
print(count)
size++
if (size == n){
break#loop
}
}
}
You can use "#" for naming loops and if you want to break from that loop, you can use this syntax in kotlin. It worked for me.
For kotlin labeled break you can look at this reference: link
var count = 1
var n = 7
for(count in 1..n) {
print(count.toString().repeat(count))
}
count.toString() converts an integer to a string, .repeat() function repeats count times the string.
In case you need to add a space between each number, you can add the following:
print(" ")
Using generateSequence and Collections functions:
val n = 7
println(generateSequence(1) {it + 1}
.flatMap{e -> List(e){e}}
.take(n)
.joinToString(" "))
Your example is correct, You have to put a space between the printing
you can follow the code from this link
Kotlin lang code snippet
or the following code snippet
fun main() {
var n = 7
var count = 1
var i = 1
for (count in 1..n) {
for (i in 1..count) {
print(count)
print(' ')
}
}
}
For completeness, here's another approach where you write your own sequence function which produces individual values on demand (instead of creating intermediate lists)
sequence {
var digit = 1
while (true) {
for (i in 1..digit) yield(digit)
digit++
}
}.take(7)
.joinToString(" ")
.run(::print)
Not a big deal in this situation, but good to know!

Conditional loop repetitively printing wrong output

I wasn't sure how to phrase the title sorry.
Basically I'm writing a code that draws up a cinema and seating.
The program asks input for how many rows in the cinema and how many seats and returns this:
Cinema:
1 2 3 4 5 6 7 8 9
1 S S S S S S S S S
2 S S S S S S S S S
3 S S S S S S S S S
4 S S S S S S S S S
5 S S S S S S S S S
6 S S S S S S S S S
7 S S S S S S S S S
8 S S S S S S S S S
9 S S S S S S S S S
The program then asks the user to select a row and seat and should out put the same seating as above but with a 'B' marking their seat:
1 2 3 4 5 6 7 8 9
1 S S S S S S S S S
2 S S S S S S S S S
3 S S S S S S S S S
4 S S S B S S S S S
5 S S S S S S S S S
6 S S S S S S S S S
7 S S S S S S S S S
8 S S S S S S S S S
9 S S S S S S S S S
This is working fine unless the user selects row 1 and seat 1 then this is the returned seating:
1 2 3 4 5 6 7 8 9
1 B S S S S S S S S
2 B S S S S S S S S
3 B S S S S S S S S
4 B S S S S S S S S
5 B S S S S S S S S
6 B S S S S S S S S
7 B S S S S S S S S
8 B S S S S S S S S
9 B S S S S S S S S
I'm positive this is to do with my for and if conditionals at the end of the code but am confused as to why it will repetitively print the 'B'.
Also I understand that i've attempted this in a bad way but just want to understand why I'm having this issue.
here is the whole code so you can test on your IDEA:
fun main(args: Array<String>) {
println("Enter the number of rows:")
val rows = readln().toInt()
println("Enter the number of seats in each row:")
val seats = readln().toInt()
val total = rows * seats
var s = 'S'
var cinemaLayout = mutableListOf<MutableList<Char>>()
val cinemaSeats = mutableListOf<Char>()
for (x in 1..seats) {
cinemaSeats.add(s)
}
for (x in 1..rows) {
cinemaLayout.add(cinemaSeats.toMutableList())
}
println("Cinema:")
print(" ")
for (x in 1..seats) {
print(x)
print(" ")
}
println()
var cleanLayout1 = " ${cinemaLayout[0].joinToString().replace("]", "\n").replace("[", "").replace(",", "")}"
for (i in 1..rows) {
println("$i$cleanLayout1")
}
println("Enter a row number:")
val selectedRow = readln().toInt()
println("Enter a seat number in that row:")
val selectedSeat = readln().toInt()
if (total < 60) {
println("Ticket price: $10")
} else if (total > 60 && selectedRow % 2 === 0 && selectedRow <= rows / 2) {
println("Ticket price: $10")
} else {
println("Ticket price: $8")
}
var indexRow = selectedRow - 1
var indexSeat = selectedSeat - 1
cinemaLayout[indexRow][indexSeat] = 'B'
println("Cinema:")
print(" ")
for (x in 1..seats) {
print(x)
print(" ")
}
println()
for (i in 0 until rows) {
if (i === indexRow) {
println(
"${i + 1} ${
cinemaLayout[indexRow].joinToString().replace("]", "\n").replace("[", "").replace(",", "")
}"
)
} else {
println(
"${i + 1} ${
cinemaLayout[0].joinToString().replace("]", "\n").replace("[", "").replace(",", "")
}"
)
}
}
}
It's because you're always printing the first row, when it's not indexRow
for (i in 0 until rows) {
if (i === indexRow) {
println("...cinemaLayout[indexRow]...")
} else {
println("...cinemaLayout[0]...")
}
}
So when i is your target row, you print that row - otherwise you print row 0 instead of the row number that i currently represents. This means that when indexRow is the first row, you're just printing row 0 every single time, and that's why you see it repeated. When it's not the first row, you're still printing row 0 for everything but that row - it's just more obvious when row 0 has a change in it.
You should be printing the current row instead of the first one:
} else {
// i not 0
println("...cinemaLayout[i]...")
}
but really, why do you need to care about what indexRow is at this point? Your code is the same for both cases here, and you've added the 'B' to your data - you can just print everything as it is
for (i in 0 until rows) {
println("${i + 1} ${ cinemaLayout[i].joinToString().replace("]", "\n").replace("[", "").replace(",", "") }")
}
or better
cinemaLayout.forEachIndexed { index, row ->
val seats = row.joinToString()
.replace("]", "\n")
.replace("[", "")
.replace(",", "")
println("${index + 1} $seats")
}
(and even better ways to things like replacing with the standard library - just showing you how you can do things like looping more cleanly!)
The main issue here comes from bad organization of the code. You should extract functions, and separate business logic from printing logic.
Then you might be able to notice more easily things like the last line which prints cinemaLayout[0] no matter what i we are inspecting.
Also, joinToString takes arguments, you don't have to replace things a posteriori: joinToString(separator = "", prefix = "", postfix = "\n").

Kotlin. Function does not exit recursion after return

I need to decompose the number l into prime factors. For this I use recursion. And when l = 1, the function must exit their recursion and return the string in which the prime factors are located, however, the function continues to work and already according to a principle incomprehensible to me. Please explain what is the problem with my code?
fun factors(l: Int): String {
return if (l == 1) {
answer
} else {
for (i in 2..l) {
if (l % i == 0) {
answer += "$i "
factors(l / i)
}
}
return factors(l)
}
}
Let's first mention some issues in your current code:
You're mixing semantics, here. What is the contract of your function? Does it return a value, or does it modify a global variable? Pick one, don't do both.
You should not use a global variable because it's way harder to follow. Instead, construct your values locally from the current information + whatever the recursive call returns to you
You're already using an if expression with the syntax return if (condition) { ... } else { ... }. This means each branch of the if should just end with an expression, you don't need to use return again. That said, in this case the first branch is rather a special case that you want to get out of the way before doing the bulk of the general work. In this kind of situation, I would rather use a statement like if (condition) { return X } at the beginning and then have the rest of the body of the function unnested, instead of using an if expression (but that is a personal preference).
It is strange to compute the list of factors as a string. You likely want to avoid duplicates and maybe sort them, so a List<Int> or a Set<Int> would likely be more appropriate. You can always format after the fact using things like joinToString(" ")
I'm not sure I get the math correctly, but it seems you really will be getting all factors here, not just the prime factors.
Now, the actual cause of the behaviour you're seeing is that you're calling your function recursively with the same number at the end: return factors(l). This means that calling factors(l) with any l > 1 will end up calling itself with the same value over and over. Recursive calls need to change some arguments to the function if you don't want it to be infinite.
fun factors(value: Int, list: MutableList<Int> = mutableListOf()): MutableList<Int> {
if (value > 1) {
for (i in 2..value) {
if (value % i == 0) {
list.add(i)
list.addAll(factors(value / i))
break
}
}
}
return list
}
(2..25).forEach {
val factors = factors(it)
val result = factors.reduce { acc, i -> acc * i }.toString() + " = " + factors.joinToString(" × ")
println(result)
}
Edit: this version is based on #Joffrey's comment below. Plus I decided to wrap the recursive function, now called fn, into a function in order to have a clean parameter list for factors():
fun factors(value: Int): List<Int> {
fun fn(value: Int, list: MutableList<Int>) {
if (value > 1) {
for (i in 2..value) {
if (value % i == 0) {
list.add(i)
fn(value / i, list)
break
}
}
}
}
val list = mutableListOf<Int>()
fn(value, list)
return list
}
Output:
2 = 2
3 = 3
4 = 2 × 2
5 = 5
6 = 2 × 3
7 = 7
8 = 2 × 2 × 2
9 = 3 × 3
10 = 2 × 5
11 = 11
12 = 2 × 2 × 3
13 = 13
14 = 2 × 7
15 = 3 × 5
16 = 2 × 2 × 2 × 2
17 = 17
18 = 2 × 3 × 3
19 = 19
20 = 2 × 2 × 5
21 = 3 × 7
22 = 2 × 11
23 = 23
24 = 2 × 2 × 2 × 3
25 = 5 × 5

Palindrome of a number - No console log

So I tried to write a code that finds the largest palindromic number from two (3 spaces long) multiplied numbers. Does my code work fine or are there no palindromes for this?
function checkPalindrom(str) {
return str === str.split('').reverse().join('');
}; //Declares the funciton to check if a string is a palindrome
var x = 999;
var y = 999;
var z = 0;
var n = z.toString(); //Declares that n is the string of z
for (i=0; i<899; i++) { //For loop: counts from 0 to 899
x*y===z; //Is this correct? z is set equal to x*y
if(checkPalindrom(n) === true) { //If n is a palindrome,
console.log(n); //Write out the palindrome
} else {
x-=1; //subtract 1 from x and run again
}
};
Also, what is the best way to check for all combinations of 3 digit numbers? Because right now I am just checking for any number from 100 to 999, but I actually need to check for all combinations...
Your post has a few problems, as well as multiple questions in it. I'll try to hone in on the major stuff but, as this is a fairly standard type of Programming 101 homework question, I'm not going to give you an exact answer right out.
First off, there are three different 'equals' in javascript, =, ==, and ===. A single = is an assignment operator and it always works from right to left. Thus,
var x = 2;
assigns the value of 2 to the variable x. In your code,
x*y === z;
has a couple of problems. First off, it is backwards. Secondly, it uses === but should be using =.
z = x*y;
That is what you were trying to put here.
In javascript, == and === are both comparitives. The triple === adds type comparison and is stronger but generally unnecessary. In almost all cases, == is sufficient. But, what it does is compare the values like inside an if statement:
if(x == 2)
This just checks if the value of x is equal to the value of 2, but the values themselves do not change.
Ok, for your other question: "number from 100 to 999, but I actually need to check for all combinations..."
The best way to handle this is a double loop:
var z;
for(var x = 100; x < 1000; x++)
for(var y = x; y < 1000; y++)
z = x*y;
This will first let x = 100, then check 100 * every number from 100 to 999. Then you let x = 101 and check 101* every number from 101 to 999.
function checkPalindrom(str) {
return str === str.split('').reverse().join('');
}; //Declares the funciton to check if a string is a palindrome
var x;
var y;
var z;
var n;
var max = 0;
for (x=999; x >= 100; x--) {
for (y=999; y >= 100; y--) {
z = x*y;
n = z.toString();
if(checkPalindrom(n) === true && max < z) {
console.log(n);
max = z;
}
}
}

EasyB testing multiple input/ouput values

How do I test a functionality with multiple inputs/expected outputs?
Here is a really simple example:
scenario "Can add two numbers", {
given "Two numbers", {
num1 = 2
num2 = 3
}
when "I trigger add.", {
result = add(num1,num2)
}
then "The result should be correct.", {
result.shouldBe 5
}
}
I want to test this with multiple values, say add(4,8).shouldBe 12, ....
Whats the best practice to do this? In other BDD frameworks I have seen table like structures to implement this, but cannot find something like that in EasyB. Should I create multiple scenarios to cover this (appending (1), (2) to the scenario name), or should I put the inputs and expected outputs into an array, and check this for equality?
If I use the latter approach, how do I get meaningfull failures?
Use the where/example clause
http://code.google.com/p/easyb/wiki/ChangesInEasyb098
package org.easyb.where
/*
Example tests a map at the story level
*/
numberArray = [12, 8, 20, 199]
where "we are using sample data at a global level", [number:numberArray]
before "Before we start running the examples", {
given "an initial value for counters", {
println "initial"
whenCount = 0
thenCount = 0
numberTotal = 0
}
}
scenario "Number is #number and multiplier is #multiplier and total is #{number * multiplier}", {
when "we multiply #number by #multiplier", {
whenCount ++
num = number * multiplier
}
then "our calculation (#num) should equal #{number * multiplier}", {
num.shouldBeGreaterThan 0
numberTotal += num
thenCount ++
}
where "Multipliers should be", {
multiplier = [1,2,3]
}
}
after "should be true after running example data", {
then "we should have set totals", {
whenCount.shouldBe 12
thenCount.shouldBe 12
num = 0
numberArray.each { n ->
num = num + (n + (2*n) + (3*n))
}
num.shouldBe numberTotal
}
}