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

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!

Related

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").

Write a kotlin program that prints the number that is repeated the most in a consecutive way

I'm kind of stuck, I don't know how to make the second loop to start 1 position above the first loop in Kotlin.
I have an array (named myArray) with 10 elements, I need to Write a Kotlin program that prints the number that has the most consecutive repeated number in the array and also prints the number of times it appears in the sequence.
The program must parse the array from left to right so that if two numbers meet the condition, the one that appears first from left to right will be printed.
Longest: 3
Number: 8
fun main() {
val myArray: IntArray = intArrayOf(1,2,2,4,5,6,7,8,8,8)
for((index , value) in myArray.withIndex()){
var inx = index + 1
var count = 0
var longest = 0
var number = 0
for((inx,element) in myArray.withIndex()) {
if(value == element ){
count+=
}
}
if(longest < count){
longest = count
number = value
}
}
}
I'm against just dropping answers, but it is quite late for me, so I'll leave this answer here and edit it tomorrow with more info on how each part works. I hope that maybe in the meanwhile it will help you to gain some idea to where you might be going wrong.
val results = mutableMapOf<Int, Int>()
(0..myArray.size - 2).forEach { index ->
val current = myArray[index]
if (current == myArray[index + 1]) {
results[current] = (results[current] ?: 1) + 1
}
}
val (max, occurrences) = results.maxByOrNull { it.value } ?: run { println("No multiple occurrences"); return }
println("Most common consecutive number $max, with $occurrences occurrences")
Alternatively if the intArray would be a list, or if we allowed to change it to a list myArray.toList(), you could replace the whole forEach loop with a zipWithNext. But I'm pretty sure that this is a HW question, so I doubt this is the expected way of solving it.
myList.zipWithNext { a, b ->
if (a == b) results[a] = (results[a] ?: 1) + 1
}

My kotlin code gives the wrong answer for the largest and smallest values in a list and I don't know why

This was a simple code wars question but my code gives the wrong answer for the largest value and smallest value. I have checked every section but I can't seem to make it work. I have looked at the solutions for this problem but I wanted to find out what I was doing wrong in the first place.
fun highAndLow(numbers: String): String {
val splitNum = numbers.split(" ")
var largestNum = splitNum[0]
var smallestNum = splitNum[0]
for (num in splitNum) {
if (largestNum < num) {
largestNum = num
}
if (num < smallestNum) {
smallestNum = num
}
}
return "$largestNum $smallestNum"
}
fun main() {
print(highAndLow("8 3 -5 42 -1 0 0 -9 4 7 4 -4 9"))
}
Expected output: 42 -9
Current output: 9 -1
You are comparing strings, not integers. Use toInt() to convert a string into an integer.
val splitNum = numbers.split(" ").map { it.toInt() }
A little tip by the way: perhaps the code could be optimised even further. Have a look here:
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/min-by-or-null.html
and
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/max-by-or-null.html

Write a program that reads a three-digit number(923), reverses the order of its digits, and outputs a new number(329) in Kotlin?

import java.util.Scanner
fun main() {
val scanner = Scanner(System.in)
}
I know there is possibility of using String.reversed() but the exercise is part of Integers in action so I need to solve it only with integers.
thats pretty easy,
var num = 923
var reversed = 0
while (num != 0) {
val digit = num % 10
reversed = reversed * 10 + digit
num /= 10
}
println("Reversed Number: $reversed")

Create a euphonious word

All the letters of the English alphabet are divided into vowels and consonants.
A word is considered euphonious if it doesn't have three or more vowels or consonants in a row.
My goal is to create euphonious words from the discordant ones and output the minimum number of characters needed to create a euphonious word from a given word.
Examples:
Input:
schedule
Output:
1
Input:
biiiiig
Output:
2
Code
fun main() {
val word = readLine()!!.toMutableList()
checkWord(word)
}
fun isVowel(c: Char): Boolean {
val vowels = listOf('a', 'e', 'i', 'o', 'u', 'y')
return c in vowels
}
fun checkWord(word: MutableList<Char>){
var counter = 0
for (number in 0 .. word.size - 2) {
if (isVowel(word[number]) && isVowel(word[number + 1]) && isVowel(word[number + 2])) {
counter++
word.add(number + 2, 'b')
// println(word)
}
if (!isVowel(word[number]) && !isVowel(word[number + 1]) && !isVowel(word[number + 2])) {
counter++
word.add(number + 2, 'a')
// println(word)
}
}
println(counter)
}
My code is working for those examples but not for a case like eeeeeeeeeeeeeeeee where the output is supposed to be 8 but my counter is 6.
Since the list is growing as you iterate, your for loop never reaches the end of the list. Your code can be fixed by replacing
for (number in 0 .. word.size - 2) {
with
var number = -1
while (++number < word.size - 1) {
so it checks the current list size on each iteration.
I want to point out however that it is unnecessary to use a MutableList and keep enlarging it since you don't use the "fixed" euphonious list afterwards. It is also unnecessary to repeatedly search neighbors on each iteration. You can just count as you go.
fun checkWord (word: String) {
var count = 0
var currentTypeCount = 0
var lastTypeVowel = true
for (c in word) {
if (isVowel(c) == lastTypeVowel) {
if (++currentTypeCount == 3) {
count++
currentTypeCount = 1
}
} else {
lastTypeVowel = !lastTypeVowel
currentTypeCount = 1
}
}
println(count)
}
Let's analyze the modifications of your word:
eebeeeeeeeeeeeeeee
eebeebeeeeeeeeeeeee
eebeebeebeeeeeeeeeee
eebeebeebeebeeeeeeeee
eebeebeebeebeebeeeeeee
eebeebeebeebeebeebeeeee
eebeebeebeebeebeebeebeee
eebeebeebeebeebeebeebeebe
Your last 2 modification take place on the letters with index, which is bigger than your word's original length. That happens because for loop iterations number is dependent on your word's original length.
I recommend you to use while loop, as its condition is always recalculated and word.size will be updated there
var i = 0
while (i + 2 < word.size) {
// the same logic
i++
}