Programs in Kotlin
Program to display the length of the string using higher order function by accepting String array and lambda expression as input fun main() {
val data = listOf("Keshav", "Pai")
var result = IntArray(data.size)
val lambda : (List<String>) -> IntArray = { data ->
for(i in 0..data.size-1) {
result[i] = data[i].length
}
result
}
addTwoNumbers(data, lambda)
}
fun addTwoNumbers(stringList : List<String>, lambdaResult : (List<String>) -> IntArray) {
var result = lambdaResult(stringList)
for(i in result) {
println(i)
}
}
Program to add 2 numbers using higher order function and lambda expression
fun main() {
val lambdaResult : (Int, Int) -> Int = { x, y -> x + y}
addTwoNumbers(3, 8, lambdaResult)
addTwoNumbers(3, 8, { x : Int, y : Int -> x + y}) addTwoNumberss(3, 8) { x : Int, y : Int -> x + y}
}
fun addTwoNumbers(a : Int, b : Int, action : (Int, Int) -> Int) {
val result = action(a, b)
println(result)
}
Program to find the occurrence of a particular character in a String using Kotlin
fun main(args: Array<String>) {
val str = "This website is awesome."
val ch = 'e'
var frequency = 0
for (i in 0..str.length - 1) {
if (ch == str[i]) {
++frequency
}
}
println("Frequency of $ch = $frequency")
}
Using replace
fun countOccurrences(s: String, ch: Char): Int {
return s.length - s.replace(ch.toString(), "").length
}
fun main() {
val s = "Eeny, meeny, miny, moe"
println(countOccurrences(s, 'e')) // 4
}
Using Frequency Map
fun getFreqMap(chars: String): Map<Char, Int> {
val freq: MutableMap<Char, Int> = HashMap()
for (c in chars) {
freq.putIfAbsent(c, 0)
freq[c] = freq[c]!! + 1
}
return freq
}
fun main() {
val s = "Eeny, meeny, miny, moe"
val ch = 'e'
val freq = getFreqMap(s)[ch]
println(freq) // 4
}
Program to find Repeated/Duplicate Characters of String
Kotlin
import java.util.HashMap
fun main(a: Array<String>) {
var s = "aabbccA"
s = s.toLowerCase()
val map = HashMap()
for (i in s.toCharArray()) {
if (map.keys.contains(i)) {
var x = map[i]
map[i] = 1+x!!
} else {
map[i] = 1
}
}
for (c in map.keys) {
println(c + " " + map[c])
}
}Output :
a 3
b 2
c 2
Java
Algorithm
Define a string.
Two loops will be used to find the duplicate characters. Outer loop will be used to select a
character and initialize variable count by 1.
Inner loop will compare the selected character with rest of characters present in the string.
If a match found, it increases the count by 1 and set the duplicates of selected character
by '0' to mark them as visited.
After inner loop, if count of character is greater than 1, then it has duplicates in the
string
public class DuplicateCharacters {
public static void main(String[] args) {
String string1 = "Great responsibility";
int count;
//Converts given string into character array
char string[] = string1.toCharArray();
System.out.println("Duplicate characters in a given string: ");
//Counts each character present in the string
for(int i = 0; i <string.length; i++) {
count = 1;
for(int j = i+1; j <string.length; j++) {
if(string[i] == string[j] && string[i] != ' ') {
count++;
//Set string[j] to 0 to avoid printing visited character
string[j] = '0';
}
}
//A character is considered as duplicate if count is greater than 1
if(count > 1 && string[i] != '0')
System.out.println(string[i]);
}
}
}
Output :
Duplicate characters in a given string:
r
e
t
s
i
Remove duplicates from an integer Array using Set
Kotlin
fun removeDuplicates(array: IntArray): IntArray{
return array.toSet().toIntArray()
}
fun main() {
val array: IntArray = intArrayOf(2, 4, 1, 2, 1, 2, 4, 5)
val distinct = removeDuplicates(array)
println(distinct.contentToString()) // [1, 2, 4, 5]
}
Kotlin Sorting
fun removeDuplicates(array: IntArray): IntArray {
array.sort()
var k = 0
for (i in array.indices) {
if (i == 0 || array[i] != array[i - 1]) {
array[k++] = array[i]
}
}
return array.copyOf(k)
}
fun main() {
val array: IntArray = intArrayOf(2, 4, 1, 2, 1, 2, 4, 5)
val distinct = removeDuplicates(array)
println(distinct.contentToString()) // [1, 2, 4, 5]
}
Java
public static void removeDuplicates() {
int arr[] = {1, 4, 5, 5, 7, 7, 5, 5, 4, 4, 10, 14};
LinkedHashSet<Integer> set = new LinkedHashSet<Integer>();
// adding elements to LinkedHashSet
for (int i = 0; i < arr.length; i++)
set.add(arr[i]);
// Print the elements of LinkedHashSet
System.out.print("Duplicate "+set); }
Program to remove duplicates from ArrayList
Copying all the elements of ArrayList to LinkedHashSet.fun main(args: Array<String>) {
Why we choose LinkedHashSet? Because it removes duplicates and maintains the insertion order.
Emptying the ArrayList, you can use clear() method to remove all elements of ArrayList and start fresh.
Copying all the elements of LinkedHashSet (non-duplicate elements) to the ArrayList.
// creating ArrayList with duplicate elements
val primes = listOf(2, 3, 4, 5, 5, 7)
// let's print arraylist with duplicate*/
println("list of prime numbers : $primes")
// Now let's remove duplicate element without affecting order
// LinkedHashSet will guaranteed the order and since it's set
// it will not allow us to insert duplicates.
// repeated elements will automatically filtered.
val primesWithoutDuplicates: Set<Int> = LinkedHashSet(primes)
// now let's clear the ArrayList so that we can copy all elements from LinkedHashSet
/* primes.clear() // copying elements but without any duplicates
primes.addAll(primesWithoutDuplicates)
println("list of primes without duplicates : $primes")*/
println("list of primes without duplicates : $primesWithoutDuplicates")
}
Sorting Integer ArrayList in Ascending and Descending Order
Kotlin
fun main() {
val numsList = listOf(1,5,2,88,33,56,23,10)
//Ascending Order
val sortAsc = numsList.sorted() println(sortAsc)
//Descending Order val sortDesc = numsList.sortedDescending()
println(sortDesc) //Reverse val sortReverse = numsList.reversed() println(sortDesc)
}
Java
import java.util.ArrayList;
import java.util.Collections;
public class SortArrayListExample1
{
public static void main(String args[])
{
// creating object of ArrayList class
ArrayList<String> list = new ArrayList<String>();
// adding elements to the ArrayList
list.add("Volkswagen");
list.add("Toyota");
list.add("Porsche");
list.add("Ferrari");
// printing the unsorted ArrayList
System.out.println("Before Sorting: "+ list);
// Sorting ArrayList in ascending Order
Collections.sort(list);// Sorting ArrayList in descending Order Collections.sort(list, Collections.reverseOrder());// printing the sorted ArrayList
System.out.println("After Sorting: "+ list);
}
}
Sorting Array using Bubble Sort
fun main(args: Array<String>) {
//testing our bubble sort method in Java
val unsorted = intArrayOf(32, 39, 21, 45, 23, 3)
bubbleSort(unsorted)
//one more testing of our bubble sort code logic in Java
val test = intArrayOf(5, 3, 2, 1)
bubbleSort(test)
}
/*
* In bubble sort we need n-1 iteration to sort n elements
* at end of first iteration larget number is sorted and subsequently numbers smaller
* than that.
*/
fun bubbleSort(unsorted: IntArray) {
System.out.println("unsorted array before sorting : " + Arrays.toString(unsorted))
// Outer loop - need n-1 iteration to sort n elements
for (i in 0 until unsorted.size - 1) {
//Inner loop to perform the comparison and swapping between adjacent numbers
//After each iteration one index from last is sorted
for (j in 1 until unsorted.size - i) {
//If the current number is greater than swap those two
if (unsorted[j - 1] > unsorted[j]) {
val temp = unsorted[j]
unsorted[j] = unsorted[j - 1]
unsorted[j - 1] = temp
}
}
System.out.printf(
"unsorted array after %d pass %s: %n",
i + 1,
Arrays.toString(unsorted)
)
}
}
Reverse ArrayList
fun main(args: Array<String>) {
val listOfInts: ArrayList<String?> = ArrayList()
listOfInts.add("1")
listOfInts.add("2")
listOfInts.add("3")
listOfInts.add("4")
listOfInts.add("5")
println("Before Reversing : $listOfInts")
Collections.reverse(listOfInts)
println("After Reversing : $listOfInts")
}
Merge two sorted arrays
Kotlin :
// Java program to merge two sorted arrays
import java.util.*;
import java.lang.*;
import java.io.*;internal object MergeTwoSorted {
// Merge arr1[0..n1-1] and arr2[0..n2-1]
// into arr3[0..n1+n2-1]
fun mergeArrays(
arr1: IntArray, arr2: IntArray, n1: Int,
n2: Int, arr3: IntArray
) {
var i = 0
var j = 0
var k = 0
// Traverse both array
while (i < n1 && j < n2) {
// Check if current element of first
// array is smaller than current element
// of second array. If yes, store first
// array element and increment first array
// index. Otherwise do same with second array
if (arr1[i] < arr2[j]) arr3[k++] = arr1[i++] else arr3[k++] = arr2[j++]
}
// Store remaining elements of first array
while (i < n1) arr3[k++] = arr1[i++]
// Store remaining elements of second array
while (j < n2) arr3[k++] = arr2[j++]
}
@JvmStatic
fun main(args: Array<String>) {
val arr1 = intArrayOf(1, 3, 5, 7)
val n1 = arr1.size
val arr2 = intArrayOf(2, 4, 6, 8)
val n2 = arr2.size
val arr3 = IntArray(n1 + n2)
mergeArrays(arr1, arr2, n1, n2, arr3)
println("Array after merging")
for (i in 0 until n1 + n2) print(arr3[i].toString() + " ")
}
}
*********************************************
// Java program to merge two sorted arrays
//using mapsinternal object Test {
// Function to merge arrays
fun mergeArrays(a: IntArray, b: IntArray, n: Int, m: Int) {
// Declaring a map.
// using map as a inbuilt tool
// to store elements in sorted order.
val mp: MutableMap<Int, Boolean> = HashMap()
// Inserting values to a map.
for (i in 0 until n) {
mp[a[i]] = true
}
for (i in 0 until m) {
mp[b[i]] = true
}
// Printing keys of the map.
for ((key) in mp) {
print("$key ")
}
}
// Driver Code
@JvmStatic
fun main(args: Array<String>) {
val a = intArrayOf(1, 3, 5, 7)
val b = intArrayOf(2, 4, 6, 8)
val size = a.size
val size1 = b.size
// Function call
mergeArrays(a, b, size, size1)
}
}
Java
// Java program to merge two sorted arrays using maps
import java.io.*;
import java.util.*;
class GFG {
// Function to merge arrays
static void mergeArrays(int a[], int b[], int n, int m)
{
// Declaring a map.
// using map as a inbuilt tool
// to store elements in sorted order.
Map<Integer,Boolean> mp = new TreeMap<Integer,Boolean>();
// Inserting values to a map.
for(int i = 0; i < n; i++)
{
mp.put(a[i], true);
}
for(int i = 0;i < m;i++)
{
mp.put(b[i], true);
}
// Printing keys of the map.
for (Map.Entry<Integer,Boolean> me : mp.entrySet())
{
System.out.print(me.getKey() + " ");
}
}
// Driver Code
public static void main (String[] args)
{
int a[] = {1, 3, 5, 7}, b[] = {2, 4, 6, 8};
int size = a.length;
int size1 = b.length;
// Function call
mergeArrays(a, b, size, size1);
}
}
// Java program to merge two sorted arrays
import java.util.*;
import java.lang.*;
import java.io.*;
class MergeTwoSorted
{
// Merge arr1[0..n1-1] and arr2[0..n2-1]
// into arr3[0..n1+n2-1]
public static void mergeArrays(int[] arr1, int[] arr2, int n1,
int n2, int[] arr3)
{
int i = 0, j = 0, k = 0;
// Traverse both array
while (i<n1 && j <n2)
{
// Check if current element of first
// array is smaller than current element
// of second array. If yes, store first
// array element and increment first array
// index. Otherwise do same with second array
if (arr1[i] < arr2[j])
arr3[k++] = arr1[i++];
else
arr3[k++] = arr2[j++];
}
// Store remaining elements of first array
while (i < n1)
arr3[k++] = arr1[i++];
// Store remaining elements of second array
while (j < n2)
arr3[k++] = arr2[j++];
}
public static void main (String[] args)
{
int[] arr1 = {1, 3, 5, 7};
int n1 = arr1.length;
int[] arr2 = {2, 4, 6, 8};
int n2 = arr2.length;
int[] arr3 = new int[n1+n2];
mergeArrays(arr1, arr2, n1, n2, arr3);
System.out.println("Array after merging");
for (int i=0; i < n1+n2; i++)
System.out.print(arr3[i] + " ");
}
}
Merging two unsorted arrays in sorted order
Java
Method 1 (first Concatenate then Sort)
// Java Code for Merging two unsorted arrays in sorted order
import java.util.*;
class GFG {
// Function to merge array in sorted order
public static void sortedMerge(int a[], int b[], int res[], int n, int m)
{
// Concatenate two arrays
int i = 0, j = 0, k = 0;
while (i < n) {
res[k] = a[i];
i++;
k++;
}
while (j < m) {
res[k] = b[j];
j++;
k++;
}
// sorting the res array
Arrays.sort(res);
}
/* Driver program to test above function */
public static void main(String[] args)
{
int a[] = { 10, 5, 15 };
int b[] = { 20, 3, 2, 12 };
int n = a.length;
int m = b.length;
// Final merge list
int res[]=new int[n + m];
sortedMerge(a, b, res, n, m);
System.out.print("Sorted merged list :");
for (int i = 0; i < n + m; i++)
System.out.print(" " + res[i]);
}
}
Method 2 (First Sort then Merge)
// JAVA Code for Merging two unsorted arrays in sorted order
import java.util.*;
class GFG {
// Function to merge array in sorted order
public static void sortedMerge(int a[], int b[], int res[], int n, int m) {
// Sorting a[] and b[]
Arrays.sort(a);
Arrays.sort(b);
// Merge two sorted arrays into res[]
int i = 0, j = 0, k = 0;
while (i < n && j < m) {
if (a[i] <= b[j]) {
res[k] = a[i];
i += 1;
k += 1;
} else {
res[k] = b[j];
j += 1;
k += 1;
}
}
while (i < n) { // Merging remaining
// elements of a[] (if any)
res[k] = a[i];
i += 1;
k += 1;
}
while (j < m) { // Merging remaining
// elements of b[] (if any)
res[k] = b[j];
j += 1;
k += 1;
}
}
/* Driver program to test above function */
public static void main(String[] args)
{
int a[] = { 10, 5, 15 };
int b[] = { 20, 3, 2, 12 };
int n = a.length;
int m = b.length;
// Final merge list
int res[] = new int[n + m];
sortedMerge(a, b, res, n, m);
System.out.print( "Sorted merged list :");
for (int i = 0; i < n + m; i++)
System.out.print(" " + res[i]);
}
}
LinkedList descendingIterator() returns an iterator that iterates over the element in the reverse
order. We can use this iterator to create a new Linked List with elements in the reverse order
LinkedList<Integer> ll = new LinkedList<>();
ll.add(1);
ll.add(2);
ll.add(3);
System.out.println(ll);
LinkedList<Integer> ll1 = new LinkedList<>();
ll.descendingIterator().forEachRemaining(ll1::add);
System.out.println(ll1);
Program to count the occurrence of each character in a string using Hashmap
Declare a Hashmap in Java of {char, int}.
Traverse in the string, check if the Hashmap already contains the traversed character or not.
If it is present, then increase its count using get() and put() function in Hashmap.
Once the traversal is completed, traverse in the Hashmap and print the character and its frequency.
// Java program to count frequencies of
// characters in string using Hashmap
import java.io.*;
import java.util.*;
class OccurenceOfCharInString {
static void characterCount(String inputString)
{
// Creating a HashMap containing char as a key and occurrences as a value
HashMap<Character, Integer> charCountMap
= new HashMap<Character, Integer>();
// Converting given string to char array
char[] strArray = inputString.toCharArray();
// checking each char of strArray
for (char c : strArray) {
if (charCountMap.containsKey(c)) {
// If char is present in charCountMap,
// incrementing it's count by 1
charCountMap.put(c, charCountMap.get(c) + 1);
} else {
// If char is not present in charCountMap,
// putting this char to charCountMap with 1 as it's value
charCountMap.put(c, 1);
}
}
// Printing the charCountMap
for (Map.Entry entry : charCountMap.entrySet()) {
System.out.println(entry.getKey() + " " + entry.getValue());
}
}
// Driver Code
public static void main(String[] args) {
String str = "Ajit";
characterCount(str);
}
}
Traverse in the string, check if the Hashmap already contains the traversed character or not.
If it is present, then increase its count using get() and put() function in Hashmap.
Once the traversal is completed, traverse in the Hashmap and print the character and its frequency.
// Java program to count frequencies of
// characters in string using Hashmap
import java.io.*;
import java.util.*;
class OccurenceOfCharInString {
static void characterCount(String inputString)
{
// Creating a HashMap containing char as a key and occurrences as a value
HashMap<Character, Integer> charCountMap
= new HashMap<Character, Integer>();
// Converting given string to char array
char[] strArray = inputString.toCharArray();
// checking each char of strArray
for (char c : strArray) {
if (charCountMap.containsKey(c)) {
// If char is present in charCountMap,
// incrementing it's count by 1
charCountMap.put(c, charCountMap.get(c) + 1);
} else {
// If char is not present in charCountMap,
// putting this char to charCountMap with 1 as it's value
charCountMap.put(c, 1);
}
}
// Printing the charCountMap
for (Map.Entry entry : charCountMap.entrySet()) {
System.out.println(entry.getKey() + " " + entry.getValue());
}
}
// Driver Code
public static void main(String[] args) {
String str = "Ajit";
characterCount(str);
}
}
Sorting an array in Java
int[] array = {1, 2, 3, -1, -2, 4};
Arrays.sort(array);
System.out.println(Arrays.toString(array));
Palindrome Number
Java
class PalindromeExample{
public static void main(String args[]){
int r,sum=0,temp;
int n=454;//It is the number variable to be checked for palindrome
temp=n;
while(n>0){
r=n%10; //getting remainder
sum=(sum*10)+r;
n=n/10;
}
if(temp==sum)
System.out.println("palindrome number ");
else
System.out.println("not palindrome");
}
}
/*
* Java method to check if a number is palindrome or not
*/fun isPalindrome(number: Int): Boolean {
var palindrome = number // copied number into variable
var reverse = 0
while (palindrome != 0) {
val remainder = palindrome % 10
reverse = reverse * 10 + remainder
palindrome = palindrome / 10
}
// if original and reverse of number is equal means
// number is palindrome in Java
return number == reverse
}Output:
Please Enter a number :
123
Number : 123 is not a palindrome
Please Enter a number :
121
Number : 121 is a palindrome
Program to check if entered string is Palindrome
Java
public class PalindromeChecker {
public static boolean isPalindrome(String str){
StringBuilder sb=new StringBuilder(str);
sb.reverse();
String rev=sb.toString();
if(str.equals(rev)){
return true;
}else{
return false;
}
}
public static void main(String[] args) {
System.out.println(PalindromeChecker.isPalindrome("nitin"));
System.out.println(PalindromeChecker.isPalindrome("jatin"));
}
}
fun main(args: Array<String>) {
val input = "Madam"
val number = 12321
System.out.printf("Is %s a palindrome? : %b %n", input, isPalindrome(input))
System.out.printf("Is %s a palindrome? : %b %n", number, isPalindrome(number))
}
/*
* Java method to check if a string is palindrome or not
*/
fun isPalindrome(input: String?): Boolean {
if (input == null || input.isEmpty()) {
return true
}
val array = input.toCharArray()
val sb = StringBuilder(input.length)
for (i in input.length - 1 downTo 0) {
sb.append(array[i])
}
val reverseOfString = sb.toString()
return input == reverseOfString
}
/*
* Java method to check if a number is palindrome or not
*/
fun isPalindrome(number: Int): Boolean {
var palindrome = number // copied number into variable
var reverse = 0
while (palindrome != 0) {
val remainder = palindrome % 10
reverse = reverse * 10 + remainder
palindrome = palindrome / 10
}
// if original and reverse of number is equal means
// number is palindrome in Java
return number == reverse
}
Palindrome Check
fun checkPalindromeString(input: String): Boolean {
var result = true
val length = input.length
for (i in 0 until length / 2) {
if (input[i] != input[length - i - 1]) {
result = false
break
}
}
return result
}
Program to check if the given number is Prime
Java
public class PrimeExample{
public static void main(String args[]){
int i,m=0,flag=0;
int n=3;//it is the number to be checked
m=n/2;
if(n==0||n==1){
System.out.println(n+" is not prime number");
}else{
for(i=2;i<=m;i++){
if(n%i==0){
System.out.println(n+" is not prime number");
flag=1;
break;
}
}
if(flag==0) { System.out.println(n+" is prime number"); }
}//end of else
}
}
Kotlin
Program to Check Prime Number using a for-in loop
fun main(args: Array<String>) {
val num = 29
var flag = false
for (i in 2..num / 2) {
// condition for nonprime number
if (num % i == 0) {
flag = true
break
}
}
if (!flag)
println("$num is a prime number.")
else
println("$num is not a prime number.")
}
Program to Check Prime Number using a while loop
fun main(args: Array<String>) {
val num = 33
var i = 2
var flag = false
while (i <= num / 2) {
// condition for nonprime number
if (num % i == 0) {
flag = true
break
}
++i
}
if (!flag)
println("$num is a prime number.")
else
println("$num is not a prime number.")
}
Program to find sum of prime numbers between 1 to n
Java
Using For Loop
public class SumOfPrimeNumbers1 {
public static void main(String args[]) {
int count, sum = 0;
//the loop executes 100 time and increments the variable number by 1 after each iteration
for (int number = 1; number <= 200; number++) {
count = 0;
for (int i = 2; i <= number / 2; i++) {
//find the remainder and check if it is equal to 0 or not
if (number % i == 0) {
//increments the count variable by 1 if the above condition returns true
count++;
break;
} //end of if statement
} //end of for loop
//returns true if both conditions are true
if (count == 0 && number != 1) {
//calculates the sum of prime numbers
sum = sum + number;
} //end of if statement
} //end of for loop
//prints the sum
System.out.println("The Sum of Prime Numbers from 1 to 200 is: " + sum);
} //end of main
}
Using while Loop
public class SumOfPrimeNumbersExample2
{
public static void main(String args[])
{
int number = 1, count, sum = 0;
//executes until the condition becomes false
while(number <= 100)
{
count = 0;
int i = 2;
while(i <= number/2 )
{
//find the remainder and check if it is equal to 0 or not
if(number % i == 0)
{
//increments the count variable by 1 if the above condition returns true
count++;
break;
}
//increments the variable i by 1
i++;
} //end of while
if(count == 0 && number != 1 ) {
//calculates the sum of prime numbers
sum = sum + number;
} //end of if statement
//increments the variable number by 1 after completing each iteration
number++;
} //end of while
//prints the sum
System.out.println("The Sum of Prime Numbers from 1 to 100 is: " + sum);
} //end of main
} //end of class
// Returns sum of primes
// in range from
// 1 to n.
fun sumOfPrimes(n: Int): Int {
// Array to store prime numbers
val prime = BooleanArray(n + 1)
// Create a boolean array "prime[0..n]"
// and initialize all entries it as true.
// A value in prime[i] will finally be
// false if i is Not a prime, else true.
Arrays.fill(prime, true)
var p = 2
while (p * p <= n) {
// If prime[p] is not changed, then
// it is a prime
if (prime[p] == true) {
// Update all multiples of p
var i = p * 2
while (i <= n) {
prime[i] = false
i += p
}
}
p++
}
// Return sum of primes generated through
// Sieve.
var sum = 0
for (i in 2..n) if (prime[i]) sum += i
return sum
}
// Driver code
fun main(args: Array<String>) {
val n = 11
print(sumOfPrimes(n))
}
Program to check if a vowel is present in the string
object StringContainsVowels {
@JvmStatic
fun main(args: Array<String>) {
println(stringContainsVowels("Hello")) // true
println(stringContainsVowels("TV")) // false
}
fun stringContainsVowels(input: String): Boolean {
return input.toLowerCase().matches(".*[aeiou].*")
}
}
Swap two numbers without using a third variable
fun swapNumbers(a: Int, b: Int) {
var a = a
var b = b
b = b + a
a = b - a
b = b - a
}
@JvmStatic
fun main(args: Array<String>) {
val a = 10
val b = 20
swapNumbers(a, b)
System.out.printf("a is %d, b is %d", a, b) // a is 10, b is 20
}
Remove Duplicates from String using Hashing
object RemoveDuplicatesExample3 {
//Create removeDuplicates() method for removing duplicates using LinkedHashSet
fun removeDuplicates(str: String) {
//Create LinkedHashSet of type character
val set: LinkedHashSet<Char> = LinkedHashSet()
//Add each character of the string into LinkedHashSet
for (i in 0 until str.length) set.add(str[i])
// print the string after removing duplicate characters
for (ch in set) print(ch)
}
//main() method start
@JvmStatic
fun main(args: Array<String>) {
//Create string variable with default value
val str = "javaTpoint is the best learning website"
//removeDuplicates() method by passing the string as an argument
removeDuplicates(str)
}
}
Remove Duplicates from String using ForLoop
object RemoveDuplicatesExample1 {
//Creating removeDuplicates() method to remove duplicates from array
fun removeDuplicate(str: CharArray, length: Int) {
//Creating index variable to use it as index in the modified string
var index = 0
// Traversing character array
for (i in 0 until length) {
// Check whether str[i] is present before or not
var j: Int
j = 0
while (j < i) {
if (str[i] == str[j]) {
break
}
j++
}
// If the character is not present before, add it to resulting string
if (j == i) {
str[index++] = str[i]
}
}
println(java.lang.String.valueOf(Arrays.copyOf(str, index)))
}
// main() method starts
@JvmStatic
fun main(args: Array<String>) {
val info = "javaTpoint is the best learning website"
//Converting string to character array
val str = info.toCharArray()
//Calculating length of the character array
val len = str.size
//Calling removeDuplicates() method to remove duplicate characters
removeDuplicate(str, len)
}
}
Factorial of an integer
The factorial of an integer is calculated by multiplying all the numbers from 1 to the given number.
F(n) = F(1)*F(2)…F(n-1)*F(n).
We can use recursion to find the factorial of an integer.
public static long factorial(long n) {
if (n == 1)
return 1;
else
return (n * factorial(n - 1));
}fun factorial(n: Long): Long {
return if (n == 1L) 1 else n * factorial(n - 1)
}
Factorial of a number
object FactorialInJava {
@JvmStatic
fun main(args: Array<String>) {
//finding factorial of a number in Java using recursion - Example
println("factorial of 5 using recursion in Java is: " + factorial(5))
//finding factorial of a number in Java using Iteration - Example
println("factorial of 6 using iteration in Java is: " + fact(6))
}
/*
* Java program example to find factorial of a number using recursion
* @return factorial of number
*/
fun factorial(number: Int): Int {
//base case
return if (number == 0) {
1
} else number * factorial(number - 1)
//is this tail-recursion?
}
/*
* Java program example to calculate factorial using while loop or iteration
* @return factorial of number
*/
fun fact(number: Int): Int {
var number = number
var result = 1
while (number != 0) {
result = result * number
number--
}
return result
}
}
Reverse a String
fun main(args: Array<String>) {
var word = "HelloWorld"
var reverse = StringBuffer(word).reverse().toString()
println(reverse)
word = "WakeUp"
reverse = StringBuilder(word).reverse().toString()
println(reverse)
word = "Band"
reverse = reverse(word)
println(reverse)
}
fun reverse(source: String): String {
if (source == null || source.isEmpty()) {
return source
}
var reverse = ""
for (i in source.length - 1 downTo 0) {
reverse = reverse + source[i]
}
return reverse
}
Check for Anagram
Java
import java.util.Arrays;
class Main {
public static void main(String[] args) {
String str1 = "Race";
String str2 = "Care";
str1 = str1.toLowerCase();
str2 = str2.toLowerCase();
// check if length is same
if(str1.length() == str2.length()) {
// convert strings to char array
char[] charArray1 = str1.toCharArray();
char[] charArray2 = str2.toCharArray();
// sort the char array
Arrays.sort(charArray1);
Arrays.sort(charArray2);
// if sorted char arrays are same
// then the string is anagram
boolean result = Arrays.equals(charArray1, charArray2);
if(result) {
System.out.println(str1 + " and " + str2 + " are anagram.");
}
else {
System.out.println(str1 + " and " + str2 + " are not anagram.");
}
}
else {
System.out.println(str1 + " and " + str2 + " are not anagram.");
}
}
}
/**
* Function to check two strings are anagram string or not using Kotlin
*/
fun isAnagrams(str1: String, str2: String): Boolean {
//Both String Length must be Equal
if (str1.length != str2.length) {
return false
}
//Convert Strings to character Array
val strArray1 = str1.toCharArray()
val strArray2 = str2.toCharArray()
//Sort the Arrays
Arrays.sort(strArray1)
Arrays.sort(strArray2)
//Convert Arrays to String
val sortedStr1 = String(strArray1)
val sortedStr2 = String(strArray2)
//Check Both String Equals or not After Sorting
//and Return value True or False
return sortedStr1 == sortedStr2
}
//Main Function, entry Point of Program
fun main(args: Array<String>) {
//Input Stream
val sc = Scanner(System.`in`)
//Enter String Value
println("Enter String1 : ")
val str1: String = sc.nextLine()
println("Enter String2 : ")
val str2: String = sc.next()
//Call Function to check anagram String
if (isAnagrams(str1, str2)) {
println("Anagram Strings !!")
} else {
println("Strings are not Anagram !!")
}
}
fun main(args: Array<String>) {
val ans = iAnagram("programming", "prgoramgmin")
println(ans)
}
fun iAnagram(word: String, anagram: String): Boolean {
val charFromWord = word.toCharArray()
val charFromAnagram = anagram.toCharArray()
Arrays.sort(charFromWord)
Arrays.sort(charFromAnagram)
return Arrays.equals(charFromWord, charFromAnagram)
}
Print Full Pyramid Pattern
Java *
public class Main {
public static void main(String[] args) {
int rows = 5, k = 0;
for (int i = 1; i <= rows; ++i, k = 0) {
for (int space = 1; space <= rows - i; ++space) {
System.out.print(" ");
}
while (k != 2 * i - 1) {
System.out.print("* ");
++k;
}
System.out.println();
}
}
}
Java Numbers
public class Main {
public static void main(String[] args) {
int rows = 5, k = 0, count = 0, count1 = 0;
for (int i = 1; i <= rows; ++i) {
for (int space = 1; space <= rows - i; ++space) {
System.out.print(" ");
++count;
}
while (k != 2 * i - 1) {
if (count <= rows - 1) {
System.out.print((i + k) + " ");
++count;
} else {
++count1;
System.out.print((i + k - 2 * count1) + " ");
}
++k;
}
count1 = count = k = 0;
System.out.println();
}
}
}
Print Half Pyramid Pattern
Kotlin (*)
fun main(args: Array<String>) {
val rows = 5
var k = 0
for (i in 1..rows) {
for (space in 1..rows - i) {
print(" ")
}
while (k != 2 * i - 1) {
print("* ")
++k
}
println()
k = 0
}
}
Print Pyramid Pattern numbers fun main(args: Array<String>) {
val rows = 5
for (i in 1..rows) {
for (j in 1..i) {
print("$j ")
}
println()
}
}
Print Pyramid Pattern Alphabetsfun main(args: Array<String>) {
val last = 'E'
var alphabet = 'A'
for (i in 1..last - 'A' + 1) {
for (j in 1..i) {
print("$alphabet ")
}
++alphabet
println()
}
}
Print Full Pyramid Pattern Kotlin * fun main(args: Array<String>) {
val rows = 5
var k = 0
for (i in 1..rows) {
for (space in 1..rows - i) {
print(" ")
}
while (k != 2 * i - 1) {
print("* ")
++k
}
println()
k = 0
}
}Print Full Pyramid Pattern Kotlin Numbersfun main(args: Array<String>) {
val rows = 5
var k = 0
var count = 0
var count1 = 0
for (i in 1..rows) {
for (space in 1..rows - i) {
print(" ")
++count
}
while (k != 2 * i - 1) {
if (count <= rows - 1) {
print((i + k).toString() + " ")
++count
} else {
++count1
print((i + k - 2 * count1).toString() + " ")
}
++k
}
k = 0
count = k
count1 = count
println()
}
}
Convert String Array to ArrayList
fun main() {
val arr = arrayOf("A", "B", "C", "D")
val list: List<String> = arr.toList()
println(list) // [A, B, C, D]
}
Fibonacci Series Program
Java
class GFG {
// Function to print N Fibonacci Number
static void Fibonacci(int N)
{
int num1 = 0, num2 = 1;
int counter = 0;
// Iterate till counter is N
while (counter < N) {
// Print the number
System.out.print(num1 + " ");
// Swap
int num3 = num2 + num1;
num1 = num2;
num2 = num3;
counter = counter + 1;
}
}
// Driver Code
public static void main(String args[])
{
// Given Number N
int N = 10;
// Function Call
Fibonacci(N);
}
}
Kotlin For Loop
fun main(args: Array<String>) {
val n = 10
var t1 = 0
var t2 = 1
print("First $n terms: ")
for (i in 1..n) {
print("$t1 + ")
val sum = t1 + t2
t1 = t2
t2 = sum
}
}
val n = 10
var t1 = 0
var t2 = 1
print("First $n terms: ")
for (i in 1..n) {
print("$t1 + ")
val sum = t1 + t2
t1 = t2
t2 = sum
}
}
Kotlin While Loop
fun main(args: Array<String>) {
var i = 1
val n = 10
var t1 = 0
var t2 = 1
print("First $n terms: ")
while (i <= n) {
print("$t1 + ")
val sum = t1 + t2
t1 = t2
t2 = sum
i++
}
}
var i = 1
val n = 10
var t1 = 0
var t2 = 1
print("First $n terms: ")
while (i <= n) {
print("$t1 + ")
val sum = t1 + t2
t1 = t2
t2 = sum
i++
}
}
Count of Smaller Numbers After Self
JAVA
// Java program for the above approach
public class CountSmaller
{
void constructLowerArray(int arr[], int countSmaller[], int n)
{
int i, j;
// initialize all the counts in countSmaller array as 0
for (i = 0; i < n; i++)
countSmaller[i] = 0;
for (i = 0; i < n; i++)
{
for (j = i + 1; j < n; j++)
{
if (arr[j] < arr[i])
countSmaller[i]++;
}
}
}
/* Utility function that prints out an array on a line */
void printArray(int arr[], int size)
{
int i;
for (i = 0; i < size; i++)
System.out.print(arr[i] + " ");
System.out.println("");
}
// Driver program to test above functions
public static void main(String[] args)
{
CountSmaller small = new CountSmaller();
int arr[] = {12, 10, 5, 4, 2, 20, 6, 1, 0, 2};
int n = arr.length;
int low[] = new int[n];
small.constructLowerArray(arr, low, n);
small.printArray(low, n);
}
}
// Java program for the above approach
public class CountSmaller
{
void constructLowerArray(int arr[], int countSmaller[], int n)
{
int i, j;
// initialize all the counts in countSmaller array as 0
for (i = 0; i < n; i++)
countSmaller[i] = 0;
for (i = 0; i < n; i++)
{
for (j = i + 1; j < n; j++)
{
if (arr[j] < arr[i])
countSmaller[i]++;
}
}
}
/* Utility function that prints out an array on a line */
void printArray(int arr[], int size)
{
int i;
for (i = 0; i < size; i++)
System.out.print(arr[i] + " ");
System.out.println("");
}
// Driver program to test above functions
public static void main(String[] args)
{
CountSmaller small = new CountSmaller();
int arr[] = {12, 10, 5, 4, 2, 20, 6, 1, 0, 2};
int n = arr.length;
int low[] = new int[n];
small.constructLowerArray(arr, low, n);
small.printArray(low, n);
}
}
You are given an integer array nums
and you have to return a new counts
array. The counts
array has the property where counts[i]
is the number of smaller elements to the right of nums[i]
Input: nums = [5,2,6,1] Output: [2,1,1,0] Explanation: To the right of 5 there are 2 smaller elements (2 and 1). To the right of 2 there is only 1 smaller element (1). To the right of 6 there is 1 smaller element (1). To the right of 1 there is 0 smaller element.
Comments
Post a Comment