Posts

Find First and Last Index of a Number

public class FirstAndLastIndedOfNumber { public static void main (String[] args) { int arr[] = { 1 , 2 , 2 , 3 , 4 , 5 , 3 , 2 , 7 , 22 , 22 } ; int first = - 1 ; int last = - 1 ; boolean flag = true; int searchNumber = 2 ; for ( int i= 0 ; i<arr. length ; i++){ if (searchNumber == arr[i]){ if (flag){ first = i ; flag = false; } last = i ; } } System. out .println(first + " \t " + last) ; } }

FibnociiSeries 2 Ways

import java.util.Arrays ; import java.util.StringJoiner ; public class FibnociiSeries { public static void main (String[] args) { int num = 10 ; int start = 0 ; int start2 = 1 ; StringJoiner sj = new StringJoiner( "," ) ; sj.add(String. valueOf (start)) ; sj.add(String. valueOf (start2)) ; for ( int i= 0 ; i<num ; i++){ int num3 = start + start2 ; sj.add(String. valueOf (num3)) ; start = start2 ; start2 = num3 ; } System. out .println(sj.toString()) ; usingArraysConcept () ; } public static void usingArraysConcept (){ int num = 10 ; int arr[] = new int [num+ 2 ] ; int num1 = 0 ; int num2 = 1 ; arr[ 0 ] = num1 ; arr[ 1 ] = num2 ; for ( int i= 2 ; i<arr. length ; i++){ int num3 = num1 + num2 ; arr[i] = num3 ; num1 = num2 ; nu

Permutation Of Given Word

public class Permutation { public static void main (String[] args) { String str = "ABCD" ; int len = str.length() ; Permutation permutation = new Permutation() ; permutation.permute(str , 0 , len- 1 ) ; } private void permute (String str , int left , int right) { if (left == right){ System. out .println(str) ; } else { for ( int i=left ; i<=right ; i++){ str = swap(str , left , i) ; permute(str , left+ 1 , right) ; } } } public String swap (String str , int i , int j) { char temp ; char [] ch = str.toCharArray() ; temp = ch[i] ; ch[i] = ch[j] ; ch[j] = temp ; return String. valueOf (ch) ; } }

Inverted Pyramid

public class InvertedPyramid { public static void main (String[] args) { int n = 3 ; for ( int i=n ; i>= 1 ; i--){ for ( int j= 1 ; j<= 2 *n- 1 ; j++){ if (j>=(n-i+ 1 ) && j<=(n+i- 1 )){ System. out .print( "*" ) ; } else { System. out .print( " " ) ; } } System. out .println() ; } } }

SpiralMatrix

public class SpiralMatrix { public static void main (String[] args) { int arr[][] = { { 1 , 2 , 3 , 4 } , { 5 , 6 , 7 , 8 } , { 9 , 10 , 11 , 12 } , { 13 , 14 , 15 , 16 } , { 17 , 18 , 19 , 20 } } ; for ( int x[]: arr){ for ( int y: x){ System. out .print(y+ " " ) ; } System. out .println() ; } int len = arr. length ; int top = 0 ; int down = len- 1 ; int left = 0 ; int right = arr[ 0 ]. length - 1 ; int direction = 0 ; while (top<=down && left<=right){ if (direction == 0 ){ for ( int i=left ; i<=right ; i++){ System. out .print(arr[top][i] + "," ) ; } top += 1 ; } else if (direction == 1 ){ for ( int i=top ; i<