Count Occurrences in List item and String in KOTLIN

 



Here is some way to find out how to count list item from the list, only first char in list and many more;

1. Count first character with start particular char on list 

fun countOccurrencesOnlyFirstCharUsingCount() {
val list = listOf("one", "two", "three", "four", "five", "six",
"seven", "eight", "nine", "ten")
val char = 't'
val count = list.count { it.startsWith(char) }
println("$char => $count")
}

output:

/*
t => 3
*/

2. Count occurrence first all characters on list

fun countOccurrencesFirstCharUsingGroupingBy() {
val list = listOf("one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten")
val frequenciesByFirstChar = list.groupingBy { it.first() }.eachCount()
println(frequenciesByFirstChar) // {o=1, t=3, f=2, s=2, e=1, n=1}
}

output:

/*
{o=1, t=3, f=2, s=2, e=1, n=1}
*/


3. Count occurrence of word in list by using groupingBy and eachCount

fun countOccurrencesUsingGroupingBy() {
val list = listOf("usa", "china","japan","usa", "canada","usa","canada", "japan", "india","japan")
println(list.groupingBy { it }.eachCount())

}

output:

/*
{usa=3, china=1, japan=3, canada=2, india=1}
*/

4. Count occurrence of word in list by using  MutableMap and for loop

fun countOccurrencesUsingMutableMap() {
val list = listOf("usa", "china","japan","usa", "canada","usa","canada", "japan", "india","japan")
val countMap : MutableMap<String, Int> = HashMap()
for (item in list){
var count = countMap[item]
if (count == null) count = 0
countMap[item] = count + 1
}
println(countMap)
}

output:

/*
{usa=3, china=1, canada=2, japan=3, india=1}
*/

5. Count occurrence of word in list by using distinctCollections and, frequency

fun countOccurrencesUsingCollection() {
val list:List<String> = listOf("usa", "china","japan","usa", "canada","usa","canada", "japan", "india","japan")
for(i in list.distinct()){
println( "$i => ${Collections.frequency( list, i)}")
}
}

output:

/*
usa => 3
china => 1
japan => 3
canada => 2
india => 1
*/

6. Count occurrence of word in list without (expect) banned word or list   (.filterNotgroupingBy ,  eachCount)

with help fo HashSet.

fun countOccurrencesUsingGroupingByBannedItem() {
val list = listOf("usa", "china","japan","usa", "canada","usa","canada", "japan", "india","japan")

val banned = setOf("china","india")
var bannedSet = banned.toHashSet()

val wordCount = list.filterNot { it in bannedSet }.groupingBy { it } .eachCount()
println(wordCount)
}

output:

/*
{usa=3, japan=3, canada=2}
*/


HAPPY CODING :) 

FizzBuzz solutions in KOTLIN


 

The FizzBuzz problem is a classic test given in coding interviews. The task is simple: Print integers 1 to N, but print “Fizz” if an integer is divisible by 3, “Buzz” if an integer is divisible by 5, and “FizzBuzz” if an integer is divisible by both 3 and 5.

Doing a "3 and 5" test makes the code more readable -- with more duplication:

  if (theNumber is divisible by 3) and (theNumber is divisible by 5) then
	print "FizzBuzz"
  else if (theNumber is divisible by 3) then
	print "Fizz"
  else if (theNumber is divisible by 5) then
	print "Buzz"
  else /* theNumber is not divisible by 3 or 5 */
	print theNumber
  end if


Here is some way of doing fizzbuzz solutions

1. Print FizBuzz using when

//".......Using when......."
fun printFizzBuzzWhen() {
for (i in 1..30) {
val result: String =
when {
i % 15 == 0 -> "FizzBuzz"
i % 3 == 0 -> "Fizz"
i % 5 == 0 -> "Buzz"
else -> "$i"
}
print("$result ")
}
}

output:

1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz 16 17 Fizz 19 Buzz Fizz 22 23 Fizz Buzz 26 Fizz 28 29 FizzBuzz


2. Print on List using map

//".......Using map and print on list......."
fun printFizzBuzzMapOf() {
println((1..30)
.map {
i -> mapOf(0 to i,
i % 3 to "Fizz",
i % 5 to "Buzz",
i % 15 to "FizzBuzz")[0] })
}

output:

[1, 2, Fizz, 4, Buzz, Fizz, 7, 8, Fizz, Buzz, 11, Fizz, 13, 14, FizzBuzz, 16, 17, Fizz, 19, Buzz, Fizz, 22, 23, Fizz, Buzz, 26, Fizz, 28, 29, FizzBuzz]

3. Check number is FIZZ or BUZZ or FIZZBUZZ or not (return number)

/--------find fizz or buzz or fizzbuzz-----------------
fun findFizzBuzzWhen(num: Int): String {
return when {
(num % 3 == 0 && num % 5 == 0) -> "FizzBuzz"
(num % 3 == 0) -> "Fizz"
(num % 5 == 0) -> "Buzz"
else -> "$num"
}
}
println("${findFizzBuzzWhen(15)}");

output: FizzBuzz


Learn more about fizzbuzz sotluion: https://wiki.c2.com/?FizzBuzzTest




Regular Expression Example in KOTLIN - Check EMAIL address and more

 


Represents a compiled regular expression. Provides functions to match strings in text with a pattern, replace the found occurrences and split text around matches.

Here are some examples;


1. Check Email address valid or not (using matches )

println(".....email pattern check....")
val emails = listOf("abc_d@gmail.com", "test!@hotmail.com","abc_d@mailcom",
"343434ffsdkfs#mail", "p6060606@gmail.com","_testmaail$@last.com")

val emailPattern = "[a-zA-Z0-9._-]+@[a-zA-Z0-9-]+\\.[a-zA-Z.]{2,18}".toRegex()

emails.forEach { email ->
if (emailPattern.matches(email)) {
println("$email matches")
} else {
println("$email does not match")
}
}

output:

/* .....email pattern check....
abc_d@gmail.com matches
test!@hotmail.com does not match
abc_d@mailcom does not match
343434ffsdkfs#mail does not match
p6060606@gmail.com matches
_testmaail$@last.com does not match
*/

2.  Find the exact substring(partially word) inside the words in list

 - containsMatchIn

matches

val testWords = listOf("test", "testified", "testing", "techtest",
"exam","labtest", "roadtest", "protest", "tstom", "testimonials")

val pattern = "test".toRegex()

println("*********particular sub string inside the string************")
println("containsMatchIn function")

testWords.forEach{ word ->
if(pattern.containsMatchIn(word)){
println("$word matches")
}else{
println("$word not matches")
}
}



println("********* exact string to another string ************")
println("matches function")

testWords.forEach { word ->
if (pattern.matches(word)) {
println("$word matches")
}else{
println("$word not matches")
}
}

output

/**********particular sub string inside the string************
containsMatchIn function
test matches
testified matches
testing matches
techtest matches
exam not matches
labtest matches
roadtest matches
protest matches
tstom not matches
testimonials matches
********* exact string to another string ************
matches function
test matches
testified not matches
testing not matches
techtest not matches
exam not matches
labtest not matches
roadtest not matches
protest not matches
tstom not matches
testimonials not matches */

3. Find only only from the string or sentence - findAll

findAll
println("....find only numbers.....")
val findNumInText = "Use numerals, however, when the number modifies a unit of measure, time, proportion, etc.: 2 inches, 5-minute delay, 65 mph, 23 years old, page 23, 2 percent. "

val patternN = "\\d+".toRegex()
val founds = patternN.findAll(findNumInText)

founds.forEach { num ->
val foundValue = num.value
println(foundValue)
}

output

/*....find only numbers.....
2
5
65
23
23
2*/

4. Find particular word and its indices in sentence 

println("...Find particular word and its indices in sentence...using\\\\b operator......")
val sent = "But you never know now do you now do you now do you."
val patternIs = "\\byou\\b".toRegex()
val matchesIS = patternIs.findAll(sent)
matchesIS.forEach { word ->
val value = word.value
val index = word.range
println("$value found at indexes: $index")
}

output:

/* ...Find particular word and its indices in sentence...using\\b operator......
you found at indexes: 4..6
you found at indexes: 26..28
you found at indexes: 37..39
you found at indexes: 48..50
*/


If you want know more about regex, please check out this: 

https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/-regex/

https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html



Sorting Array, List, Custom Object and Dates in Kotlin

 Here is some sorting example in KOTLIN.

Sorting Array using ArrayOf

----------

fun sortedArrayOf() {
val array1 = arrayOf(44,6,1,9,23,11,5,19,3)
array1.sort()
println("Sorted array : ${array1.contentToString()}")
}
//output
/*
Sorted array : [1, 3, 5, 6, 9, 11, 19, 23, 44]
*/

IntArray Sorting

----------

fun sortingByIntArray() {
val intArray = intArrayOf(4, 3, 2, 1)
intArray.sort()
println(intArray.joinToString())
// output : 1, 2, 3, 4
}

 Sorting Alphabetically String Array

---------

fun sortingByAlphabetically() {
val stringArray = mutableListOf("ccc", "aab","aaa", "zzz", "bbb")
val tempSortedList = stringArray.sortedWith(compareBy { it }) //it.first() is for first letter only
println("Sorted by ascending: $tempSortedList")
//output: Sorted by ascending: [aaa, aab, bbb, ccc, zzz]
}


Get the first element of String Array

---------

fun getFirstDataOfList() {
val stringArray = mutableListOf("ccc", "aab","aaa", "zzz", "bbb")
val firstElement = stringArray.first()
println("First Element: $firstElement")
//output : First Element: ccc
}

Sorting Date Ascending

---------

fun sortingByDates() {
val dates = mutableListOf(
Date(2020, 3, 8),
Date(2022, 8, 16),
Date(2020, 1, 30),
Date(1999, 1, 5)
)
//useing sortBy
dates.sortBy { it.toString() }
dates.forEach { println(it) }
println(".........")
//using sortWith
dates.sortWith(compareBy<Date> { it.year }.thenBy { it.month }.thenBy { it.day })
dates.forEach { println(it) }
//for descending: dates.reverse()
println(".........")
//using sortedWith
val sortedDates = dates.sortedWith(compareBy<Date> { it.year }.thenBy { it.month }.thenBy { it.day })
sortedDates.forEach { println(it) }
//use for descending .reversed()
}

data class Date(val year: Int, val month: Int, val day: Int)

//output
/*
Date(year=1999, month=1, day=5)
Date(year=2020, month=1, day=30)
Date(year=2020, month=3, day=8)
Date(year=2022, month=8, day=16)
.........
Date(year=1999, month=1, day=5)
Date(year=2020, month=1, day=30)
Date(year=2020, month=3, day=8)
Date(year=2022, month=8, day=16)
.........
Date(year=1999, month=1, day=5)
Date(year=2020, month=1, day=30)
Date(year=2020, month=3, day=8)
Date(year=2022, month=8, day=16)
*/


Sorting Ascending array by adding manually 

---------

fun sortByAddingManually() {
val stringList: MutableList<String> = ArrayList()
stringList.add("ccc")
stringList.add("aab")
stringList.add("aaa")
stringList.add("zzz")
stringList.add("bbb")
stringList.sortBy { it }
stringList.forEach { println(it) }
}
//output
//aaa
//aab
//bbb
//ccc
//zzz


Sorting by custom object

---------------------------

fun sortedCustomObject() {
val persons: MutableList<People> = ArrayList()
persons.add(People("ABC", 61))
persons.add(People("XZY", 30))
persons.add(People("ABB",61))
persons.add(People("XYZ",30))
persons.add(People("ABZ",61))

println(".....Sorted Overall Object.....")
persons.sortBy { it.toString() }
persons.forEach { println(it) }
println(".....Sorted First Name and then Age.....")
val sortedListName = persons.sortedWith(compareBy({ it.name }, { it.age }))
sortedListName.forEach { println(it) }
println(".....Sorted First Age and then Name.....")
val sortedListAge = persons.sortedWith(compareBy({ it.age }, { it.name }))
sortedListAge.forEach { println(it) }
println(".....Sorted First Age and then Name...thenBy....")
persons.sortedWith(compareBy<People> { it.name }.thenBy { it.age })
persons.forEach { println(it) }
println(".....using lambda...")
persons.sortBy { person -> person.age}
persons.forEach { println(it) }

}
data class People(val name:String, val age: Int)

//output
/*
.....Sorted Overall Object.....
People(name=ABB, age=61)
People(name=ABC, age=61)
People(name=ABZ, age=60)
People(name=XYZ, age=30)
People(name=XZY, age=30)
.....Sorted First Name and then Age.....
People(name=ABB, age=61)
People(name=ABC, age=61)
People(name=ABZ, age=60)
People(name=XYZ, age=30)
People(name=XZY, age=30)
.....Sorted First Age and then Name.....
People(name=XYZ, age=30)
People(name=XZY, age=30)
People(name=ABZ, age=60)
People(name=ABB, age=61)
People(name=ABC, age=61)
*/

More details:

https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/sorted.html

I will try to adding more frequently, please keep visiting this blog.