Last active
January 24, 2025 13:48
-
-
Save parthdesai1208/8e79c9f261624137cc3245e46b9e4345 to your computer and use it in GitHub Desktop.
kotlin code example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
************************************************************************************************************************************** | |
Sort without sort function | |
************************************************************************************************************************************** | |
val numbers = mutableListOf(4, 8, 32, 2, 5, 8) | |
var temp: Int | |
for (i in 0 until numbers.size) { | |
for (j in i + 1 until numbers.size) { | |
if (numbers[i] > numbers[j]) { | |
temp = numbers[i] | |
numbers[i] = numbers[j] | |
numbers[j] = temp | |
} | |
} | |
} | |
println(numbers) | |
//[2, 4, 5, 8, 8, 32] | |
************************************************************************************************************************************** | |
Anagram - all character is same on both string but in different position | |
e.g., Triangle & Integral | |
************************************************************************************************************************************** | |
fun main() { | |
val str1 = "Triangle" | |
val str2 = "Integral" | |
if (isAnagram(str1.lowercase(), str2.lowercase())) print( "yes") else print(("no")) | |
} | |
fun isAnagram(a: String, b: String): Boolean { | |
if (a.length != b.length) { | |
return false | |
} | |
val map: HashMap<Char, Int> = HashMap() | |
for (i in a.indices) { | |
if (map.containsKey(a[i])) { | |
map[a.get(i)] = map.get(a.get(i))!! + 1 | |
} else { | |
map[a.get(i)] = 1 | |
} | |
} | |
// Now loop over String b | |
for (i in b.indices) { | |
if (map.containsKey(b[i])) { | |
map[b.get(i)] = map.get(b.get(i))!! - 1 | |
} | |
} | |
val keys: Set<Char> = map.keys | |
for (key: Char in keys) { | |
if (map[key] != 0) { | |
return false | |
} | |
} | |
// Returning True as all keys are zero | |
return true | |
} | |
************************************************************************************************************************************** | |
count duplicate character | |
e.g., abcde = 0 , aabbcde = 2 | |
************************************************************************************************************************************** | |
fun main(){ | |
var s = "abcde" | |
s = s.lowercase() | |
val map = HashMap<Char,Int>() | |
for (i in s.toCharArray()) { | |
if (map.keys.contains(i)) { | |
map[i] = map[i]!!.plus(1) | |
} else { | |
map[i] = 1 | |
} | |
} | |
var count = 0 | |
for (c in map.keys) { | |
if(map[c]!! > 1){ | |
count++ | |
} | |
} | |
println(count) | |
} | |
************************************************************************************************************************************** | |
Getapplication - find recent application in stack | |
statement:- | |
fun main(args: Array<String>) { | |
val array = arrayOf("open chrome","open terminal","open curl","open edge","close 2") | |
val result = getOpenApplications(array) | |
println(result.joinToString("\n")) | |
} | |
************************************************************************************************************************************** | |
code:- | |
fun getOpenApplications(commands: Array<String>): Array<String> { | |
val list = ArrayList<String>() | |
commands.forEach{ | |
when{ | |
it.contains("open") -> { | |
val openApplication = it.split(" ")[1] | |
list.add(openApplication) | |
} | |
it.contains("close") -> { | |
val closeApplication = it.split(" ")[1].toInt() | |
if(closeApplication >= list.size){ | |
list.clear() | |
}else{ | |
repeat((0 until closeApplication).count()) { | |
list.asReversed().removeAt(0) | |
} | |
} | |
} | |
it.contains("clear") -> list.clear() | |
} | |
} | |
return list.toTypedArray() | |
} | |
************************************************************************************************************************************** | |
countsubstring from string that has equal number of 0's & 1's | |
e.g., countSubstring("001100011") output:- 6 | |
************************************************************************************************************************************** | |
fun countSubstring(S: String): Int { | |
var ans = 0 | |
var i = 0 | |
while (i < S.length) { | |
var cnt0 = 0 | |
var cnt1 = 0 | |
if (S[i] == '0') { | |
while (i < S.length && S[i] == '0') { | |
cnt0++ | |
i++ | |
} | |
var j = i | |
while (j < S.length && S[j] == '1') { | |
cnt1++ | |
j++ | |
} | |
} else { | |
while (i < S.length && S[i] == '1') { | |
cnt1++ | |
i++ | |
} | |
var j = i | |
while (j < S.length && S[j] == '0') { | |
cnt0++ | |
j++ | |
} | |
} | |
ans += Math.min(cnt0, cnt1) | |
} | |
return ans | |
} | |
************************************************************************************************************************************** | |
Similar string or not - “(”, “)”, “[”, “]”, “{”, “}” | |
************************************************************************************************************************************** | |
if (isValid("(({{[[))}}")) { | |
Log.e("focus", "valid"); | |
} else { | |
Log.e("focus", "Invalid"); | |
} | |
public static boolean isValid(String S) { | |
boolean result = false; | |
if (S.length() >= 1 && S.length() <= 104) { | |
if (S.length() % 2 == 0) { | |
if (S.contains("(") && S.contains(")")) { | |
if (S.contains("{") && S.contains("}")) { | |
result = S.contains("[") && S.contains("]"); | |
} | |
if (S.contains("[") && S.contains("]")) { | |
result = S.contains("{") && S.contains("}"); | |
} | |
} | |
if (S.contains("{") && S.contains("}")) { | |
if (S.contains("[") && S.contains("]")) { | |
result = S.contains("(") && S.contains(")"); | |
} | |
if (S.contains("(") && S.contains(")")) { | |
result = S.contains("[") && S.contains("]"); | |
} | |
} | |
if (S.contains("[") && S.contains("]")) { | |
if (S.contains("(") && S.contains(")")) { | |
result = S.contains("{") && S.contains("}"); | |
} | |
if (S.contains("{") && S.contains("}")) { | |
result = S.contains("(") && S.contains(")"); | |
} | |
} | |
} | |
} | |
return result; | |
} | |
************************************************************************************************************************************** | |
Sherlock considers a string to be valid if all characters of the string appear the same number of times. | |
It is also valid if he can remove just character at index in the string, and | |
the remaining characters will occur the same number of times. Given a string , | |
determine if it is valid. If so, return YES, otherwise return NO. | |
************************************************************************************************************************************** | |
isValid("abcdefghhgfedecba") | |
private fun isValid(s: String): String { | |
if (s.length in 1..100000) { | |
val distinctCharWithCount = | |
s.toLowerCase().toList().groupingBy { it }.eachCount() | |
val distinctCountWithCount = distinctCharWithCount.values.groupingBy { it }.eachCount() | |
if (distinctCountWithCount.size == 1) { | |
return "YES" | |
} else if (distinctCountWithCount.values.toSet().size == 1) { | |
return "NO" | |
} else { | |
return if (distinctCountWithCount.size == 2) { | |
val minimumCountValueInDistinctCountWithCount = | |
distinctCountWithCount.values.min() | |
val key = | |
distinctCountWithCount.filterValues { it == minimumCountValueInDistinctCountWithCount }.keys.toList()[0] | |
val otherKey = | |
distinctCountWithCount.filterValues { it != minimumCountValueInDistinctCountWithCount }.keys.toList()[0] | |
if (minimumCountValueInDistinctCountWithCount == 1) { | |
if (key == 1) "YES" | |
else //key > 1 | |
if (key - 1 == otherKey) "YES" else "NO" | |
} else { | |
"NO" | |
} | |
} else { | |
"NO" | |
} | |
} | |
} else { | |
return "No" | |
} | |
} | |
************************************************************************************************************************************** | |
Given a square matrix, calculate the absolute difference between the sums of its diagonals. | |
Explanation | |
1 2 3 | |
4 5 6 | |
9 8 9 | |
1+5+9 = 15 | |
3+5+9 = 17 | |
|15-17| = 2 | |
************************************************************************************************************************************** | |
fun diagonalDifference(arr: Array<Array<Int>>): Int { | |
var left_to_right = 0 | |
var right_to_left = 0 | |
val diagonalDifference = 0 | |
val lastIndex = arr.size - 1 | |
arr.forEachIndexed { index, element -> | |
left_to_right = left_to_right + arr[index][index] | |
right_to_left = right_to_left + arr[index][lastIndex - index] | |
} | |
return abs(left_to_right - right_to_left) | |
} | |
************************************************************************************************************************************** | |
print Staircase structure | |
n=4 | |
# | |
## | |
### | |
#### | |
************************************************************************************************************************************** | |
fun staircase(n: Int): Unit { | |
repeat(n){index -> | |
repeat(n-index-1){ print(" ") } | |
repeat(index + 1){ print("#") } | |
if(index - 1 != n) print("\n") | |
} | |
} | |
************************************************************************************************************************************** | |
Print two space-separated long integers denoting the respective minimum and maximum values | |
Input | |
1 2 3 4 5 | |
output | |
10 14 | |
Sum everything except 1, the sum is 2+3+4+5=14 | |
Sum everything except 2, the sum is 1+3+4+5=13 | |
Sum everything except 3, the sum is 1+2+4+5=12 | |
Sum everything except 4, the sum is 1+2+3+5=11 | |
Sum everything except 5, the sum is 1+2+3+4=10 | |
************************************************************************************************************************************** | |
@kotlin.ExperimentalUnsignedTypes | |
fun miniMaxSum(arr: Array<ULong>): Unit { | |
// Write your code here | |
var arrayname = arrayOf(0UL, 0UL, 0UL, 0UL, 0UL) | |
val first = arr[0] | |
val isAllEqual = arr.all { it == first } | |
if(isAllEqual){ | |
arrayname = arr.toList().chunked(arr.size - 1)[0].toTypedArray() | |
println("${arrayname.sum()} ${arrayname.sum()}") | |
}else{ | |
arr.forEachIndexed{index,element -> | |
arrayname[index] = arr.filterNot{ it == element }.sum() | |
} | |
println("${arrayname.toList().min()} ${arrayname.toList().max()}") | |
} | |
} | |
************************************************************************************************************************************** | |
nearest multiple of 5 | |
input | |
73 | |
67 | |
38 | |
33 | |
output | |
75 | |
67 | |
40 | |
33 | |
73 nearest 75 -> 75 - 73 = 2 < 3 then 75 | |
67 nearest 70 -> 70 - 67 = 3 not < 3 then 67 | |
38 nearest 40 -> 40 - 38 = 2 < 3 then 40 | |
33 if < 38 then consider exact value which is 33 | |
************************************************************************************************************************************** | |
fun gradingStudents(grades: Array<Int>): Array<Int> { | |
val rArr = IntArray(grades.size) | |
grades.forEachIndexed { index, i -> | |
if(i in 0 until 38){ | |
rArr[index] = i | |
}else if(i in 38..100){ | |
val nearestMultiple = ceil(i.toDouble() / 5) * 5 | |
if(nearestMultiple - i < 3){ | |
rArr[index] = nearestMultiple.toInt() | |
}else{ | |
rArr[index] = i | |
} | |
} | |
} | |
return rArr.toTypedArray() | |
} | |
************************************************************************************************************************************** | |
Number Line Jumps | |
input - 0 3 4 2 output - YES | |
input - 0 2 5 3 output - NO | |
************************************************************************************************************************************** | |
fun kangaroo(x1: Int, v1: Int, x2: Int, v2: Int): String { | |
val vdiff: Int = v1 - v2 | |
if (vdiff <= 0) { | |
return "NO" | |
} | |
val xdiff = x1 - x2 | |
return if (xdiff % vdiff == 0) "YES" else "NO" | |
} | |
************************************************************************************************************************************** | |
calculate number of integers between the two array that is the factor of all elements of two array | |
2 4 | |
16 32 96 | |
there are only 3 integers 4, 8, 16 (range should be 1st array's max to 2nd array's min value) | |
so answer is 3 | |
************************************************************************************************************************************** | |
fun getTotalX(a: Array<Int>, b: Array<Int>): Int { | |
var returnCounter = 0 | |
(1..100).forEach{oneToHun -> | |
val aCount = a.count { if(oneToHun>it) oneToHun%it==0 else it%oneToHun==0 } | |
val bCount = b.count { if(oneToHun>it) oneToHun%it==0 else it%oneToHun==0 } | |
if(aCount == a.size && bCount == b.size && oneToHun in a.max()..b.min()){ | |
returnCounter += 1 | |
} | |
} | |
return returnCounter | |
} | |
************************************************************************************************************************************** | |
count min score & mac score | |
10 5 20 20 4 5 2 25 1 | |
2 4 | |
game 0 1 2 3 4 5 6 7 8 | |
score 10 5 20 20 4 5 2 25 1 | |
H sco.10 10 20 20 20 20 20 25 25 | |
L sco.10 5 5 5 4 4 2 2 1 | |
2 times highest score | |
4 times lowest score | |
************************************************************************************************************************************** | |
fun breakingRecords(scores: Array<Int>): Array<Int> { | |
val maxScoreArray = IntArray(scores.size) | |
val minScoreArray = IntArray(scores.size) | |
val arr = IntArray(2) | |
scores.forEachIndexed { index, element -> | |
if(index == 0){ | |
maxScoreArray[index] = element | |
minScoreArray[index] = element | |
}else{ | |
maxScoreArray[index] = scores.toList().chunked(index + 1)[0].max() | |
minScoreArray[index] = scores.toList().chunked(index + 1)[0].min() | |
} | |
} | |
arr[0] = maxScoreArray.distinct().size - 1 | |
arr[1] = minScoreArray.distinct().size - 1 | |
return arr.toTypedArray() | |
} | |
************************************************************************************************************************************** | |
Migratory Birds | |
1 4 4 4 5 3 | |
4 | |
4 is repeating 3 times | |
1 2 3 4 5 4 3 2 1 3 4 | |
3 | |
3 & 4 repeating 3 times but consider lower as 3 | |
************************************************************************************************************************************** | |
fun migratoryBirds(arr: Array<Int>): Int { | |
// Write your code here | |
val t = arr.toList().groupingBy { it }.eachCount() | |
val max = t.values.max() | |
val key = t.filterValues { it == max }.keys.toList() | |
return key.min() | |
} | |
************************************************************************************************************************************** | |
Day of programmer | |
1800 | |
12.09.1800 | |
************************************************************************************************************************************** | |
fun dayOfProgrammer(year: Int): String { | |
// Write your code here | |
var str = "" | |
val isLeapYear = if (year >= 1919) { | |
((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0) | |
} else if (year in 1700..1917) { | |
year % 4 == 0 | |
} else { | |
false | |
} | |
var count = 0 | |
(1..12).forEach { i -> | |
count += if (i % 2 == 0 && i != 2 && i != 8) { | |
30 | |
} else { | |
if (i != 2) { | |
31 | |
} else { | |
if (year == 1918) { | |
15 | |
} else { | |
if (isLeapYear) 29 | |
else 28 | |
} | |
} | |
} | |
if (256 - count < 28) { | |
str = "${(256 - count)}.${DecimalFormat("00").format(i + 1)}.${year}" | |
return str | |
} | |
} | |
return str | |
} | |
************************************************************************************************************************************** | |
Bill Division | |
Input:- | |
3 10 2 9 | |
1 | |
12 | |
Output:- | |
5 | |
************************************************************************************************************************************** | |
fun bonAppetit(bill: Array<Int>, k: Int, b: Int): Unit { | |
val totalCost = (bill.sum() - bill[k]) / 2 | |
if (b > totalCost) { | |
print((b - totalCost).toString()) | |
} else { | |
print("Bon Appetit") | |
} | |
} | |
************************************************************************************************************************************** | |
Sales By Match | |
Input:- | |
9 | |
10 20 20 10 10 30 50 10 20 | |
Output:- | |
3 | |
************************************************************************************************************************************** | |
fun sockMerchant(n: Int, ar: Array<Int>): Int { | |
val temp = ar.groupingBy { it }.eachCount() | |
var sum = 0 | |
temp.values.forEach { | |
if(it >= 2) sum += (it/2) | |
} | |
return sum | |
} | |
************************************************************************************************************************************** | |
Drawing book | |
Input:- | |
6 | |
2 | |
output:- | |
1 | |
************************************************************************************************************************************** | |
fun pageCount(n: Int, p: Int): Int { | |
val fromFront = p / 2 | |
val fromBack = if (n % 2 == 0) (n - p + 1) / 2 else (n - p) / 2 | |
return minOf(fromFront, fromBack) | |
} | |
************************************************************************************************************************************** | |
Counting Valley | |
8 | |
UDDDUDUU | |
1 | |
************************************************************************************************************************************** | |
fun countingValleys(steps: Int, path: String): Int { | |
var seaLevel = 0 | |
var valleys = 0 | |
var currentAltitude = 0 | |
path.forEach { step -> | |
if (step == 'U') { | |
currentAltitude++ | |
} else if (step == 'D') { | |
currentAltitude-- | |
if (currentAltitude == -1) { | |
valleys++ | |
} | |
} | |
} | |
return valleys | |
} | |
************************************************************************************************************************************* | |
Sword | |
fun sword(){ | |
val numbers = (1..10).toMutableList() | |
var handOverSword = true //hand over sword to first element, i.e.1 | |
while (numbers.size > 1){ | |
var count = if(handOverSword) 1 else 0 | |
while (count < numbers.size){ | |
handOverSword = count == numbers.size - 1 | |
if(count < numbers.size) numbers.removeAt(count) | |
count++ | |
} | |
} | |
println(numbers) | |
} | |
************************************************************************************************************************************** | |
Electronic shop | |
b = 60 | |
keyboards = [40,50,60] | |
drives = [5,8,12] | |
58 | |
************************************************************************************************************************************** | |
fun getMoneySpent(keyboards: Array<Int>, drives: Array<Int>, budget: Int): Int { | |
var maxCost = -1 | |
for (keyboardPrice in keyboards) { | |
for (drivePrice in drives) { | |
val totalCost = keyboardPrice + drivePrice | |
if (totalCost in (maxCost + 1)..budget) { | |
maxCost = totalCost | |
} | |
} | |
} | |
return maxCost | |
} | |
************************************************************************************************************************************** | |
cat and mouse | |
x=2,y=5,z=4 | |
Cat B | |
************************************************************************************************************************************** | |
fun catAndMouse(x: Int, y: Int, z: Int): String { | |
val distanceFromCatA = Math.abs(x - z) | |
val distanceFromCatB = Math.abs(y - z) | |
return when { | |
distanceFromCatA < distanceFromCatB -> "Cat A" | |
distanceFromCatB < distanceFromCatA -> "Cat B" | |
else -> "Mouse C" | |
} | |
} | |
************************************************************************************************************************************** | |
Climbing the Leaderboard | |
input: | |
100,100,50,40,40,20,10 | |
5,25,50,120 | |
output: | |
6,4,2,1 | |
************************************************************************************************************************************** | |
fun climbingLeaderboard(ranked: Array<Int>, player: Array<Int>): Array<Int> { | |
val distinctRanked = ranked.distinct() | |
val result = mutableListOf<Int>() | |
var i = distinctRanked.lastIndex | |
player.forEach { _player -> | |
while (i >= 0 && _player >= distinctRanked[i]) { | |
i-- | |
} | |
result.add(i + 2) | |
} | |
return result.toTypedArray() | |
} | |
************************************************************************************************************************************** | |
reverse string word without using inbuilt kotlin collections | |
input = "I LOVE INDIA" | |
output = "INDIA LOVE I" | |
************************************************************************************************************************************** | |
val input = "I LOVE APPLE" | |
val inputList = mutableListOf<String>() | |
var temp = "" | |
input.forEachIndexed { index, character -> | |
temp += character | |
if (character == ' ' || index == input.length - 1) { | |
inputList.add(temp.trim()) | |
temp = "" | |
} | |
} | |
val outputList = mutableListOf<String>() | |
for (i in (inputList.size - 1) downTo 0) { | |
outputList.add(inputList.get(i)) | |
} | |
var output = "" | |
for (i in outputList) { | |
output += "$i " | |
} | |
println(output.trim()) | |
************************************************************************************************************************************** | |
Even index character in upper & odd in lower case without using inbuilt kotlin collections | |
input = "I LOVE APPLE" | |
output = "I LoVe ApPlE" | |
************************************************************************************************************************************** | |
val input = "I LOVE APPLE" | |
val inputList = mutableListOf<String>() | |
var temp = "" | |
input.forEachIndexed { index, character -> | |
temp += character | |
if (character == ' ' || index == input.length -1) { | |
inputList.add(temp.trim()) | |
temp = "" | |
} | |
} | |
val str = StringBuilder() | |
inputList.forEach { inputListString -> | |
str.append(" ") | |
inputListString.forEachIndexed { index, c -> | |
if(index % 2 == 0) str.append(c.uppercase()) | |
else str.append(c.lowercase()) | |
} | |
} | |
println(str) | |
************************************************************************************************************************************** | |
Password Decryption | |
you have given a string, loop through the string | |
1) if s[i] is lowerCase & next character s[i+1] is upperCase, swap them, add '*' after them, & move to i+2 | |
2) if s[i] is number, replace it with 0, place original number at start, move to i+1 | |
3) else move to i+1 | |
4) stop when you reach at end of string | |
input = aP1pL5e | |
output = 51Pa*0Lp*0e | |
************************************************************************************************************************************** | |
val s = "aP1pL5e" | |
val result = s.toMutableList() | |
var i = 0 | |
var resultPointer = 0 | |
while (i < s.length - 1) { | |
when { | |
s[i].isDigit() -> { | |
result.set(resultPointer, '0') | |
result.add(0, s[i]).also { resultPointer += 2 } //to go ahead of i | |
i += 1 | |
} | |
s[i].isLowerCase() && s[i + 1].isUpperCase() -> { | |
result[resultPointer] = s[i + 1].also { result[resultPointer + 1] = s[i] } //swap | |
result.add(resultPointer + 2, '*').also { resultPointer += 3 } //to go ahead of i | |
i += 2 | |
} | |
else -> { | |
i += 1 | |
} | |
} | |
} | |
println(result.joinToString("")) | |
************************************************************************************************************************************** | |
xxxx | |
************************************************************************************************************************************** |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment