If the list contains the following elements ("a", "b", "a") then the function should return 0.6666666666666666,
the percentage of "a" appearances in the list.
The returning value should always be between 0.0 and 1.0 if the input is correct.
Also the list should have at least one "a" and one "b".
If the list has one incorrect element or more, the function should return -1.0.
Here are some example of incorrect values: "A", "c", "aa", " ", "ab", "بي", "ba"
fun solution(list: MutableList<String>): Double {
return if ("a" in list && "b" in list) {
(list.count { it == "a" }.toDouble() / list.size)
} else {
-1.0
}
}
When I try it it does not check for "a" and "b" only but it accepts "c" and it should accept "a" and "b" only.
You are only checking with "a" in list, which will return true if at least one entry "a" exists in list. No check is made on the other entries. Same for "b". You need to check for each entry if it is "a" or "b".
One way is to count the lowercase "a" and the lowercase "b" and work with these two results. Like this:
fun solution(list: List<String>): Double {
val smallAs = list.count { it.length == 1 && it[0] == 'a' }
val smallBs = list.count { it.length == 1 && it[0] == 'b' }
return if (smallAs > 0 && smallBs > 0 && smallAs + smallBs == list.size) {
smallAs.toDouble() / list.size
} else {
-1.0
}
}
Related
can someone help me make star patterns like this using for loop in kotlin? i already try this but i think my code is too long. can someone help me?
x Star Pattern
fun fifthPyramid(){
for(i in 1..13){
if(i==1||i==13){
print("*")
}else
print(" ")
}
println("")
for(i in 1..13){
if(i==2||i==12){
print("*")
}else
print(" ")
}
println("")
for(i in 1..13){
if(i==3||i==11){
print("*")
}else
print(" ")
}
println("")
for(i in 1..13){
if(i==4||i==10){
print("*")
}else
print(" ")
}
println("")
for(i in 1..13){
if(i==5||i==9){
print("*")
}else
print(" ")
}
}
The star pattern consists of exactly N * 2 - 1 rows and columns. So the outer and inner loop will run till towards count = N * 2 - 1
fun main() {
var starCount = 5;
val count = starCount * 2 - 1;
for(i in 1..count){
for(j in 1..count){
if(j==i || (j==count - i + 1))
{
print("*");
}
else
{
print(" ");
}
}
println("")
}
}
Identify the pattern with respect to row and column. You put a * when the row and column are the same, or the row and inverse of the column are the same.
fun printX(size: Int, char: Char) {
repeat(size) { row ->
repeat(size) { col ->
print(if (row == col || row == (size - col - 1)) char else ' ')
}
println()
}
}
fun main() {
printX(7, '*')
}
You can write a fun that takes an Int and a Char as arguments and then use a loop in order to build each line and print it.
Basically like this:
fun printX(heightWidth: Int, symbol: Char) {
// iterate the heigth in order to build up each line (top->down)
for (i in 0 until heightWidth) {
/*
build up an array of Chars (representing a line)
with the desired size (length of a line)
filled up with whitespaces by default
*/
var line = CharArray(heightWidth) { ' ' }
// then replace whitespaces at the desired indexes by the symbol
line[i] = symbol // one from left to right
line[line.size - i - 1] = symbol // and one from right to left
// and print the result
println(line)
}
}
You can throw an Exception in case of negative heightWidth values because they will cause trouble if you don't. And maybe forbid 0, 1 and 2, because although they would produce valid output, that output can hardly be regarded as X. Even the output for 3 and 4 is rather ugly ;-)
However, here's the output of printX(7, '7'):
7 7
7 7
7 7
7
7 7
7 7
7 7
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
}
I'm writing a function that allows you to remove certain numbers from an int arraylist.
My code
for (i in 1 until 4) {
divider = setDivider(i)
for(index in 0 until numbers.size){
if(index <= numbers.size){
if (numbers[index] % divider == 0 && !isDone) {
numbers.removeAt(index)
}
}else{
isDone = true
}
}
if(isDone)
break
}
the function to set the divider
fun setDivider(divider: Int): Int {
when (divider) {
1 -> return 2
2 -> return 3
3 -> return 5
4 -> return 7
}
return 8
}
I do not know why the ide is giving me the error Index 9 out of bounds for length 9.
Author explained in the comments that the goal is to remove all numbers that are divisible by 2, 3, 5 and 7.
It can be achieved much easier by utilizing ready to use functions from stdlib:
val dividers = listOf(2, 3, 5, 7)
numbers.removeAll { num ->
dividers.any { num % it == 0 }
}
It removes elements that satisfy the provided condition (is divisible) for any of provided dividers.
Also, it is often cleaner to not modify a collection in-place, but to create an entirely new collection:
val numbers2 = numbers.filterNot { num ->
dividers.any { num % it == 0 }
}
Only for context: I am trying to implement Playfair Cipher. It would be really helpful if you take a look at Playfair Cipher to understand my problem.
This program is just for some background:
fun main(){
println("Enter the message:")
var message:String = readLine()!!.toUpperCase()
println("Enter the key:")
var key:String = readLine()!!.toUpperCase()
var cipTable = Array(5){ Array(5){'X'}}
var j=0; //to iterate througm my key
for(innerArray in cipTable){
for(i in innerArray.indices){
if(key[j++] !in cipTable)
innerArray[i]+=key[j]
if(j==key.length) break
}
}
}
My main issue is with this part:
for(innerArray in cipTable){
for(i in innerArray.indices){
if(key[j++] !in cipTable)
I wanted to check if the key that I am going to insert in the matrix is already present in it or not. I also cannot use innerArray instead of cipTable as it would only check for char in the same row. Is there any way I can check if a char is present or not in the entire matrix?
For eg.:
fun main(){
var result = arrayOf(
intArrayOf(3, 2, 4),
intArrayOf(6, 7, 9),
intArrayOf(12, 11, 23)
)
//To check if 2 is present in the entire matrix/table
if(result.any { 2 !in it}) println("not present") else print("present")
}
Can you tell me what is wrong in this code because the output is not expected. Also is there any way I can use forEach for the same.
If I understand correctly, you want this for loop to result in a true or false based on whether any inner array has the same sequence and number of chars as the key String.
First of all, the inner array should be a CharArray instead of an Array<Char>, to avoid boxing.
val cipTable = Array(5) { CharArray(5) { 'X' } }
Then you can use all and contentEquals to check if any of the inner CharArrays are a match for the key.
val charArrayKey = key.toCharArray()
val isKeyInTable = cipTable.any { it.contentEquals(charArrayKey) }
If you want to skip the step of converting the key to a CharArray, you can manually check it like this:
val isKeyInTable =
cipTable.any { it.size == key.length && it.withIndex().all { (i, c) -> c == key[i] } }
I guess one way is to use extensions.
fun Array<IntArray>.has(x:Int):Boolean{
for(innerArray in this){
if(x in innerArray)
return true
}
return false
}
fun main(){
var result = arrayOf(
intArrayOf(3, 2, 4),
intArrayOf(6, 7, 9),
intArrayOf(12, 11, 23)
)
//To check if 43 or 4 is present in the entire matrix/table
if(result.has(43)) println("present") else println("not present")
if(result.has(4)) println("present") else println("not present")
}
I have following code which is working in Objective-C:
NSScanner *scanner ;
for(int i = 0; i < [expression count]; i = i + 2)
{
scanner = [NSScanner scannerWithString:[expression objectAtIndex:i]];
BOOL isNumeric = [scanner scanInteger:NULL] && [scanner isAtEnd];
if(!isNumeric)
return false;
}
return true;
I need equivalent code in Swift 4. I have tried different things but couldn't work it out. The requirement is to check whether the elements of array are number or not.
To check if an object is a number (Int in your case), you could do two things:
Type check via is or as?
This only checks the type and not the content
let isNumberType = "1" is Int
print(isNumberType) //false because "1" is of type String
Creating an Int via it's initializer
This returns an Int? because it can fail so further check != nil
let something = "1"
let isNumber = Int(something) != nil
print(isNumber) //true because "1" can be made into an Int
NOTE: As per your example, you're checking only even elements, hence we will use stride(from:to:by:)
Solution #1:
Assuming you have an array of Strings, we can use the Int initializer to check if the string element can be a number, like so:
func check(expression: [String]) -> Bool {
for idx in stride(from: 0, to: expression.count, by: 2) {
let isNumeric = Int(expression[idx]) != nil
if isNumeric == false {
return false
}
}
return true
}
check(expression: ["1", "A", "2", "B", "3", "C"]) //true
check(expression: ["1", "A", "2", "B", "E", "C"]) //false
Solution #2:
Assuming your array is of type [Any] and you want to type check the alternate elements to be Int then use is, like so:
func check(expression: [Any]) -> Bool {
for idx in stride(from: 0, to: expression.count, by: 2) {
let isNumeric = expression[idx] is Int
if isNumeric == false {
return false
}
}
return true
}
check(expression: [1, "A", 2, "B", 3, "C"]) //true
check(expression: [1, "A", 2, "B", "3", "C"]) //false
The thing with [Any] is that it's elements can't be fed directly to the Int's initializer without bringing it into an acceptable type.
So in this example, for simplicity sake, we are just checking if the object is exactly of type Int or not.
Therefore, I doubt this one suits your requirement.
Try this:
var str = "1234456";
let scanner = Scanner(string: str);
let isNumeric = scanner.scanInt(nil) && scanner.isAtEnd
if !isNumeric {
print("not numeric")
} else {
print("is numeric")
}
Overall if you just want to check the given string is an parsable Integer, I recommend you try :
var expressions = ["1234456","abcd"];
for str in expressions {
if let isNumeric = Int(str) {
print("is numeric")
} else {
print("not numeric")
}
}