diff --git a/ActivitySelection.java b/ActivitySelection.java new file mode 100644 index 0000000..ab37a37 --- /dev/null +++ b/ActivitySelection.java @@ -0,0 +1,51 @@ +import java.util.ArrayList; +import java.util.Collections; + +public class ActivitySelection { + + static class Activity { + int start; + int end; + + public Activity(int start, int end) { + this.start = start; + this.end = end; + } + + @Override + public String toString(){ + return "[" + this.start + ", " + this.end + "]"; + } + } + + public static void maxActivities(ArrayList activities){ + + //sort the activities in ascending order of meeting finish time + System.out.println("Given Activities: " + activities); + Collections.sort(activities, (o1, o2) -> o1.end - o2.end); + + ArrayList selectedActivities = new ArrayList<>(); + int currentEnd = -1; + for (int i = 0; i currentEnd){ + selectedActivities.add(currentActivity); + currentEnd = currentActivity.end; + } + } + + //print selected activities + System.out.println("Selected Activities: " + selectedActivities); + } + + public static void main(String[] args) { + ArrayList activities = new ArrayList<>(); + activities.add(new Activity(1, 3)); + activities.add(new Activity(2, 5)); + activities.add(new Activity(0, 7)); + activities.add(new Activity(6, 8)); + activities.add(new Activity(9, 11)); + activities.add(new Activity(10, 12)); + maxActivities(activities); + } +} \ No newline at end of file diff --git a/Armstrong_Funtion.java b/Armstrong_Funtion.java new file mode 100644 index 0000000..07148f6 --- /dev/null +++ b/Armstrong_Funtion.java @@ -0,0 +1,48 @@ +import java.io.*; +class Armstrong_Funtion +{ + public int Number(int n) + { + int r,a=0,ano=n,flag=0; + while(n>0) + { + r = n%10; + a = a + (r*r*r); + n = (n-r)/10; + } + if(ano==a) + { + flag = 1; + } + else + { + flag = 0; + } + return(flag); + } + public static void main(String args[]) throws IOException + { + System.out.println("Armstrong Number"); + System.out.println("****************"); + System.out.println(""); + InputStreamReader isr=new InputStreamReader(System.in); + BufferedReader br=new BufferedReader(isr); + int d,p; + System.out.print("Enter Number : "); + d = Integer.parseInt(br.readLine()); + System.out.println(""); + Armstrong_Funtion ob = new Armstrong_Funtion(); + p = ob.Number(d); + if(p==1) + { + System.out.println("Number is Armstrong"); + } + else + { + System.out.println("Number is Not Armstrong"); + } + } +} + + + \ No newline at end of file diff --git a/BinarySearch.java b/BinarySearch.java index eeffdf1..dbc1c11 100644 --- a/BinarySearch.java +++ b/BinarySearch.java @@ -45,7 +45,23 @@ public static void main(String[] args) { * @param number * @return index of given number in array or -1 if not found */ - public static int performBinarySearch(int[] input, int number) { +// public static int performBinarySearch(int[] input, int number) { +// int low = 0; +// int high = input.length - 1; + +// while (high >= low) { +// int middle = (low + high) / 2; +// if (input[middle] == number) { +// return middle; +// } else if (input[middle] < number) { +// low = middle + 1; +// } else if (input[middle] > number) { +// high = middle - 1; +// } +// } +// return -1; +// } + public static int performBinarySearch(int[] input, int number) { int low = 0; int high = input.length - 1; diff --git a/Binary_Search.java b/Binary_Search.java new file mode 100644 index 0000000..147c9e9 --- /dev/null +++ b/Binary_Search.java @@ -0,0 +1,35 @@ +import java.util.*; +class Main{ + public static void main(String args[]){ + int numArray[] = {5,10,15,20,25,30,35}; + System.out.println("The input array: " + Arrays.toString(numArray)); + + int key = 20; + System.out.println("\nKey to be searched=" + key); + + int first = 0; + + int last=numArray.length-1; + + int mid = (first + last)/2; + + while( first <= last ){ + + if ( numArray[mid] < key ){ + first = mid + 1; + }else if ( numArray[mid] == key ){ + + System.out.println("Element is found at index: " + mid); + break; + }else{ + + last = mid - 1; + } + mid = (first + last)/2; + } + + if ( first > last ){ + System.out.println("Element is not found!"); + } + } +} diff --git a/BubbleSort.java b/BubbleSort.java index ae1ceaa..81e3ef9 100644 --- a/BubbleSort.java +++ b/BubbleSort.java @@ -1,4 +1,5 @@ public class BubbleSortExample { + //worst case of this code is O(n2). static void bubbleSort(int[] arr) { int n = arr.length; int temp = 0; @@ -13,8 +14,32 @@ static void bubbleSort(int[] arr) { } } + - } + } + // An optimized version of Bubble Sort + //worst case of this code is O(n). + static void optimizedbubbleSort(int arr[], int n) + { + int i, j, temp; + boolean swapped; + for (i = 0; i < n - 1; i++) + { + swapped = false; + for (j = 0; j < n - i - 1; j++) + { + if (arr[j] > arr[j + 1]) + { + temp = arr[j]; + arr[j] = arr[j + 1]; + arr[j + 1] = temp; + swapped = true; + } + } + if (swapped == false) + break; + } + } public static void main(String[] args) { int arr[] ={3,60,35,2,45,320,5}; @@ -32,4 +57,4 @@ public static void main(String[] args) { } } -} \ No newline at end of file +} diff --git a/BubbleSortExample.java b/BubbleSortExample.java new file mode 100644 index 0000000..c716ce0 --- /dev/null +++ b/BubbleSortExample.java @@ -0,0 +1,35 @@ +public class BubbleSortExample { + static void bubbleSort(int[] arr) { + int n = arr.length; + int temp = 0; + for(int i=0; i < n; i++){ + for(int j=1; j < (n-i); j++){ + if(arr[j-1] > arr[j]){ + //swap elements + temp = arr[j-1]; + arr[j-1] = arr[j]; + arr[j] = temp; + } + + } + } + + } + public static void main(String[] args) { + int arr[] ={3,60,35,2,45,320,5}; + + System.out.println("Array Before Bubble Sort"); + for(int i=0; i < arr.length; i++){ + System.out.print(arr[i] + " "); + } + System.out.println(); + + bubbleSort(arr);//sorting array elements using bubble sort + + System.out.println("Array After Bubble Sort"); + for(int i=0; i < arr.length; i++){ + System.out.print(arr[i] + " "); + } + + } +} \ No newline at end of file diff --git a/Count the number of words in a string using HashMap.java b/Count the number of words in a string using HashMap.java new file mode 100644 index 0000000..8097cd7 --- /dev/null +++ b/Count the number of words in a string using HashMap.java @@ -0,0 +1,23 @@ +import java.util.HashMap; + +public class FinalCountWords { + + public static void main(String[] args) { + // TODO Auto-generated method stub + String str = "You are doing this Code"; + String[] split = str.split(" "); + + HashMap map = new HashMap(); + for (int i=0; i max) + max = array[i]; + } + int[] count = new int[max + 1]; + + // Initialize count array with all zeros + for (int i = 0; i < max; ++i) { + count[i] = 0; + } + + // Store the count of each element + for (int i = 0; i < size; i++) { + count[array[i]]++; + } + + // Store the cummulative count of each array + for (int i = 1; i <= max; i++) { + count[i] += count[i - 1]; + } + + // Find the index of each element of the original array in count array, and + // place the elements in output array + for (int i = size - 1; i >= 0; i--) { + output[count[array[i]] - 1] = array[i]; + count[array[i]]--; + } + + // Copy the sorted elements into original array + for (int i = 0; i < size; i++) { + array[i] = output[i]; + } + } + + // Driver code for the above code + public static void main(String args[]) { + int[] data = { 4, 2, 2, 8, 3, 3, 1 }; + int size = data.length; + CountingSort cs = new CountingSort(); + cs.countSort(data, size); + System.out.println("Sorted Array in Ascending Order: "); + System.out.println(Arrays.toString(data)); + } +} diff --git a/DNFSort.java b/DNFSort.java new file mode 100644 index 0000000..daaacc4 --- /dev/null +++ b/DNFSort.java @@ -0,0 +1,49 @@ +public class DNFSort { + + // Sort the input array, the array is assumed to + // have values in {0, 1, 2} + static void sort012(int a[], int arr_size) { + int low = 0; + int high = arr_size - 1; + int mid = 0, temp = 0; + while (mid <= high) { + switch (a[mid]) { + case 0: { + temp = a[low]; + a[low] = a[mid]; + a[mid] = temp; + low++; + mid++; + break; + } + case 1: + mid++; + break; + case 2: { + temp = a[mid]; + a[mid] = a[high]; + a[high] = temp; + high--; + break; + } + } + } + } + + /* Utility function to print array arr[] */ + static void printArray(int arr[], int arr_size) { + for (int i = 0; i < arr_size; i++) { + System.out.print(arr[i] + " "); + } + System.out.println(""); + } + + /*Driver function to check for above functions*/ + public static void main(String[] args) { + int arr[] = {0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1}; + int arr_size = arr.length; + sort012(arr, arr_size); + System.out.println("Array after seggregation "); + printArray(arr, arr_size); + } +} diff --git a/Date_and_time.java b/Date_and_time.java new file mode 100644 index 0000000..e6ce5e0 --- /dev/null +++ b/Date_and_time.java @@ -0,0 +1,32 @@ +// Java program to convert 24 hour +// time format to 12 hour format + +// Importing specific date class libraries +import java.util.Date; +import java.text.SimpleDateFormat; + +public class GFG { + +// Main driver method + public static void main(String[] args) + { + // Getting the current current time + Date date = new Date(); + + + System.out.println("Current Time is : " + date); + + // set format in 12 hours + SimpleDateFormat formatTime = new SimpleDateFormat("hh.mm aa"); + // hh = hours in 12hr format + // mm = minutes + // aa = am/pm + + String time = formatTime.format( + date); // changing the format of 'date' + + // display time as per format + System.out.println( + "Current Time in AM/PM Format is : " + time); + } +} diff --git a/Dequeue- basics/Double-End Queue.pdf b/Dequeue- basics/Double-End Queue.pdf new file mode 100644 index 0000000..6010260 Binary files /dev/null and b/Dequeue- basics/Double-End Queue.pdf differ diff --git a/Determinant_of_Matrix.java b/Determinant_of_Matrix.java new file mode 100644 index 0000000..bf856b9 --- /dev/null +++ b/Determinant_of_Matrix.java @@ -0,0 +1,94 @@ +// Java program to find Determinant of a matrix +class GFG { + + // Dimension of input square matrix + static final int N = 4; + + // Function to get determinant of matrix + static int determinantOfMatrix(int mat[][], int n) + { + int num1, num2, det = 1, index, + total = 1; // Initialize result + + // temporary array for storing row + int[] temp = new int[n + 1]; + + // loop for traversing the diagonal elements + for (int i = 0; i < n; i++) { + index = i; // initialize the index + + // finding the index which has non zero value + while (mat[index][i] == 0 && index < n) { + index++; + } + if (index == n) // if there is non zero element + { + // the determinant of matrix as zero + continue; + } + if (index != i) { + // loop for swaping the diagonal element row + // and index row + for (int j = 0; j < n; j++) { + swap(mat, index, j, i, j); + } + // determinant sign changes when we shift + // rows go through determinant properties + det = (int)(det * Math.pow(-1, index - i)); + } + + // storing the values of diagonal row elements + for (int j = 0; j < n; j++) { + temp[j] = mat[i][j]; + } + + // traversing every row below the diagonal + // element + for (int j = i + 1; j < n; j++) { + num1 = temp[i]; // value of diagonal element + num2 = mat[j] + [i]; // value of next row element + + // traversing every column of row + // and multiplying to every row + for (int k = 0; k < n; k++) { + // multiplying to make the diagonal + // element and next row element equal + mat[j][k] = (num1 * mat[j][k]) + - (num2 * temp[k]); + } + total = total * num1; // Det(kA)=kDet(A); + } + } + + // multiplying the diagonal elements to get + // determinant + for (int i = 0; i < n; i++) { + det = det * mat[i][i]; + } + return (det / total); // Det(kA)/k=Det(A); + } + + static int[][] swap(int[][] arr, int i1, int j1, int i2, + int j2) + { + int temp = arr[i1][j1]; + arr[i1][j1] = arr[i2][j2]; + arr[i2][j2] = temp; + return arr; + } + + // Driver code + public static void main(String[] args) + { + int mat[][] = { { 1, 0, 2, -1 }, + { 3, 0, 0, 5 }, + { 2, 1, 4, -3 }, + { 1, 0, 5, 0 } }; + + // Function call + System.out.printf( + "Determinant of the matrix is : %d", + determinantOfMatrix(mat, N)); + } +} diff --git a/DijkstraAlgorithm.java b/DijkstraAlgorithm.java new file mode 100644 index 0000000..757d028 --- /dev/null +++ b/DijkstraAlgorithm.java @@ -0,0 +1,57 @@ + +import java.util.Scanner; +public class DijkstraAlgorithm { + private static void dijkstra(int[][] adjacencyMatrix) { + int v = adjacencyMatrix.length; + boolean visited[] = new boolean[v]; + int distance[] = new int[v]; + distance[0] = 0; + for (int i = 1; i < v; i++) { + distance[i] = Integer.MAX_VALUE; + } + for (int i = 0; i < v - 1; i++) { + + int minVertex = findMinVertex(distance, visited); + visited[minVertex] = true; + + for (int j = 0; j < v; j++) { + if (adjacencyMatrix[minVertex][j] != 0 && !visited[j] && + distance[minVertex] != Integer.MAX_VALUE) { + int newDist = distance[minVertex] + + adjacencyMatrix[minVertex][j]; + if (newDist < distance[j]) { + distance[j] = newDist; + } + } + } + } + + for (int i = 0; i < v; i++) { + System.out.println(i + " " + distance[i]); + } + } + private static int findMinVertex(int[] distance, boolean visited[]) { + int minVertex = -1; + for (int i = 0; i < distance.length; i++) { + if (!visited[i] && (minVertex == -1 || distance[i] < + distance[minVertex])) { + minVertex = i; + } + } + return minVertex; + } + public static void main(String[] args) { + Scanner s = new Scanner(System.in); + int v = s.nextInt(); + int e = s.nextInt(); + int adjacencyMatrix[][] = new int[v][v]; + for (int i = 0; i < e; i++) { + int v1 = s.nextInt(); + int v2 = s.nextInt(); + int weight = s.nextInt(); + adjacencyMatrix[v1][v2] = weight; + adjacencyMatrix[v2][v1] = weight; + } + dijkstra(adjacencyMatrix); + } +} \ No newline at end of file diff --git a/Disarium.java b/Disarium.java new file mode 100644 index 0000000..20966b3 --- /dev/null +++ b/Disarium.java @@ -0,0 +1,21 @@ +import java.util.*; +public class Disarium{ + boolean isDisarium(int n){ + byte c=0; + int b=0; + for(int i=n;i>0;c+=1,i/=10); + for(int i=n;i>0;b=b+(int)Math.pow(i%10,c--),i/=10); + if(n==b) + return true; + return false; + } + + public static void main(String args[]) + { + System.out.println("Enter a number:"); + if(new Disarium().isDisarium(new Scanner(System.in).nextInt())) + System.out.println("Disarium number"); + else + System.out.println("Not an Disarium number."); + } +} \ No newline at end of file diff --git a/Electricitybill.java b/Electricitybill.java new file mode 100644 index 0000000..8792ab8 --- /dev/null +++ b/Electricitybill.java @@ -0,0 +1,26 @@ +class ElectricityBillExample1 +{ + // main() method start + public static void main(String args[]) + { + // declare and initialize variable units + int units = 380; + // variable to calculate electricity bill to pay + double billToPay = 0; + // check whether units are less than 100 + if(units < 100) + { + billToPay = units * 1.20; + } + // check whether the units are less than 300 + else if(units < 300){ + billToPay = 100 * 1.20 + (units - 100) * 2; + } + // check whether the units are greater than 300 + else if(units > 300) + { + billToPay = 100 * 1.20 + 200 * 2 + (units - 300) * 3; + } + System.out.println("The electricity bill for " +units+ " is : " + billToPay); + } +} diff --git a/FactorialProgram.java b/FactorialProgram.java new file mode 100644 index 0000000..de1ecbc --- /dev/null +++ b/FactorialProgram.java @@ -0,0 +1,31 @@ +import java.util.Scanner; + +class Abc +{ + public int f=1,i=0; + + public void fact(int n) + { + for(i=1; i<=n; i++) + { + f = f*i; + } + + System.out.println(n + " Factorial is : " + f); + } +} + +class factorial +{ + public static void main(String arr[]) + { + Scanner m = new Scanner(System.in); + + System.out.print("Enter Elemnt TO find Factorial : "); + int n = m.nextInt(); + + Abc a1 = new Abc(); + a1.fact(n); + + } +} diff --git a/FibonacciSeries.java b/FibonacciSeries.java new file mode 100644 index 0000000..4e6629e --- /dev/null +++ b/FibonacciSeries.java @@ -0,0 +1,15 @@ +class Fibonacci{ +public static void main(String args[]) +{ + int n1=0,n2=1,n3,i,count=10; + System.out.print(n1+" "+n2);//printing 0 and 1 + + for(i=2;icc) + { + System.out.println("This number is greater than computer's.\nTry again :"); + } + } + } +} \ No newline at end of file diff --git a/HeapSort.java b/HeapSort.java index fb34021..3330fdf 100644 --- a/HeapSort.java +++ b/HeapSort.java @@ -1,72 +1,59 @@ -public class HeapSort { - public void sort(int arr[]) - { - int N = arr.length; - - // Build heap (rearrange array) - for (int i = N / 2 - 1; i >= 0; i--) - heapify(arr, N, i); - - // One by one extract an element from heap - for (int i = N - 1; i > 0; i--) { - // Move current root to end - int temp = arr[0]; - arr[0] = arr[i]; - arr[i] = temp; - - // call max heapify on the reduced heap - heapify(arr, i, 0); - } - } - - // To heapify a subtree rooted with node i which is - // an index in arr[]. n is size of heap - void heapify(int arr[], int N, int i) - { - int largest = i; // Initialize largest as root - int l = 2 * i + 1; // left = 2*i + 1 - int r = 2 * i + 2; // right = 2*i + 2 - - // If left child is larger than root - if (l < N && arr[l] > arr[largest]) - largest = l; - - // If right child is larger than largest so far - if (r < N && arr[r] > arr[largest]) - largest = r; - - // If largest is not root - if (largest != i) { - int swap = arr[i]; - arr[i] = arr[largest]; - arr[largest] = swap; - - // Recursively heapify the affected sub-tree - heapify(arr, N, largest); - } - } - - /* A utility function to print array of size n */ - static void printArray(int arr[]) - { - int N = arr.length; - - for (int i = 0; i < N; ++i) - System.out.print(arr[i] + " "); - System.out.println(); - } - - // Driver's code - public static void main(String args[]) - { - int arr[] = { 12, 11, 13, 5, 6, 7 }; - int N = arr.length; - - // Function call - HeapSort ob = new HeapSort(); - ob.sort(arr); - - System.out.println("Sorted array is"); - printArray(arr); - } -} \ No newline at end of file +class HeapSort +{ +/* function to heapify a subtree. Here 'i' is the +index of root node in array a[], and 'n' is the size of heap. */ +static void heapify(int a[], int n, int i) +{ + int largest = i; // Initialize largest as root + int left = 2 * i + 1; // left child + int right = 2 * i + 2; // right child + // If left child is larger than root + if (left < n && a[left] > a[largest]) + largest = left; + // If right child is larger than root + if (right < n && a[right] > a[largest]) + largest = right; + // If root is not largest + if (largest != i) { + // swap a[i] with a[largest] + int temp = a[i]; + a[i] = a[largest]; + a[largest] = temp; + + heapify(a, n, largest); + } +} +/*Function to implement the heap sort*/ +static void heapSort(int a[], int n) +{ + for (int i = n / 2 - 1; i >= 0; i--) + heapify(a, n, i); + + // One by one extract an element from heap + for (int i = n - 1; i >= 0; i--) { + /* Move current root element to end*/ + // swap a[0] with a[i] + int temp = a[0]; + a[0] = a[i]; + a[i] = temp; + + heapify(a, i, 0); + } +} +/* function to print the array elements */ +static void printArr(int a[], int n) +{ + for (int i = 0; i < n; ++i) + System.out.print(a[i] + " "); +} +public static void main(String args[]) +{ + int a[] = {45, 7, 20, 40, 25, 23, -2}; + int n = a.length; + System.out.print("Before sorting array elements are - \n"); + printArr(a, n); + heapSort(a, n); + System.out.print("\nAfter sorting array elements are - \n"); + printArr(a, n); +} +} \ No newline at end of file diff --git a/Inheritance.java b/Inheritance.java new file mode 100644 index 0000000..21b5e51 --- /dev/null +++ b/Inheritance.java @@ -0,0 +1,103 @@ +import java.util.Scanner; + +class Player +{ + static int age,total; + static String name; + static String type; + static String role; +} + +class CricketPlayer extends Player +{ + public int c = 0; + + void getData() + { + Scanner meet = new Scanner(System.in); + + System.out.print("Enter Player Name : "); + name = meet.nextLine(); + + System.out.print("Enter Player Age : "); + age = meet.nextInt(); + + System.out.print("Enter Player Type (Batsman or Bowler) : "); + type = meet.next(); + + if(type == "Bowler" || type == "bowler") + { + c++; + } + } + + void Bowler_Info() + { + if(c>0) + { + Scanner meet = new Scanner(System.in); + + System.out.print("Enter Bowler Player Type (Fast / Spin / Medium) : "); + role = meet.next(); + } + + } +} + +class batsman extends CricketPlayer +{ + void getCar() + { + Scanner meet = new Scanner(System.in); + + System.out.print("Enter Player Carrer Total Match : "); + total = meet.nextInt(); + + } + + void print1() + { + System.out.println("Player Type : " + type); + System.out.println("Carrer Total Match : " + total); + } + +} + +class Bowler extends CricketPlayer +{ + + void print() + { + System.out.println("Player Name : " + name); + System.out.println("Player Age : " + age); + + if(c == 1) + { + System.out.println("Player Boling Type : " + role); + } + + } + +} + +class Inheri { + + public static void main(String arr[]) + { + Bowler b1 = new Bowler(); + batsman c1 = new batsman(); + + b1.getData(); + c1.getCar(); + b1.Bowler_Info(); + + System.out.print("\n------------------------------------------------\n"); + + b1.print(); + c1.print1(); + + System.out.println("------------------------------------------------"); + + } + +} diff --git a/Java program to find maximum product of.java b/Java program to find maximum product of.java new file mode 100644 index 0000000..b61b9f7 --- /dev/null +++ b/Java program to find maximum product of.java @@ -0,0 +1,78 @@ +// Java program to find maximum product of +// a subset. +class Array { + + static int minProductSubset(int a[], int n) + { + if (n == 1) + return a[0]; + + // Find count of negative numbers, + // count of zeros, maximum valued + // negative number, minimum valued + // positive number and product of + // non-zero numbers + int negmax = Integer.MIN_VALUE; + int posmin = Integer.MAX_VALUE; + int count_neg = 0, count_zero = 0; + int product = 1; + + for (int i = 0; i < n; i++) { + + // if number is zero,count it + // but dont multiply + if (a[i] == 0) { + count_zero++; + continue; + } + + // count the negative numbers + // and find the max negative number + if (a[i] < 0) { + count_neg++; + negmax = Math.max(negmax, a[i]); + } + + // find the minimum positive number + if (a[i] > 0 && a[i] < posmin) + posmin = a[i]; + + product *= a[i]; + } + + // if there are all zeroes + // or zero is present but no + // negative number is present + if (count_zero == n + || (count_neg == 0 && count_zero > 0)) + return 0; + + // If there are all positive + if (count_neg == 0) + return posmin; + + // If there are even number except + // zero of negative numbers + if (count_neg % 2 == 0 && count_neg != 0) { + + // Otherwise result is product of + // all non-zeros divided by maximum + // valued negative. + product = product / negmax; + } + + return product; + } + + // main function + public static void main(String[] args) + { + + int a[] = { -1, -1, -2, 4, 3 }; + int n = 5; + + System.out.println(minProductSubset(a, n)); + } +} + +// This code is contributed by Arnab Kundu. diff --git a/K closest elements b/K closest elements new file mode 100644 index 0000000..2d0ee55 --- /dev/null +++ b/K closest elements @@ -0,0 +1,25 @@ +class Solution { + public List findClosestElements(int[] arr, int k, int x) { + Map> map = new TreeMap<>(); + List result = new ArrayList<>(); + + for(int i=0; i vals = map.getOrDefault(diff,new ArrayList<>()); + vals.add(arr[i]); + map.put(diff,vals); + } + + + for(Map.Entry> entry : map.entrySet()){ + for(Integer num : entry.getValue()){ + if(k>0){ + result.add(num); + k--; + } + } + } + Collections.sort(result); + return result; + } +} diff --git a/Kadane.java b/Kadane.java new file mode 100644 index 0000000..261aae7 --- /dev/null +++ b/Kadane.java @@ -0,0 +1,24 @@ + +public class Kadane { + public static void main(String[] args) { + System.out.println(kadaneAlgo(new int[]{1,2,3,4,-10, 11, -1})); + } + + public static int kadaneAlgo(int[] arr){ + int max = arr[0], sum = 0; + int len = 0; + for (int i = 0; i < arr.length; i++) { + + sum+=arr[i]; + len++; + if (sum > max) { + max = sum; + } + if (sum <= 0) { + sum = 0; + len = 0; + } + } + return max; + } +} diff --git a/Kadane_Algorithm.java b/Kadane_Algorithm.java new file mode 100644 index 0000000..fc3b9e3 --- /dev/null +++ b/Kadane_Algorithm.java @@ -0,0 +1,30 @@ +// Java program to print largest contiguous array sum +import java.io.*; +import java.util.*; + +class Kadane_Algorithm { + // Driver Code + public static void main(String[] args) + { + int[] a = { -2, -3, 4, -1, -2, 1, 5, -3 }; + System.out.println("Maximum contiguous sum is " + + maxSubArraySum(a)); + } + + // Function Call + static int maxSubArraySum(int a[]) + { + int size = a.length; + int max_so_far = Integer.MIN_VALUE, max_ending_here + = 0; + + for (int i = 0; i < size; i++) { + max_ending_here = max_ending_here + a[i]; + if (max_so_far < max_ending_here) + max_so_far = max_ending_here; + if (max_ending_here < 0) + max_ending_here = 0; + } + return max_so_far; + } +} diff --git a/Linear_Search.java b/Linear_Search.java new file mode 100644 index 0000000..9459795 --- /dev/null +++ b/Linear_Search.java @@ -0,0 +1,23 @@ +public class LinearSearch { + + public static final int unorderedLinearSearch(int value, int[] array) { + for (int i = 0; i < array.length; i++) { + int iValue = array[i]; + if (value == iValue) + return i; + } + return Integer.MAX_VALUE; + } + + public static void main(String[] args) { + int[] integers = {1,2,3,4,5,6,7,8,8,8,9,9,9,0}; + //the element that should be found + int shouldBeFound = 9; + + int atIndex = LinearSearch.unorderedLinearSearch(shouldBeFound, integers); + + System.out.println(String.format("Should be found: %d. Found %d at index %d. An array length %d" + , shouldBeFound, integers[atIndex], atIndex, integers.length)); + + } +} diff --git a/LinkedListInsertion.java b/LinkedListInsertion.java new file mode 100644 index 0000000..63d9b17 --- /dev/null +++ b/LinkedListInsertion.java @@ -0,0 +1,43 @@ +package com.example.demo; + +import java.util.*; + +class example{ + public static void main(String[] args){ + + // create linkedlist + LinkedList ll = new LinkedList<>(); + Scanner sc = new Scanner(System.in); + + // Add elements to LinkedList + System.out.println("Options:"); + System.out.println("1. Enter element.\n2. Exit."); + System.out.println("Enter choice: "); + int ch = 1; + ch = Integer.parseInt(sc.nextLine()); + do{ + switch(ch){ + case 1: + //insert the element. + System.out.println("Enter the element: "); + String element = sc.nextLine(); + ll.add(element); + break; + + case 2: + //exit the loop, + ch=2; + System.out.println("Ending insertion into linked list..."); + break; + + default: + //invalid choice: + System.out.println("Enter a valid input!"); + break; + } + System.out.println("Enter choice: "); + ch = Integer.parseInt(sc.nextLine()); + }while(ch!=2); + System.out.println("LinkedList: " + ll); + } +} \ No newline at end of file diff --git a/MazeRecursion.java b/MazeRecursion.java new file mode 100644 index 0000000..c52a4e6 --- /dev/null +++ b/MazeRecursion.java @@ -0,0 +1,158 @@ +package com.thealgorithms.backtracking; + +public class MazeRecursion { + + public static void mazeRecursion() { + // First create a 2 dimensions array to mimic a maze map + int[][] map = new int[8][7]; + int[][] map2 = new int[8][7]; + + // We use 1 to indicate wall + // Set the ceiling and floor to 1 + for (int i = 0; i < 7; i++) { + map[0][i] = 1; + map[7][i] = 1; + } + + // Then we set the left and right wall to 1 + for (int i = 0; i < 8; i++) { + map[i][0] = 1; + map[i][6] = 1; + } + + // Now we have created a maze with its wall initialized + + // Here we set the obstacle + map[3][1] = 1; + map[3][2] = 1; + + // Print the current map + System.out.println("The condition of the map: "); + for (int i = 0; i < 8; i++) { + for (int j = 0; j < 7; j++) { + System.out.print(map[i][j] + " "); + } + System.out.println(); + } + + // clone another map for setWay2 method + for (int i = 0; i < map.length; i++) { + for (int j = 0; j < map[i].length; j++) { + map2[i][j] = map[i][j]; + } + } + + // By using recursive backtracking to let your ball(target) find its way in the + // maze + // The first parameter is the map + // Second parameter is x coordinate of your target + // Thrid parameter is the y coordinate of your target + setWay(map, 1, 1); + setWay2(map2, 1, 1); + + // Print out the new map1, with the ball footprint + System.out.println("After the ball goes through the map1,show the current map1 condition"); + for (int i = 0; i < 8; i++) { + for (int j = 0; j < 7; j++) { + System.out.print(map[i][j] + " "); + } + System.out.println(); + } + + // Print out the new map2, with the ball footprint + System.out.println("After the ball goes through the map2,show the current map2 condition"); + for (int i = 0; i < 8; i++) { + for (int j = 0; j < 7; j++) { + System.out.print(map2[i][j] + " "); + } + System.out.println(); + } + } + + + + // Using recursive path finding to help the ball find its way in the maze + // Description: + // 1. map (means the maze) + // 2. i, j (means the initial coordinate of the ball in the maze) + // 3. if the ball can reach the end of maze, that is position of map[6][5], + // means the we have found a path for the ball + // 4. Additional Information: 0 in the map[i][j] means the ball has not gone + // through this position, 1 means the wall, 2 means the path is feasible, 3 + // means the ball has gone through the path but this path is dead end + // 5. We will need strategy for the ball to pass through the maze for example: + // Down -> Right -> Up -> Left, if the path doesn't work, then backtrack + /** + * + * @Description + * @author OngLipWei + * @date Jun 23, 202111:36:14 AM + * @param map The maze + * @param i x coordinate of your ball(target) + * @param j y coordinate of your ball(target) + * @return If we did find a path for the ball,return true,else false + */ + public static boolean setWay(int[][] map, int i, int j) { + if (map[6][5] == 2) {// means the ball find its path, ending condition + return true; + } + if (map[i][j] == 0) { // if the ball haven't gone through this point + // then the ball follows the move strategy : down -> right -> up -> left + map[i][j] = 2; // we assume that this path is feasible first, set the current point to 2 first。 + if (setWay(map, i + 1, j)) { // go down + return true; + } else if (setWay(map, i, j + 1)) { // go right + return true; + } else if (setWay(map, i - 1, j)) { // go up + return true; + } else if (setWay(map, i, j - 1)) { // go left + return true; + } else { + // means that the current point is the dead end, the ball cannot proceed, set + // the current point to 3 and return false, the backtraking will start, it will + // go to the previous step and check for feasible path again + map[i][j] = 3; + return false; + } + + } else { // if the map[i][j] != 0 , it will probably be 1,2,3, return false because the + // ball cannot hit the wall, cannot go to the path that has gone though before, + // and cannot head to deadend. + return false; + } + + } + + // Here is another move strategy for the ball: up->right->down->left + public static boolean setWay2(int[][] map, int i, int j) { + if (map[6][5] == 2) {// means the ball find its path, ending condition + return true; + } + if (map[i][j] == 0) { // if the ball haven't gone through this point + // then the ball follows the move strategy : up->right->down->left + map[i][j] = 2; // we assume that this path is feasible first, set the current point to 2 first。 + if (setWay2(map, i - 1, j)) { // go up + return true; + } else if (setWay2(map, i, j + 1)) { // go right + return true; + } else if (setWay2(map, i + 1, j)) { // go down + return true; + } else if (setWay2(map, i, j - 1)) { // go left + return true; + } else { + // means that the current point is the dead end, the ball cannot proceed, set + // the current point to 3 and return false, the backtraking will start, it will + // go to the previous step and check for feasible path again + map[i][j] = 3; + return false; + } + + } else { // if the map[i][j] != 0 , it will probably be 1,2,3, return false because the + // ball cannot hit the wall, cannot go to the path that has gone though before, + // and cannot head to deadend. + return false; + } + + } + +} diff --git a/Method_overloading.java b/Method_overloading.java new file mode 100644 index 0000000..acd8aaa --- /dev/null +++ b/Method_overloading.java @@ -0,0 +1,80 @@ + // Java Program for Method overloading +// By using Different Types of Arguments + +// Class 1 +// Helper class +class Helper { + + // Method with 2 integer parameters + static int Multiply(int a, int b) + { + + // Returns product of integer numbers + return a * b; + } + + // Method 2 + // With same name but with 2 double parameters + static double Multiply(double a, double b) + { + + // Returns product of double numbers + return a * b; + } +} + +// Class 2 +// Main class +class basic { + + // Main driver method + public static void main(String[] args) + { + + // Calling method by passing + // input as in arguments + System.out.println(Helper.Multiply(2, 4)); + System.out.println(Helper.Multiply(5.5, 6.3)); + } +} + +// Java program for Method Overloading +// by Using Different Numbers of Arguments + +// Class 1 +// Helper class +class abc { + + // Method 1 + // Multiplication of 2 numbers + static int Multiply(int a, int b) + { + + // Return product + return a * b; + } + + // Method 2 + // // Multiplication of 3 numbers + static int Multiply(int a, int b, int c) + { + + // Return product + return a * b * c; + } +} + +// Class 2 +// Main class +class simple { + + // Main driver method + public static void main(String[] args) + { + + // Calling method by passing + // input as in arguments + System.out.println(abc.Multiply(2, 4)); + System.out.println(abc.Multiply(2, 7, 3)); + } +} diff --git a/NQueens.java b/NQueens.java new file mode 100644 index 0000000..fb0138d --- /dev/null +++ b/NQueens.java @@ -0,0 +1,111 @@ +package com.thealgorithms.backtracking; + +import java.util.ArrayList; +import java.util.List; + +/** + * Problem statement: Given a N x N chess board. Return all arrangements in + * which N queens can be placed on the board such no two queens attack each + * other. Ex. N = 6 Solution= There are 4 possible ways Arrangement: 1 ".Q....", + * "...Q..", ".....Q", "Q.....", "..Q...", "....Q." + *

+ * Arrangement: 2 "..Q...", ".....Q", ".Q....", "....Q.", "Q.....", "...Q.." + *

+ * Arrangement: 3 "...Q..", "Q.....", "....Q.", ".Q....", ".....Q", "..Q..." + *

+ * Arrangement: 4 "....Q.", "..Q...", "Q.....", ".....Q", "...Q..", ".Q...." + * + * Solution: Brute Force approach: + * + * Generate all possible arrangement to place N queens on N*N board. Check each + * board if queens are placed safely. If it is safe, include arrangement in + * solution set. Otherwise ignore it + * + * Optimized solution: This can be solved using backtracking in below steps + * + * Start with first column and place queen on first row Try placing queen in a + * row on second column If placing second queen in second column attacks any of + * the previous queens, change the row in second column otherwise move to next + * column and try to place next queen In case if there is no rows where a queen + * can be placed such that it doesn't attack previous queens, then go back to + * previous column and change row of previous queen. Keep doing this until last + * queen is not placed safely. If there is no such way then return an empty list + * as solution + */ +public class NQueens { + + public static void main(String[] args) { + placeQueens(1); + placeQueens(2); + placeQueens(3); + placeQueens(4); + placeQueens(5); + placeQueens(6); + } + + public static void placeQueens(final int queens) { + List> arrangements = new ArrayList>(); + getSolution(queens, arrangements, new int[queens], 0); + if (arrangements.isEmpty()) { + System.out.println("There is no way to place " + queens + " queens on board of size " + queens + "x" + queens); + } else { + System.out.println("Arrangement for placing " + queens + " queens"); + } + arrangements.forEach(arrangement -> { + arrangement.forEach(row -> System.out.println(row)); + System.out.println(); + }); + } + + /** + * This is backtracking function which tries to place queen recursively + * + * @param boardSize: size of chess board + * @param solutions: this holds all possible arrangements + * @param columns: columns[i] = rowId where queen is placed in ith column. + * @param columnIndex: This is the column in which queen is being placed + */ + private static void getSolution(int boardSize, List> solutions, int[] columns, int columnIndex) { + if (columnIndex == boardSize) { + // this means that all queens have been placed + List sol = new ArrayList(); + for (int i = 0; i < boardSize; i++) { + StringBuilder sb = new StringBuilder(); + for (int j = 0; j < boardSize; j++) { + sb.append(j == columns[i] ? "Q" : "."); + } + sol.add(sb.toString()); + } + solutions.add(sol); + return; + } + + // This loop tries to place queen in a row one by one + for (int rowIndex = 0; rowIndex < boardSize; rowIndex++) { + columns[columnIndex] = rowIndex; + if (isPlacedCorrectly(columns, rowIndex, columnIndex)) { + // If queen is placed successfully at rowIndex in column=columnIndex then try placing queen in next column + getSolution(boardSize, solutions, columns, columnIndex + 1); + } + } + } + + /** + * This function checks if queen can be placed at row = rowIndex in column = + * columnIndex safely + * + * @param columns: columns[i] = rowId where queen is placed in ith column. + * @param rowIndex: row in which queen has to be placed + * @param columnIndex: column in which queen is being placed + * @return true: if queen can be placed safely false: otherwise + */ + private static boolean isPlacedCorrectly(int[] columns, int rowIndex, int columnIndex) { + for (int i = 0; i < columnIndex; i++) { + int diff = Math.abs(columns[i] - rowIndex); + if (diff == 0 || columnIndex - i == diff) { + return false; + } + } + return true; + } +} diff --git a/Number is Palindrome or Not.java b/Number is Palindrome or Not.java new file mode 100644 index 0000000..395b5fa --- /dev/null +++ b/Number is Palindrome or Not.java @@ -0,0 +1,26 @@ +import java.util.Scanner; + class expalindrome +{ +public static void main(String args[]) +{ +int x,number, y=0,temp=0; +Scanner s=new Scanner(System.in); +System.out.println("Enter any number: "); +number=s.nextInt(); +x=number; +while(number>0) +{ +x=number%10; +number=number/10; +temp=temp*10+x; +} +if(temp==y) +{ +System.out.println("Number is Palindrome"); +} +else +{ +System.out.println("not Palindrome"); +} +} +} diff --git a/Number_guessing_game.java b/Number_guessing_game.java new file mode 100644 index 0000000..fca0218 --- /dev/null +++ b/Number_guessing_game.java @@ -0,0 +1,66 @@ +import java.util.Scanner; + +public class GFG { + + public static void + guessingNumberGame() + { + Scanner sc = new Scanner(System.in); + + int number = 1 + (int)(100 + * Math.random()); + + int K = 5; + + int i, guess; + + System.out.println( + "A number is chosen" + + " between 1 to 100." + + "Guess the number" + + " within 5 trials."); + + for (i = 0; i < K; i++) { + + System.out.println( + "Guess the number:"); + + guess = sc.nextInt(); + + if (number == guess) { + System.out.println( + "Congratulations!" + + " You guessed the number."); + break; + } + else if (number > guess + && i != K - 1) { + System.out.println( + "The number is " + + "greater than " + guess); + } + else if (number < guess + && i != K - 1) { + System.out.println( + "The number is" + + " less than " + guess); + } + } + + if (i == K) { + System.out.println( + "You have exhausted" + + " K trials."); + + System.out.println( + "The number was " + number); + } + } + + public static void + main(String arg[]) + { + + guessingNumberGame(); + } +} diff --git a/OopsConcept.java b/OopsConcept.java new file mode 100644 index 0000000..5902834 --- /dev/null +++ b/OopsConcept.java @@ -0,0 +1,21 @@ +class Student{ + int rollno; + String name; + float fee; + Student(int roll,String names,float fees){ + rollno=roll; + name=names; + fee=fees; + } + void display(){ + System.out.println(rollno+" "+name+" "+fee); + } +} +class OopsConcept{ + public static void main(String args[]){ + Student s1=new Student(111,"ankit",5000f); + Student s2=new Student(112,"sumit",6000f); + s1.display(); + s2.display(); + } +} diff --git a/Pattern.java b/Pattern.java new file mode 100644 index 0000000..bc9dd90 --- /dev/null +++ b/Pattern.java @@ -0,0 +1,35 @@ +import java.util.Scanner; +public class MainClass +{ + public static void main(String[] args) + { + Scanner sc = new Scanner(System.in); + + //Taking rows value from the user + + System.out.println("How many rows you want in this pattern?"); + + int rows = sc.nextInt(); + + System.out.println("Here is your pattern....!!!"); + + for (int i=1; i<= rows ; i++) + { + for (int j = i; j < rows ; j++) { + System.out.print(" "); + } + for (int k = 1; k <= (2*i -1) ;k++) { + if( k==1 || i == rows || k==(2*i-1)) { + System.out.print("*"); + } + else { + System.out.print(" "); + } + } + System.out.println(""); + } + + //Close the resources + sc.close(); + } +} diff --git a/PreorderTraversal.java b/PreorderTraversal.java new file mode 100644 index 0000000..08dc518 --- /dev/null +++ b/PreorderTraversal.java @@ -0,0 +1,55 @@ + +class Node { + int key; + Node left, right; + + public Node(int item) + { + key = item; + left = right = null; + } +} + +class BinaryTree { + + Node root; + + BinaryTree() { + root = null; + } + + + void printInorder(Node node) + { + if (node == null) + return; + + + printInorder(node.left); + + System.out.print(node.key + " "); + + + printInorder(node.right); + } + + + void printInorder() { + printInorder(root); + } + + + public static void main(String[] args) + { + BinaryTree tree = new BinaryTree(); + tree.root = new Node(1); + tree.root.left = new Node(2); + tree.root.right = new Node(3); + tree.root.left.left = new Node(4); + tree.root.left.right = new Node(5); + + + System.out.println("\nInorder traversal of binary tree is "); + tree.printInorder(); + } +} diff --git a/Program to Check whether Person is eligible to vote or Not.java b/Program to Check whether Person is eligible to vote or Not.java new file mode 100644 index 0000000..f6d76de --- /dev/null +++ b/Program to Check whether Person is eligible to vote or Not.java @@ -0,0 +1,20 @@ +import java.util.*; +class Voting +{ + public static void main(String args[]) + { + Scanner sc = new Scanner(System.in); + System.out.println("Enter your Name: "); + String name=sc.nextLine(); + System.out.println("Enter your age: "); + int age=sc.nextInt(); + if((age>=18)&&(age<=100)) + { + System.out.println("Congratulation "+name+", You are eligible for Voting"); + } + else + { + System.out.println("Sorry "+name+", You are not eligible for voting"); + } + } +} diff --git a/RadixSort.java b/RadixSort.java new file mode 100644 index 0000000..7667727 --- /dev/null +++ b/RadixSort.java @@ -0,0 +1,80 @@ +// Radix sort Java implementation + +import java.io.*; +import java.util.*; + +class Radix { + + // A utility function to get maximum value in arr[] + static int getMax(int arr[], int n) + { + int mx = arr[0]; + for (int i = 1; i < n; i++) + if (arr[i] > mx) + mx = arr[i]; + return mx; + } + + // A function to do counting sort of arr[] according to + // the digit represented by exp. + static void countSort(int arr[], int n, int exp) + { + int output[] = new int[n]; // output array + int i; + int count[] = new int[10]; + Arrays.fill(count, 0); + + // Store count of occurrences in count[] + for (i = 0; i < n; i++) + count[(arr[i] / exp) % 10]++; + + // Change count[i] so that count[i] now contains + // actual position of this digit in output[] + for (i = 1; i < 10; i++) + count[i] += count[i - 1]; + + // Build the output array + for (i = n - 1; i >= 0; i--) { + output[count[(arr[i] / exp) % 10] - 1] = arr[i]; + count[(arr[i] / exp) % 10]--; + } + + // Copy the output array to arr[], so that arr[] now + // contains sorted numbers according to current + // digit + for (i = 0; i < n; i++) + arr[i] = output[i]; + } + + // The main function to that sorts arr[] of + // size n using Radix Sort + static void radixsort(int arr[], int n) + { + // Find the maximum number to know number of digits + int m = getMax(arr, n); + + // Do counting sort for every digit. Note that + // instead of passing digit number, exp is passed. + // exp is 10^i where i is current digit number + for (int exp = 1; m / exp > 0; exp *= 10) + countSort(arr, n, exp); + } + + // A utility function to print an array + static void print(int arr[], int n) + { + for (int i = 0; i < n; i++) + System.out.print(arr[i] + " "); + } + + // Main driver method + public static void main(String[] args) + { + int arr[] = { 170, 45, 75, 90, 802, 24, 2, 66 }; + int n = arr.length; + + // Function Call + radixsort(arr, n); + print(arr, n); + } +} diff --git a/RatMaze.java b/RatMaze.java new file mode 100644 index 0000000..07935d0 --- /dev/null +++ b/RatMaze.java @@ -0,0 +1,85 @@ + + +public class RatMaze { + + + static int N; + + + void printSolution(int sol[][]) + { + for (int i = 0; i < N; i++) { + for (int j = 0; j < N; j++) + System.out.print( + " " + sol[i][j] + " "); + System.out.println(); + } + } + + + boolean isSafe( + int maze[][], int x, int y) + { + + return (x >= 0 && x < N && y >= 0 + && y < N && maze[x][y] == 1); + } + + + boolean solveMaze(int maze[][]) + { + int sol[][] = new int[N][N]; + + if (solveMazeUtil(maze, 0, 0, sol) == false) { + System.out.print("Solution doesn't exist"); + return false; + } + + printSolution(sol); + return true; + } + + + boolean solveMazeUtil(int maze[][], int x, int y, + int sol[][]) + { + + if (x == N - 1 && y == N - 1 + && maze[x][y] == 1) { + sol[x][y] = 1; + return true; + } + + if (isSafe(maze, x, y) == true) { + if (sol[x][y] == 1) + return false; + + sol[x][y] = 1; + + if (solveMazeUtil(maze, x + 1, y, sol)) + return true; + + + if (solveMazeUtil(maze, x, y + 1, sol)) + return true; + + + sol[x][y] = 0; + return false; + } + + return false; + } + + public static void main(String args[]) + { + RatMaze rat = new RatMaze(); + int maze[][] = { { 1, 0, 0, 0 }, + { 1, 1, 0, 1 }, + { 0, 1, 0, 0 }, + { 1, 1, 1, 1 } }; + + N = maze.length; + rat.solveMaze(maze); + } +} diff --git a/Reverse a Number using a while loop.java b/Reverse a Number using a while loop.java new file mode 100644 index 0000000..a443512 --- /dev/null +++ b/Reverse a Number using a while loop.java @@ -0,0 +1,21 @@ +class Main { + public static void main(String[] args) { + + int num = 1234, reversed = 0; + + System.out.println("Original Number: " + num); + + // run loop until num becomes 0 + while(num != 0) { + + // get last digit from num + int digit = num % 10; + reversed = reversed * 10 + digit; + + // remove the last digit from num + num /= 10; + } + + System.out.println("Reversed Number: " + reversed); + } +} diff --git a/Reverse-words-in-string.java b/Reverse-words-in-string.java new file mode 100644 index 0000000..840625a --- /dev/null +++ b/Reverse-words-in-string.java @@ -0,0 +1,18 @@ +class Solution { + public String reverseWords(String s) { + String resp = ""; + List list = Arrays.asList(s.split(" ")); + for(String word : list){ + resp += reverseIt(word); + resp += " "; + } + return resp.trim(); + } + + String reverseIt(String word){ + StringBuilder input = new StringBuilder(); + input.append(word); + input.reverse(); + return input.toString(); + } +} diff --git a/ReverseNumberPrint.java b/ReverseNumberPrint.java new file mode 100644 index 0000000..6bdf4a1 --- /dev/null +++ b/ReverseNumberPrint.java @@ -0,0 +1,13 @@ +public class ReverseNumber{ +public static void main(String[] args) +{ +int number = 987654, reverse = 0; +while(number != 0) +{ +int remainder = number % 10; +reverse = reverse * 10 + remainder; +number = number/10; +} +System.out.println("The reverse of the given number is: " + reverse); +} +} diff --git a/RockPaperScissors.java b/RockPaperScissors.java new file mode 100644 index 0000000..a850b44 --- /dev/null +++ b/RockPaperScissors.java @@ -0,0 +1,65 @@ +import java.util.*; + +class RockPaperScissors +{ + public static void print(int cc) + { + if(cc==1) + { + System.out.println("Computer choice is Rock"); + } + else if(cc==2) + { + System.out.println("Computer choice is Scissors"); + } + else if(cc==3) + { + System.out.println("Computer choice is Paper"); + } + } + + public static boolean check(int uc1) + { + boolean flag; + if(uc1 == 1 || uc1==2 || uc1==3) + { + flag=true; + } + else + { + flag=false; + } + return flag; + } + public static void main(String[] args) + { + System.out.println("Choose :\n1 for Rock\n2 for Scissors\n3 for Paper"); + Random rm = new Random(); + Scanner sc = new Scanner(System.in); + int uc = sc.nextInt(); + boolean flag1 = check(uc); + + if(!flag1) + { + System.out.println("Enter Right Choice"); + } + else + { + int cc = rm.nextInt(1,4); + print(cc); + + if(cc==uc) + { + System.out.println("It's a draw"); + } + else if((cc==2 && uc==1) || (cc==3 && uc==2) || (uc==3 && cc==1)) + { + System.out.println("You won"); + } + else + { + System.out.println("Computer won"); + } + } + } +} \ No newline at end of file diff --git a/Rock_Paper_Scissors.java b/Rock_Paper_Scissors.java new file mode 100644 index 0000000..32cca74 --- /dev/null +++ b/Rock_Paper_Scissors.java @@ -0,0 +1,64 @@ +import java.util.*; + +public class Game +{ + + public static final String ROCK = "ROCK"; + public static final String PAPER = "PAPER"; + public static final String SCISSORS = "SCISSORS"; + + public static void main(String args[]) + { + System.out.println("Enter any one of the following inputs: "); + System.out.println("ROCK"); + System.out.println("PAPER"); + System.out.println("SCISSORS"); + System.out.println(); + + String playerMove = getPlayerMove(); + String computerMove = getComputerMove(); + + + if (playerMove.equals(computerMove)) + System.out.println("Game is Tie !!"); + // if playerMove is ROCK + else if (playerMove.equals(Game.ROCK)) + System.out.println(computerMove.equals(Game.PAPER) ? "Computer Wins": "Player wins"); + // if playerMove is PAPER + else if (playerMove.equals(Game.PAPER)) + System.out.println(computerMove.equals(Game.SCISSORS) ? "Computer Wins": "Player wins"); + // if playerMove is SCISSORS + else + System.out.println(computerMove.equals(Game.ROCK) ? "Computer Wins": "Player wins"); + } + + /* Get Computer's move using Random + class nextInt() method */ + public static String getComputerMove() + { + String computermove; + Random random = new Random(); + int input = random.nextInt(3)+1; + if (input == 1) + computermove = Game.ROCK; + else if(input == 2) + computermove = Game.PAPER; + else + computermove = Game.SCISSORS; + + System.out.println("Computer move is: " + computermove); + System.out.println(); + return computermove; + } + + /* Get Player's move using Scanner + class */ + public static String getPlayerMove() + { + Scanner in = new Scanner(System.in); + String input = in.next(); + String playermove = input.toUpperCase(); + System.out.println("Player move is: "+ playermove); + return playermove; + } +} diff --git a/Search using BinarySearch b/Search using BinarySearch new file mode 100644 index 0000000..af46a65 --- /dev/null +++ b/Search using BinarySearch @@ -0,0 +1,16 @@ +import java.util.Collections; +import java.util.ArrayList; + +class Main { + public static void main(String[] args) { + // Creating an ArrayList + ArrayList numbers = new ArrayList<>(); + numbers.add(1); + numbers.add(2); + numbers.add(3); + + // Using binarySearch() + int pos = Collections.binarySearch(numbers, 3); + System.out.println("The position of 3 is " + pos); + } +} diff --git a/Shell_Sort.java b/Shell_Sort.java new file mode 100644 index 0000000..15c1589 --- /dev/null +++ b/Shell_Sort.java @@ -0,0 +1,47 @@ +package Sorting; + +public class shell { + + public static void main(String args[]) + { + int[] a={9, 8, 3, 56, 5, 6, 4, 1}; + int length=a.length; + + + int gap=length/2; + // System.out.println(gap); + while(gap>0) + { + for(int i=gap;i=gap && a[j-gap]>temp) + { + // System.out.println(a[j]); + a[j]=a[j-gap]; + // System.out.println(a[j]); + j=j-gap; + + a[j]=temp; + // System.out.println(a[j]); + + } + + + } + + gap=gap/2; + + + } + for(int i=0;i spiralOrder(vector>& matrix) { + + int count=0; + vector ans; + int startingrow=0,startingcol=0,endingrow=matrix.size(),endingcol=matrix[0].size(); + int total=endingrow*endingcol; + endingrow=matrix.size()-1; + endingcol=endingcol-1; + + while(count=startingcol&&count=startingrow&&count TC = (9^N). Also, O(9*9) is + * required for checking validity and finding blanks. + * + * Space Complexity: O(3*9 + 2*N). 3*9 for rows, cols and boxes int array. N for + * blanks list. N will be the recursion depth. + * + * N = Number of blank spaces. In worst case it can be 9*9 = 81. + */ +class Solution1 { + public void solveSudoku(char[][] board) { + if (board == null || board.length != 9 || board[0].length != 9) { + throw new IllegalArgumentException("Input is invalid"); + } + + int[] rows = new int[9]; + int[] cols = new int[9]; + int[] boxes = new int[9]; + List blanks = new ArrayList<>(); + + for (int i = 0; i < 9; i++) { + for (int j = 0; j < 9; j++) { + char c = board[i][j]; + // To Blanks List + if (c == '.') { + blanks.add(new int[] { i, j }); + continue; + } + + // Check for Invalid Chars + if (c < '1' || c > '9') { + throw new IllegalArgumentException("Invalid sudoku board"); + } + + int b = 3 * (i / 3) + (j / 3); + int mask = 1 << (c - '1'); + + // Check for unsolvable board + if (((rows[i] & mask) != 0) || ((cols[j] & mask) != 0) || ((boxes[b] & mask) != 0)) { + throw new IllegalArgumentException("Invalid sudoku board"); + } + + // Add the cell to rows, cols and boxes. + rows[i] |= mask; + cols[j] |= mask; + boxes[b] |= mask; + } + } + + if (!solveSudokuHelper(board, rows, cols, boxes, blanks, 0)) { + throw new RuntimeException("Input sudoku does not have a valid solution"); + } + } + + private boolean solveSudokuHelper(char[][] board, int[] rows, int[] cols, int[] boxes, List blanks, + int idx) { + if (idx == blanks.size()) { + return true; + } + + int[] cell = blanks.get(idx); + int i = cell[0]; + int j = cell[1]; + int b = 3 * (i / 3) + (j / 3); + + for (char c = '1'; c <= '9'; c++) { + int mask = 1 << (c - '1'); + + // Check if the number already used in row, column and sub-box. + if (((rows[i] & mask) != 0) || ((cols[j] & mask) != 0) || ((boxes[b] & mask) != 0)) { + continue; + } + + // Add the cell to rows, cols and boxes. + rows[i] |= mask; + cols[j] |= mask; + boxes[b] |= mask; + board[i][j] = c; + + if (solveSudokuHelper(board, rows, cols, boxes, blanks, idx + 1)) { + return true; + } + + // Backtrack + // Remove the cell to rows, cols and boxes. + rows[i] &= ~mask; + cols[j] &= ~mask; + boxes[b] &= ~mask; + } + + return false; + } +} diff --git a/Swap Numbers b/Swap Numbers new file mode 100644 index 0000000..ff675de --- /dev/null +++ b/Swap Numbers @@ -0,0 +1,24 @@ +public class SwapNumbers { + + public static void main(String[] args) { + + float first = 1.20f, second = 2.45f; + + System.out.println("--Before swap--"); + System.out.println("First number = " + first); + System.out.println("Second number = " + second); + + // Value of first is assigned to temporary + float temporary = first; + + // Value of second is assigned to first + first = second; + + // Value of temporary (which contains the initial value of first) is assigned to second + second = temporary; + + System.out.println("--After swap--"); + System.out.println("First number = " + first); + System.out.println("Second number = " + second); + } +} diff --git a/TestTwoMethods.java b/TestTwoMethods.java new file mode 100644 index 0000000..d663522 --- /dev/null +++ b/TestTwoMethods.java @@ -0,0 +1,11 @@ +package demoTest; + +public class TestTwoMethods { + public String checkMood(String message){ + return "Happy"; + } + + public static String displayStudentName(String firstName, String lastName) { + return firstName + " "+lastName; + } +} diff --git a/Tic-tac-toe java program.java b/Tic-tac-toe java program.java new file mode 100644 index 0000000..04abd22 --- /dev/null +++ b/Tic-tac-toe java program.java @@ -0,0 +1,176 @@ +import java.util.Scanner; + + +public class TicTacToe +{ + private int counter; + private char posn[]=new char[10]; + private char player; + + + public static void main(String args[]) + { + String ch; + TicTacToe Toe=new TicTacToe(); + do{ + Toe.newBoard(); + Toe.play(); + System.out.println ("Would you like to play again (Enter 'yes')? "); + Scanner in =new Scanner(System.in); + ch=in.nextLine(); + System.out.println("ch value is "+ch); + }while (ch.equals("yes")); + + + } + public void newBoard() + { + + char posndef[] = {'0','1', '2', '3', '4', '5', '6', '7', '8', '9'}; + int i; + counter = 0; + player = 'X'; + for (i=1; i<10; i++) posn[i]=posndef[i]; + currentBoard(); + + + } + public String currentBoard() + { + System.out.println( "\n\n" ); + System.out.println( "\n\n" ); + System.out.println( "\n\n\t\t" + posn [1] + " | " +posn [2]+ " | " +posn [3]); + System.out.println( " \t\t | | " ); + System.out.println( " \t\t ___|____|___ " ); + System.out.println( "\n\n\t\t" +posn [4]+ " | " +posn [5]+ " | " +posn [6]); + System.out.println( " \t\t | | " ); + System.out.println( " \t\t ___|____|___ " ); + System.out.println( "\n\n\t\t" +posn [7]+ " | " +posn [8]+ " | " +posn [9]); + System.out.println( " \t\t | | " ); + System.out.println( " \t\t | | " ); + System.out.println( "\n\n" ); + return "currentBoard"; + } + + public void play() + { + int spot; + char blank = ' '; + + System.out.println( "Player " + getPlayer() +" will go first and be the letter 'X'" ); + + do { + currentBoard(); // display current board + + System.out.println( "\n\n Player " + getPlayer() +" choose a posn." ); + + boolean posTaken = true; + while (posTaken) { + // System.out.println( "position is taken, please enter a valid space"); + Scanner in =new Scanner (System.in); + spot=in.nextInt(); + posTaken = checkPosn(spot); + if(posTaken==false) + posn[spot]=getPlayer(); + } + + System.out.println( "Nice move." ); + + currentBoard(); // display current board + + nextPlayer(); + }while ( checkWinner() == blank ); + + } + + public char checkWinner() + { + char Winner = ' '; + + // Check if X wins + if (posn[1] == 'X' && posn[2] == 'X' && posn[3] == 'X') Winner = 'X'; + if (posn[4] == 'X' && posn[5] == 'X' && posn[6] == 'X') Winner = 'X'; + if (posn[7] == 'X' && posn[8] == 'X' && posn[9] == 'X') Winner = 'X'; + if (posn[1] == 'X' && posn[4] == 'X' && posn[7] == 'X') Winner = 'X'; + if (posn[2] == 'X' && posn[5] == 'X' && posn[8] == 'X') Winner = 'X'; + if (posn[3] == 'X' && posn[6] == 'X' && posn[9] == 'X') Winner = 'X'; + if (posn[1] == 'X' && posn[5] == 'X' && posn[9] == 'X') Winner = 'X'; + if (posn[3] == 'X' && posn[5] == 'X' && posn[7] == 'X') Winner = 'X'; + if (Winner == 'X' ) + {System.out.println("Player1 wins the game." ); + return Winner; + } + + // Check if O wins + if (posn[1] == 'O' && posn[2] == 'O' && posn[3] == 'O') Winner = 'O'; + if (posn[4] == 'O' && posn[5] == 'O' && posn[6] == 'O') Winner = 'O'; + if (posn[7] == 'O' && posn[8] == 'O' && posn[9] == 'O') Winner = 'O'; + if (posn[1] == 'O' && posn[4] == 'O' && posn[7] == 'O') Winner = 'O'; + if (posn[2] == 'O' && posn[5] == 'O' && posn[8] == 'O') Winner = 'O'; + if (posn[3] == 'O' && posn[6] == 'O' && posn[9] == 'O') Winner = 'O'; + if (posn[1] == 'O' && posn[5] == 'O' && posn[9] == 'O') Winner = 'O'; + if (posn[3] == 'O' && posn[5] == 'O' && posn[7] == 'O') Winner = 'O'; + if (Winner == 'O' ) + { + System.out.println( "Player2 wins the game." ); + return Winner; } + + // check for Tie + for(int i=1;i<10;i++) + { + if(posn[i]=='X' || posn[i]=='O') + { + if(i==9) + { + char Draw='D'; + System.out.println(" Game is stalemate "); + return Draw; + } + continue; + } + else + break; + + } + + return Winner; + } + + public boolean checkPosn(int spot) + { + + + if (posn[spot] == 'X' || posn[spot] == 'O') + { + System.out.println("That posn is already taken, please choose another"); + return true; + } + else { + return false; + } + + // counter++; + // return false; + } + + + + public void nextPlayer() + { + if (player == 'X') + player = 'O'; + else player = 'X'; + + } + + public String getTitle() + { + return "Tic Tac Toe" ; + } + + public char getPlayer() + { + return player; + } + +} diff --git a/TimSort.java b/TimSort.java new file mode 100644 index 0000000..f4d00b9 --- /dev/null +++ b/TimSort.java @@ -0,0 +1,84 @@ +import java.util.Arrays; +public final class TimSort { + + static int RUN = 32; + public static void insertionSort(int[] arr, int left, int right) { + for (int i = left + 1; i <= right; i++) { + int temp = arr[i]; + int j = i - 1; + while (j >= 0 && arr[j] > temp && j >= left) { + arr[j + 1] = arr[j]; + j--; + } + arr[j + 1] = temp; + } + } + + public static void merge(int[] arr, int left, int mid, int right) { + + int leftArryLen = mid - left + 1, rightArrLen = right - mid; + int[] leftArr = new int[leftArryLen]; + int[] rightArr = new int[rightArrLen]; + + for (int x = 0; x < leftArryLen; x++) { + leftArr[x] = arr[left + x]; + } + + for (int x = 0; x < rightArrLen; x++) { + rightArr[x] = arr[mid + 1 + x]; + } + + int i = 0; + int j = 0; + int k = left; + + while (i < leftArryLen && j < rightArrLen) { + if (leftArr[i] <= rightArr[j]) { + arr[k] = leftArr[i]; + i++; + } else { + arr[k] = rightArr[j]; + j++; + } + k++; + } + + while (i < leftArryLen) { + arr[k] = leftArr[i]; + k++; + i++; + } + + while (j < rightArrLen) { + arr[k] = rightArr[j]; + k++; + j++; + } + } + + public static void timSort(int[] arr) { + int length = arr.length; + + // Sort individual subarrays of size THRESHOLD + for (int i = 0; i < length; i += RUN) { + // perform insertion sort + insertionSort(arr, i, Math.min((i + 31), (length - 1))); + } + + for (int size = RUN; size < length; size = 2 * size) { + for (int left = 0; left < length; left += 2 * size) { + int mid = left + size - 1; + int right = Math.min((left + 2 * size - 1), (length - 1)); + // perform merge sort + merge(arr, left, mid, right); + } + } + } + + public static void main(String[] args) { + int[] arr = { 10, 3, 2, 19, 7, 15, 23, 13, 1 }; + System.out.println(Arrays.toString(arr)); + timSort(arr); + System.out.println(Arrays.toString(arr)); + } +} diff --git a/Transpose_of_Matrix.java b/Transpose_of_Matrix.java new file mode 100644 index 0000000..0cc2dcc --- /dev/null +++ b/Transpose_of_Matrix.java @@ -0,0 +1,30 @@ +public class MatrixTransposeExample{ +public static void main(String args[]){ +//creating a matrix +int original[][]={{1,3,4},{2,4,3},{3,4,5}}; + +//creating another matrix to store transpose of a matrix +int transpose[][]=new int[3][3]; //3 rows and 3 columns + +//Code to transpose a matrix +for(int i=0;i<3;i++){ +for(int j=0;j<3;j++){ +transpose[i][j]=original[j][i]; +} +} + +System.out.println("Printing Matrix without transpose:"); +for(int i=0;i<3;i++){ +for(int j=0;j<3;j++){ +System.out.print(original[i][j]+" "); +} +System.out.println();//new line +} +System.out.println("Printing Matrix After Transpose:"); +for(int i=0;i<3;i++){ +for(int j=0;j<3;j++){ +System.out.print(transpose[i][j]+" "); +} +System.out.println();//new line +} +}} diff --git a/Tree/treeds b/Tree/treeds new file mode 100644 index 0000000..a803c64 --- /dev/null +++ b/Tree/treeds @@ -0,0 +1,165 @@ +import java.util.*; + +class Tree{ + static node create(){ + Scanner sc=new Scanner(System.in); + node root=null; + System.out.println("Enter the data "); + int data=sc.nextInt(); + if(data==-1){ + return null; + } + root=new node(data); + System.out.println("enter data to left of root "+root.data); + root.left=create(); + System.out.println("enter data to right of root "+root.data); + root.right=create(); + return root; + } + public static int height(node root){ + if(root==null){ + return 0; + } + return Math.max(height(root.left),height(root.right))+1; + } + public static class node{ + node left,right; + int data; + node(int data){ + this.data=data; + left=null; + right=null; + } + } + //preorder traversal in tree data structure + public static void preoder(node root){ + if(root==null){ + return; + } + System.out.print(root.data+" "); + preoder(root.left); + preoder(root.right); + } + //finding maximum in tree + public static int maximum(node root){ + if(root==null) + return Integer.MIN_VALUE; + return Math.max(root.data,Math.max(maximum(root.left),maximum(root.right))); + } + //finding minimum in tree + public static int minimum(node root){ + if(root==null) + return Integer.MAX_VALUE; + return Math.min(root.data,Math.min(minimum(root.left),minimum(root.right))); + } + //postorder traversal in tree + public static void postorder(node root){ + if(root==null){ + return; + } + postorder(root.left); + postorder(root.right); + System.out.print(root.data+" "); + } + //inoreder traveral in tree + public static void inorder(node root){ + if(root==null){ + return; + } + inorder(root.left); + System.out.print(root.data+" "); + inorder(root.right); + } + //level order traversal in tree + public static void levelorder(node root){ + Queue q=new LinkedList<>(); + q.add(root); + while(!q.isEmpty()){ + node cur=q.poll(); + System.out.print(cur.data+" "); + if(cur.left!=null){ + q.add(cur.left); + } + if(cur.right!=null){ + q.add(cur.right); + } + } + } + //int size of tree + public static int size(node root) { + if(root == null) + return 0; + return size(root.left)+size(root.right)+1; + } + public static void printleftview(node root){ + ArrayList list=new ArrayList<>(); + printviewleft(root, list, 0); + for(node cur: list){ + System.out.print(cur.data+" "); + } + } + public static void printviewleft(node root,ArrayList list,int level){ + if(root==null){ + return; + } + if(list.get(level)==null){ + list.set(level,root); + } + printviewleft(root.left, list, level+1); + printviewleft(root.right, list, level+1); + } + + public static void levelordernextlevel(node root){ + Queue q1=new LinkedList<>(); + q1.add(root); + q1.add(null); + while(!q1.isEmpty()){ + node cur=q1.poll(); + if(cur==null){ + if(q1.isEmpty()){ + return; + } + q1.add(null); + System.out.println(); + continue; + } + System.out.print(cur.data+" "); + + if(cur.left!=null){ + q1.add(cur.left); + } + if(cur.right!=null){ + q1.add(cur.right); + } + } + } + + + public static void main(String [] args){ + node root=create(); + System.out.print("preorder:-"); + preoder(root); + System.out.println(); + System.out.print("inorder:-"); + inorder(root); + System.out.println(); + System.out.print("postorder:-"); + postorder(root); + System.out.println(); + System.out.print("levelorder:-"); + levelorder(root); + System.out.println(); + System.out.print("levelorder next line:-"); + levelordernextlevel(root); + System.out.println(); + System.out.print("height of tree is "+ height(root)); + System.out.println(); + System.out.print("size of tree is "+ size(root)); + System.out.println(); + System.out.print("maximum of tree is "+ maximum(root)); + System.out.println(); + System.out.print("minimum of tree is "+ minimum(root)); + System.out.println(); + printleftview(root); + } +} diff --git a/Tree_traversal.java b/Tree_traversal.java new file mode 100644 index 0000000..33bede1 --- /dev/null +++ b/Tree_traversal.java @@ -0,0 +1,75 @@ +class Node { + public int value; + public Node left, right; + + public Node(int element) + { + value = element; + left = right = null; + } +} + +class Tree { + Node root; /* root of the tree */ + + Tree() { root = null; } + /*function to print the nodes of given binary in Preorder*/ + void traversePreorder(Node node) + { + if (node == null) + return; + System.out.print(node.value + " "); + traversePreorder(node.left); + traversePreorder(node.right); + } + /*function to print the nodes of given binary in Inorder*/ + void traverseInorder(Node node) + { + if (node == null) + return; + traverseInorder(node.left); + System.out.print(node.value + " "); + traverseInorder(node.right); + } + /*function to print the nodes of given binary in Postorder*/ + void traversePostorder(Node node) + { + if (node == null) + return; + traversePostorder(node.left); + traversePostorder(node.right); + System.out.print(node.value + " "); + } + + + void traversePreorder() { traversePreorder(root); } + void traverseInorder() { traverseInorder(root); } + void traversePostorder() { traversePostorder(root); } + + public static void main(String args[]) + { + Tree pt = new Tree(); + pt.root = new Node(36); + pt.root.left = new Node(26); + pt.root.right = new Node(46); + pt.root.left.left = new Node(21); + pt.root.left.right = new Node(31); + pt.root.left.left.left = new Node(11); + pt.root.left.left.right = new Node(24); + pt.root.right.left = new Node(41); + pt.root.right.right = new Node(56); + pt.root.right.right.left = new Node(51); + pt.root.right.right.right = new Node(66); + + System.out.println(); + System.out.println("The Preorder traversal of given binary tree is - "); + pt.traversePreorder(); + System.out.println("\n"); + System.out.println("The Inorder traversal of given binary tree is - "); + pt.traverseInorder(); + System.out.println("\n"); + System.out.println("The Postorder traversal of given binary tree is - "); + pt.traversePostorder(); + System.out.println(); + } +} \ No newline at end of file diff --git a/addTwoNumber.java b/addTwoNumber.java new file mode 100644 index 0000000..7fa0a47 --- /dev/null +++ b/addTwoNumber.java @@ -0,0 +1,16 @@ +import java.util.*; +import java.util.Scanner; +public class addTwoNumber { +public static void main (String[] args) { + + /* code */ + int a = 5; + int b = 10; + Scanner s = new Scanner(System.in); +int a = s.nextInt(); +int b = s.nextInt(); +System.out.println(a+b); + +} + +} \ No newline at end of file diff --git a/armstrongCheck.java b/armstrongCheck.java new file mode 100644 index 0000000..f9ef4c0 --- /dev/null +++ b/armstrongCheck.java @@ -0,0 +1,24 @@ +import java.util.Scanner; +public class JavaExample { + + public static void main(String[] args) { + + int num, number, temp, total = 0; + System.out.println("Enter 3 Digit Number"); + Scanner scanner = new Scanner(System.in); + num = scanner.nextInt(); + scanner.close(); + number = num; + + for( ;number!=0;number /= 10) + { + temp = number % 10; + total = total + temp*temp*temp; + } + + if(total == num) + System.out.println(num + " is an Armstrong number"); + else + System.out.println(num + " is not an Armstrong number"); + } +} diff --git a/bubble_sort.java b/bubble_sort.java new file mode 100644 index 0000000..ff0f385 --- /dev/null +++ b/bubble_sort.java @@ -0,0 +1,62 @@ +public class BubbleSortExample { + /*worst case of this code is O(n2).*/ + static void bubbleSort(int[] arr) { + int n = arr.length; + int temp = 0; + for(int i=0; i < n; i++){ + for(int j=1; j < (n-i); j++){ + if(arr[j-1] > arr[j]){ + //swap elements + temp = arr[j-1]; + arr[j-1] = arr[j]; + arr[j] = temp; + } + + } + } + + + } + /* An optimized version of Bubble Sort + worst case of this code is O(n).*/ + + static void optimizedbubbleSort(int arr[], int n) + { + int i, j, temp; + boolean swapped; + for (i = 0; i < n - 1; i++) + { + swapped = false; + for (j = 0; j < n - i - 1; j++) + { + if (arr[j] > arr[j + 1]) + { + temp = arr[j]; + arr[j] = arr[j + 1]; + arr[j + 1] = temp; + swapped = true; + } + } + if (swapped == false) + break; + } + } + public static void main(String[] args) { + int arr[] ={3,60,35,2,45,320,5}; + + System.out.println("Array Before Bubble Sort"); + for(int i=0; i < arr.length; i++){ + System.out.print(arr[i] + " "); + } + System.out.println(); + + bubbleSort(arr);/*sorting array elements using bubble sort */ + + System.out.println("Array After Bubble Sort"); + for(int i=0; i < arr.length; i++){ + System.out.print(arr[i] + " "); + } + + } +} +//THIS CODE IS UPDATED BY BATRAKESHAV10 diff --git a/bubblesort.java b/bubblesort.java index 436662e..a688ae9 100644 --- a/bubblesort.java +++ b/bubblesort.java @@ -1,35 +1,50 @@ -public class BubbleSortExample { - static void bubbleSort(int[] arr) { - int n = arr.length; - int temp = 0; - for(int i=0; i < n; i++){ - for(int j=1; j < (n-i); j++){ - if(arr[j-1] > arr[j]){ - //swap elements - temp = arr[j-1]; - arr[j-1] = arr[j]; - arr[j] = temp; - } - - } - } - - } - public static void main(String[] args) { - int arr[] ={3,60,35,2,45,320,5}; - - System.out.println("Array Before Bubble Sort"); - for(int i=0; i < arr.length; i++){ - System.out.print(arr[i] + " "); - } - System.out.println(); - - bubbleSort(arr);//sorting array elements using bubble sort - - System.out.println("Array After Bubble Sort"); - for(int i=0; i < arr.length; i++){ - System.out.print(arr[i] + " "); - } - - } -} +import java.io.*; + +class GFG +{ + // An optimized version of Bubble Sort + static void bubbleSort(int arr[], int n) + { + int i, j, temp; + boolean swapped; + for (i = 0; i < n - 1; i++) + { + swapped = false; + for (j = 0; j < n - i - 1; j++) + { + if (arr[j] > arr[j + 1]) + { + // swap arr[j] and arr[j+1] + temp = arr[j]; + arr[j] = arr[j + 1]; + arr[j + 1] = temp; + swapped = true; + } + } + + // IF no two elements were + // swapped by inner loop, then break + if (swapped == false) + break; + } + } + + // Function to print an array + static void printArray(int arr[], int size) + { + int i; + for (i = 0; i < size; i++) + System.out.print(arr[i] + " "); + System.out.println(); + } + + // Driver program + public static void main(String args[]) + { + int arr[] = { 64, 34, 25, 12, 22, 11, 90 }; + int n = arr.length; + bubbleSort(arr, n); + System.out.println("Sorted array: "); + printArray(arr, n); + } +} \ No newline at end of file diff --git a/bubblesorthacktoberfest.java b/bubblesorthacktoberfest.java new file mode 100644 index 0000000..24119cf --- /dev/null +++ b/bubblesorthacktoberfest.java @@ -0,0 +1,31 @@ +package Sorting; + +public class bubblesort { + + public static void main(String args[]) + { + int a[]={3,4,5,2,1,87,45} + + for(int i=1;i=0 && a[hole]>key) + { + a[hole+1]=a[hole]; + hole=hole-1; + + a[hole+1]=key; + } + } + + for(int i=0;i arr[j + 1]) + { + temp = arr[j]; + arr[j] = arr[j + 1]; + arr[j + 1] = temp; + swapped = true; + } + } + if (swapped == false) + break; + } + } + public static void main(String[] args) { + int arr[] ={3,60,35,2,45,320,5}; + + System.out.println("Array Before Bubble Sort"); + for(int i=0; i < arr.length; i++){ + System.out.print(arr[i] + " "); + } + System.out.println(); + + bubbleSort(arr);//sorting array elements using bubble sort + + System.out.println("Array After Bubble Sort"); + for(int i=0; i < arr.length; i++){ + System.out.print(arr[i] + " "); + } + + } +} diff --git a/calculator.java b/calculator.java new file mode 100644 index 0000000..8f81a7b --- /dev/null +++ b/calculator.java @@ -0,0 +1,56 @@ +import java.util.Scanner; + +class Main { + public static void main(String[] args) { + + char operator; + Double number1, number2, result; + + // create an object of Scanner class + Scanner input = new Scanner(System.in); + + // ask users to enter operator + System.out.println("Choose an operator: +, -, *, or /"); + operator = input.next().charAt(0); + + // ask users to enter numbers + System.out.println("Enter first number"); + number1 = input.nextDouble(); + + System.out.println("Enter second number"); + number2 = input.nextDouble(); + + switch (operator) { + + // performs addition between numbers + case '+': + result = number1 + number2; + System.out.println(number1 + " + " + number2 + " = " + result); + break; + + // performs subtraction between numbers + case '-': + result = number1 - number2; + System.out.println(number1 + " - " + number2 + " = " + result); + break; + + // performs multiplication between numbers + case '*': + result = number1 * number2; + System.out.println(number1 + " * " + number2 + " = " + result); + break; + + // performs division between numbers + case '/': + result = number1 / number2; + System.out.println(number1 + " / " + number2 + " = " + result); + break; + + default: + System.out.println("Invalid operator!"); + break; + } + + input.close(); + } +} \ No newline at end of file diff --git a/countSort.java b/countSort.java new file mode 100644 index 0000000..332a4bb --- /dev/null +++ b/countSort.java @@ -0,0 +1,23 @@ +public class countSort { + public static void main(String[] args) { + int[] arr = {5,4,3,3,2,1}; //created array + int k = 5; + int n = arr.length; + int[] countArr = new int[k+1]; + for(int i=1;i<=k;i++) countArr[i] = 0; + + for(int i=0;i0){ + n3 = n1 + n2; + n1 = n2; + n2 = n3; + System.out.print(" "+n3); + printFibonacci(count-1); + } + } + public static void main(String args[]){ + int count=10; + System.out.print(n1+" "+n2);//printing 0 and 1 + printFibonacci(count-2);//n-2 because 2 numbers are already printed + } +} \ No newline at end of file diff --git a/fileHandler.java b/fileHandler.java new file mode 100644 index 0000000..362bb9e --- /dev/null +++ b/fileHandler.java @@ -0,0 +1,36 @@ +package gomes.fernando.robson; + +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.util.Scanner; + +public class ManipuladorArquivo { + + public static void leitor(String path) throws IOException { + BufferedReader buffRead = new BufferedReader(new FileReader(path)); + String linha = ""; + while (true) { + if (linha != null) { + System.out.println(linha); + + } else + break; + linha = buffRead.readLine(); + } + buffRead.close(); + } + + public static void escritor(String path) throws IOException { + BufferedWriter buffWrite = new BufferedWriter(new FileWriter(path)); + String linha = ""; + Scanner in = new Scanner(System.in); + System.out.println("Escreva algo: "); + linha = in.nextLine(); + buffWrite.append(linha + "\n"); + buffWrite.close(); + } + +} \ No newline at end of file diff --git a/insertion.java b/insertion.java new file mode 100644 index 0000000..a3659bb --- /dev/null +++ b/insertion.java @@ -0,0 +1,20 @@ +import java.util.*; +public class Main { +public static void main(String[] args) { + //declare an array and print the original contents + int[] numArray = {10,6,15,4,1,45}; + System.out.println("Original Array:" + Arrays.toString(numArray)); + //apply insertion sort algorithm on the array + for(int k=1; k=0 && temp <= numArray[j]) { + numArray[j+1] = numArray[j]; + j = j-1; + } + numArray[j+1] = temp; + } + //print the sorted array + System.out.println("Sorted Array:" + Arrays.toString(numArray)); +} +} \ No newline at end of file diff --git a/insertion_sort.java b/insertion_sort.java new file mode 100644 index 0000000..8e90f82 --- /dev/null +++ b/insertion_sort.java @@ -0,0 +1,41 @@ +class InsertionSort { + /*Function to sort array using insertion sort*/ + void sort(int arr[]) + { + int n = arr.length; + for (int i = 1; i < n; ++i) { + int key = arr[i]; + int j = i - 1; + + /* Move elements of arr[0..i-1], that are + greater than key, to one position ahead + of their current position */ + while (j >= 0 && arr[j] > key) { + arr[j + 1] = arr[j]; + j = j - 1; + } + arr[j + 1] = key; + } + } + + /* A utility function to print array of size n*/ + static void printArray(int arr[]) + { + int n = arr.length; + for (int i = 0; i < n; ++i) + System.out.print(arr[i] + " "); + + System.out.println(); + } + + // Driver method + public static void main(String args[]) + { + int arr[] = { 12, 11, 13, 5, 6 }; + + InsertionSort ob = new InsertionSort(); + ob.sort(arr); + + printArray(arr); + } +} diff --git a/javasubstring.java b/javasubstring.java new file mode 100644 index 0000000..68bac97 --- /dev/null +++ b/javasubstring.java @@ -0,0 +1,17 @@ +package day3; + +import java.util.*; + +class javasubstring { + + public static void main(String[] args) { + Scanner in = new Scanner(System.in); + System.out.println("Enter any String value = "); + String S = in.nextLine(); + System.out.println("Enter the start point = "); + int start = in.nextInt(); + System.out.println("Enter the end point = "); + int end = in.nextInt(); + System.out.println(S.substring(start, end)); + } +} diff --git a/jobSequencing.java b/jobSequencing.java new file mode 100644 index 0000000..b0b36fd --- /dev/null +++ b/jobSequencing.java @@ -0,0 +1,130 @@ +// This is Job Sequencing Problem using Greedy Method + +import java.util.*; + +public class jobSequencing +{ + public static void main(String args[]) + { + Scanner sc=new Scanner(System.in); + System.out.println("Enter the number of Jobs"); + int n=sc.nextInt(); + String a[]=new String[n]; + int b[]=new int[n]; + int c[]=new int[n]; + for(int i=0;imax) + { + max=c[i]; + } + } + String x[]=new String[max]; + int m[]=new int[max]; + int profit=0; + for(int i=0;i"); + } + + } + System.out.println("\n"); + System.out.print("Profit Earned "+profit); // printing total profit + } +} \ No newline at end of file diff --git a/kthLargestElement.java b/kthLargestElement.java new file mode 100644 index 0000000..e36c6e0 --- /dev/null +++ b/kthLargestElement.java @@ -0,0 +1,19 @@ +class Solution { + public int findKthLargest(int[] nums, int k) { + + PriorityQueue pq = new PriorityQueue<>(Collections.reverseOrder()); + + for(int i : nums){ + pq.add(i); + } + + int res = 0; + + while(k-- > 0){ + res = pq.poll(); + } + + + return res; + } +} diff --git a/linkedlist_Implementatino.java b/linkedlist_Implementatino.java new file mode 100644 index 0000000..87c7f3c --- /dev/null +++ b/linkedlist_Implementatino.java @@ -0,0 +1,84 @@ +import java.io.*; + +public class LinkedList { + + Node head; // head of list + + static class Node { + + int data; + Node next; + + // Constructor + Node(int d) + { + data = d; + next = null; + } + } + + // Method to insert a new node + public static LinkedList insert(LinkedList list, int data) + { + // Create a new node with given data + Node new_node = new Node(data); + + + // If the Linked List is empty, + // then make the new node as head + if (list.head == null) { + list.head = new_node; + } + else { + // Else traverse till the last node + // and insert the new_node there + Node last = list.head; + while (last.next != null) { + last = last.next; + } + + // Insert the new_node at last node + last.next = new_node; + } + + // Return the list by head + return list; + } + + // Method to print the LinkedList. + public static void printList(LinkedList list) + { + Node currNode = list.head; + + System.out.print("LinkedList: "); + + // Traverse through the LinkedList + while (currNode != null) { + // Print the data at current node + System.out.print(currNode.data + " "); + + // Go to next node + currNode = currNode.next; + } + } + + // Driver code + public static void main(String[] args) + { + /* Start with the empty list. */ + LinkedList list = new LinkedList(); + + // Insert the values + list = insert(list, 1); + list = insert(list, 2); + list = insert(list, 3); + list = insert(list, 4); + list = insert(list, 5); + list = insert(list, 6); + list = insert(list, 7); + list = insert(list, 8); + + // Print the LinkedList + printList(list); + } +} diff --git a/linklist_implementation.java b/linklist_implementation.java new file mode 100644 index 0000000..885617b --- /dev/null +++ b/linklist_implementation.java @@ -0,0 +1,289 @@ +/** + * LinkedList class implements a doubly-linked list. + */ +public class MyLinkedList implements Iterable +{ + /** + * Construct an empty LinkedList. + */ + public MyLinkedList( ) + { + doClear( ); + } + + private void clear( ) + { + doClear( ); + } + + /** + * Change the size of this collection to zero. + */ + public void doClear( ) + { + beginMarker = new Node<>( null, null, null ); + endMarker = new Node<>( null, beginMarker, null ); + beginMarker.next = endMarker; + + theSize = 0; + modCount++; + } + + /** + * Returns the number of items in this collection. + * @return the number of items in this collection. + */ + public int size( ) + { + return theSize; + } + + public boolean isEmpty( ) + { + return size( ) == 0; + } + + /** + * Adds an item to this collection, at the end. + * @param x any object. + * @return true. + */ + public boolean add( AnyType x ) + { + add( size( ), x ); + return true; + } + + /** + * Adds an item to this collection, at specified position. + * Items at or after that position are slid one position higher. + * @param x any object. + * @param idx position to add at. + * @throws IndexOutOfBoundsException if idx is not between 0 and size(), inclusive. + */ + public void add( int idx, AnyType x ) + { + addBefore( getNode( idx, 0, size( ) ), x ); + } + + /** + * Adds an item to this collection, at specified position p. + * Items at or after that position are slid one position higher. + * @param p Node to add before. + * @param x any object. + * @throws IndexOutOfBoundsException if idx is not between 0 and size(), inclusive. + */ + private void addBefore( Node p, AnyType x ) + { + Node newNode = new Node<>( x, p.prev, p ); + newNode.prev.next = newNode; + p.prev = newNode; + theSize++; + modCount++; + } + + + /** + * Returns the item at position idx. + * @param idx the index to search in. + * @throws IndexOutOfBoundsException if index is out of range. + */ + public AnyType get( int idx ) + { + return getNode( idx ).data; + } + + /** + * Changes the item at position idx. + * @param idx the index to change. + * @param newVal the new value. + * @return the old value. + * @throws IndexOutOfBoundsException if index is out of range. + */ + public AnyType set( int idx, AnyType newVal ) + { + Node p = getNode( idx ); + AnyType oldVal = p.data; + + p.data = newVal; + return oldVal; + } + + /** + * Gets the Node at position idx, which must range from 0 to size( ) - 1. + * @param idx index to search at. + * @return internal node corresponding to idx. + * @throws IndexOutOfBoundsException if idx is not between 0 and size( ) - 1, inclusive. + */ + private Node getNode( int idx ) + { + return getNode( idx, 0, size( ) - 1 ); + } + + /** + * Gets the Node at position idx, which must range from lower to upper. + * @param idx index to search at. + * @param lower lowest valid index. + * @param upper highest valid index. + * @return internal node corresponding to idx. + * @throws IndexOutOfBoundsException if idx is not between lower and upper, inclusive. + */ + private Node getNode( int idx, int lower, int upper ) + { + Node p; + + if( idx < lower || idx > upper ) + throw new IndexOutOfBoundsException( "getNode index: " + idx + "; size: " + size( ) ); + + if( idx < size( ) / 2 ) + { + p = beginMarker.next; + for( int i = 0; i < idx; i++ ) + p = p.next; + } + else + { + p = endMarker; + for( int i = size( ); i > idx; i-- ) + p = p.prev; + } + + return p; + } + + /** + * Removes an item from this collection. + * @param idx the index of the object. + * @return the item was removed from the collection. + */ + public AnyType remove( int idx ) + { + return remove( getNode( idx ) ); + } + + /** + * Removes the object contained in Node p. + * @param p the Node containing the object. + * @return the item was removed from the collection. + */ + private AnyType remove( Node p ) + { + p.next.prev = p.prev; + p.prev.next = p.next; + theSize--; + modCount++; + + return p.data; + } + + /** + * Returns a String representation of this collection. + */ + public String toString( ) + { + StringBuilder sb = new StringBuilder( "[ " ); + + for( AnyType x : this ) + sb.append( x + " " ); + sb.append( "]" ); + + return new String( sb ); + } + + /** + * Obtains an Iterator object used to traverse the collection. + * @return an iterator positioned prior to the first element. + */ + public java.util.Iterator iterator( ) + { + return new LinkedListIterator( ); + } + + /** + * This is the implementation of the LinkedListIterator. + * It maintains a notion of a current position and of + * course the implicit reference to the MyLinkedList. + */ + private class LinkedListIterator implements java.util.Iterator + { + private Node current = beginMarker.next; + private int expectedModCount = modCount; + private boolean okToRemove = false; + + public boolean hasNext( ) + { + return current != endMarker; + } + + public AnyType next( ) + { + if( modCount != expectedModCount ) + throw new java.util.ConcurrentModificationException( ); + if( !hasNext( ) ) + throw new java.util.NoSuchElementException( ); + + AnyType nextItem = current.data; + current = current.next; + okToRemove = true; + return nextItem; + } + + public void remove( ) + { + if( modCount != expectedModCount ) + throw new java.util.ConcurrentModificationException( ); + if( !okToRemove ) + throw new IllegalStateException( ); + + MyLinkedList.this.remove( current.prev ); + expectedModCount++; + okToRemove = false; + } + } + + /** + * This is the doubly-linked list node. + */ + private static class Node + { + public Node( AnyType d, Node p, Node n ) + { + data = d; prev = p; next = n; + } + + public AnyType data; + public Node prev; + public Node next; + } + + private int theSize; + private int modCount = 0; + private Node beginMarker; + private Node endMarker; +} + +class TestLinkedList +{ + public static void main( String [ ] args ) + { + MyLinkedList lst = new MyLinkedList<>( ); + + for( int i = 0; i < 10; i++ ) + lst.add( i ); + for( int i = 20; i < 30; i++ ) + lst.add( 0, i ); + + lst.remove( 0 ); + lst.remove( lst.size( ) - 1 ); + + System.out.println( lst ); + + java.util.Iterator itr = lst.iterator( ); + while( itr.hasNext( ) ) + { + itr.next( ); + itr.remove( ); + System.out.println( lst ); + } + } +} \ No newline at end of file diff --git a/oddOrEvenNumber.java b/oddOrEvenNumber.java new file mode 100644 index 0000000..b856cce --- /dev/null +++ b/oddOrEvenNumber.java @@ -0,0 +1,21 @@ +import java.util.Scanner; + +public class oddOrEvenNumber { + public static void main(String[] args) throws Exception { + + Scanner inputNumber = new Scanner(System.in); + + // Check whether a number is even or odd using if else statement + System.out.print("Enter a number:\t"); + int num = inputNumber.nextInt(); + + if (num % 2 == 0) { + System.out.print(num + " is even"); + } else { + System.out.print(num + " is odd"); + } + + inputNumber.close(); + } + +} diff --git a/overidding_MR.java b/overidding_MR.java new file mode 100644 index 0000000..2a6e0c9 --- /dev/null +++ b/overidding_MR.java @@ -0,0 +1,62 @@ + +//example of the overriding method +//return type and signature(parameter) same means the overriding method + +class a1 +{ + void hell() + { + System.out.println("hello i am from i1"); + } +} + +class b1 extends a1 +{ + void hell() + { + + System.out.println("hello i am from i1"); + } +} + +class c1 extends b1{ + void hell() + { + System.out.println("hello i am from i1"); + } +} + +public class polymorph { + + public static void main(String[] args) + { + //where c1 is called reference + // where c1() is called instance + + + //c1 obj1=new c1(); + // obj1.hell(); + + // now we take the reference of b1 and instance c1 as same + + // b1 obj1=new c1(); + // obj1.hell(); + + //it's means that if we change the instance than automatically + //sentence will be changed or method /function will be change + + //reference is a1 and instance c1 + //output is of c1 method is display + + // a1 obj1=new c1(); + //obj1.hell(); + + //reference is a1 and instance b1 + //output is of b1 method is display + + // a1 obj1=new b1(); + // obj1.hell(); + + + } +} diff --git a/palindrome.java b/palindrome.java new file mode 100644 index 0000000..26e957e --- /dev/null +++ b/palindrome.java @@ -0,0 +1,17 @@ +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"); +} +} \ No newline at end of file diff --git a/polymorphism.java b/polymorphism.java new file mode 100644 index 0000000..d8d78b9 --- /dev/null +++ b/polymorphism.java @@ -0,0 +1,70 @@ +package vid24oops; + +//Method Overloading or Run time Polymorphism (Functions can be called as per required in any type of Polymorphism) +// class Student{ +// String name; +// int age; + +// public void displayInfo(String name) { +// System.out.println(name); +// } + +// public void displayInfo(int age) { +// System.out.println(age); +// } + +// public void displayInfo(String name, int age) { +// System.out.println(name); +// System.out.println(age); +// } +// } + +// public class polymorphism { +// public static void main(String[] args) { +// Student s1 = new Student(); + +// s1.name = "Adi"; +// s1.age= 21; + +// s1.displayInfo(s1.name); //If we want only name to display + +// s1.displayInfo(s1.age); //If we want only age to display + +// s1.displayInfo(s1.name,s1.age); //If we want name and age to display +// } +// } + +//Run time polymorphism +// abstract class Animal { +// abstract void walk(); +// void breathe() { +// System.out.println("This animal breathes air"); +// } + +// Animal() { +// System.out.println("You are about to create an Animal."); +// } +// } + +// class Horse extends Animal { +// void walk() { +// System.out.println("Horse walks on 4 legs"); +// } +// } + +// class Chicken extends Animal { +// void walk() { +// System.out.println("Chicken walks on 2 legs"); +// } +// } + +// public class polymorphism { +// public static void main(String args[]) { +// Horse horse = new Horse(); +// horse.walk(); +// horse.breathe(); + +// Animal animal = new Animal(); +// animal.walk(); //Gives error when you run, but not when you compile +// } +// } diff --git a/primenumber.java b/primenumber.java new file mode 100644 index 0000000..356b605 --- /dev/null +++ b/primenumber.java @@ -0,0 +1,19 @@ +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 +} +} \ No newline at end of file diff --git a/puzzleGame.java b/puzzleGame.java new file mode 100644 index 0000000..8a4c161 --- /dev/null +++ b/puzzleGame.java @@ -0,0 +1,178 @@ +import java.awt.*; +import java.awt.event.*; +import javax.swing.JOptionPane; +public class Puzzle extends Frame implements ActionListener{ +Button b1,b2,b3,b4,b5,b6,b7,b8,b9; +Puzzle(){ + super("Puzzle - JavaTpoint"); + b1=new Button("1"); + b1.setBounds(50,100,40,40); + b2=new Button("2"); + b2.setBounds(100,100,40,40); + b3=new Button("3"); + b3.setBounds(150,100,40,40); + b4=new Button("4"); + b4.setBounds(50,150,40,40); + b5=new Button("5"); + b5.setBounds(100,150,40,40); + b6=new Button("6"); + b6.setBounds(150,150,40,40); + b7=new Button("7"); + b7.setBounds(50,200,40,40); + b8=new Button(""); + b8.setBounds(100,200,40,40); + b9=new Button("8"); + b9.setBounds(150,200,40,40); + + b1.addActionListener(this); + b2.addActionListener(this); + b3.addActionListener(this); + b4.addActionListener(this); + b5.addActionListener(this); + b6.addActionListener(this); + b7.addActionListener(this); + b8.addActionListener(this); + b9.addActionListener(this); + + add(b1);add(b2);add(b3);add(b4);add(b5);add(b6);add(b7);add(b8);add(b9); + setSize(400,400); + setLayout(null); + setVisible(true); +} +public void actionPerformed(ActionEvent e){ + if(e.getSource()==b1){ + String label=b1.getLabel(); + if(b2.getLabel().equals("")){ + b2.setLabel(label); + b1.setLabel(""); + } + if(b4.getLabel().equals("")){ + b4.setLabel(label); + b1.setLabel(""); + } + } + if(e.getSource()==b2){ + String label=b2.getLabel(); + if(b1.getLabel().equals("")){ + b1.setLabel(label); + b2.setLabel(""); + } + if(b3.getLabel().equals("")){ + b3.setLabel(label); + b2.setLabel(""); + } + if(b5.getLabel().equals("")){ + b5.setLabel(label); + b2.setLabel(""); + } + } + if(e.getSource()==b3){ + String label=b3.getLabel(); + if(b2.getLabel().equals("")){ + b2.setLabel(label); + b3.setLabel(""); + } + if(b6.getLabel().equals("")){ + b6.setLabel(label); + b3.setLabel(""); + } + } + if(e.getSource()==b4){ + String label=b4.getLabel(); + if(b1.getLabel().equals("")){ + b1.setLabel(label); + b4.setLabel(""); + } + if(b7.getLabel().equals("")){ + b7.setLabel(label); + b4.setLabel(""); + } + if(b5.getLabel().equals("")){ + b5.setLabel(label); + b4.setLabel(""); + } + } + if(e.getSource()==b5){ + String label=b5.getLabel(); + if(b2.getLabel().equals("")){ + b2.setLabel(label); + b5.setLabel(""); + } + if(b6.getLabel().equals("")){ + b6.setLabel(label); + b5.setLabel(""); + } + if(b4.getLabel().equals("")){ + b4.setLabel(label); + b5.setLabel(""); + } + if(b8.getLabel().equals("")){ + b8.setLabel(label); + b5.setLabel(""); + } + } + if(e.getSource()==b6){ + String label=b6.getLabel(); + if(b9.getLabel().equals("")){ + b9.setLabel(label); + b6.setLabel(""); + } + if(b3.getLabel().equals("")){ + b3.setLabel(label); + b6.setLabel(""); + } + if(b5.getLabel().equals("")){ + b5.setLabel(label); + b6.setLabel(""); + } + } + if(e.getSource()==b7){ + String label=b7.getLabel(); + if(b4.getLabel().equals("")){ + b4.setLabel(label); + b7.setLabel(""); + } + if(b8.getLabel().equals("")){ + b8.setLabel(label); + b7.setLabel(""); + } + } + if(e.getSource()==b8){ + String label=b8.getLabel(); + if(b9.getLabel().equals("")){ + b9.setLabel(label); + b8.setLabel(""); + } + if(b7.getLabel().equals("")){ + b7.setLabel(label); + b8.setLabel(""); + } + if(b5.getLabel().equals("")){ + b5.setLabel(label); + b8.setLabel(""); + } + } + if(e.getSource()==b9){ + String label=b9.getLabel(); + if(b6.getLabel().equals("")){ + b6.setLabel(label); + b9.setLabel(""); + } + if(b8.getLabel().equals("")){ + b8.setLabel(label); + b9.setLabel(""); + } + } + + //congrats code + if(b1.getLabel().equals("1")&&b2.getLabel().equals("2")&&b3.getLabel() + .equals("3")&&b4.getLabel().equals("4")&&b5.getLabel().equals("5") + &&b6.getLabel().equals("6")&&b7.getLabel().equals("7")&&b8.getLabel() + .equals("8")&&b9.getLabel().equals("")){ + JOptionPane.showMessageDialog(this,"Congratulations! You won."); + } +} +public static void main(String[] args) { + new Puzzle(); +} +} diff --git a/radix_Sort.java b/radix_Sort.java new file mode 100644 index 0000000..8c1316f --- /dev/null +++ b/radix_Sort.java @@ -0,0 +1,70 @@ + +import java.io.*; +import java.util.*; + +class Radix { + + + static int getMax(int arr[], int n) + { + int mx = arr[0]; + for (int i = 1; i < n; i++) + if (arr[i] > mx) + mx = arr[i]; + return mx; + } + + static void countSort(int arr[], int n, int exp) + { + int output[] = new int[n]; // output array + int i; + int count[] = new int[10]; + Arrays.fill(count, 0); + + // Store count of occurrences in count[] + for (i = 0; i < n; i++) + count[(arr[i] / exp) % 10]++; + + + for (i = 1; i < 10; i++) + count[i] += count[i - 1]; + + // Build the output array + for (i = n - 1; i >= 0; i--) { + output[count[(arr[i] / exp) % 10] - 1] = arr[i]; + count[(arr[i] / exp) % 10]--; + } + + + for (i = 0; i < n; i++) + arr[i] = output[i]; + } + + static void radixsort(int arr[], int n) + { + // Find the maximum number to know number of digits + int m = getMax(arr, n); + + + for (int exp = 1; m / exp > 0; exp *= 10) + countSort(arr, n, exp); + } + + // A utility function to print an array + static void print(int arr[], int n) + { + for (int i = 0; i < n; i++) + System.out.print(arr[i] + " "); + } + + // Main driver method + public static void main(String[] args) + { + int arr[] = { 170, 45, 75, 90, 802, 24, 2, 66 }; + int n = arr.length; + + // Function Call + radixsort(arr, n); + print(arr, n); + } +} diff --git a/reverseString.java b/reverseString.java new file mode 100644 index 0000000..44d8752 --- /dev/null +++ b/reverseString.java @@ -0,0 +1,10 @@ +class Solution { + public void reverseString(char[] s) { + char temp; + for(int i=0;i None: + """ + Do not return anything, modify s in-place instead. + """ + for i in range(len(s)//2): + s[i], s[len(s)-1-i] = s[len(s)-1-i], s[i] + diff --git a/reversing arry.java b/reversing arry.java new file mode 100644 index 0000000..e95e4d1 --- /dev/null +++ b/reversing arry.java @@ -0,0 +1,28 @@ +// Basic Java program that reverses an array + +public class reverseArray { + + // function that reverses array and stores it + // in another array + static void reverse(int a[], int n) + { + int[] b = new int[n]; + int j = n; + for (int i = 0; i < n; i++) { + b[j - 1] = a[i]; + j = j - 1; + } + + // printing the reversed array + System.out.println("Reversed array is: \n"); + for (int k = 0; k < n; k++) { + System.out.println(b[k]); + } + } + + public static void main(String[] args) + { + int [] arr = {10, 20, 30, 40, 50}; + reverse(arr, arr.length); + } +} diff --git a/shuffling.java b/shuffling.java new file mode 100644 index 0000000..e05e4cb --- /dev/null +++ b/shuffling.java @@ -0,0 +1,21 @@ +import java.util.ArrayList; +import java.util.Collections; + +class Main { + public static void main(String[] args) { + + // Creating an array list + ArrayList numbers = new ArrayList<>(); + + // Add elements + numbers.add(1); + numbers.add(2); + numbers.add(3); + System.out.println("Sorted ArrayList: " + numbers); + + // Using the shuffle() method + Collections.shuffle(numbers); + System.out.println("ArrayList using shuffle: " + numbers); + + } +} diff --git a/snake.java b/snake.java new file mode 100644 index 0000000..f7dfd8f --- /dev/null +++ b/snake.java @@ -0,0 +1,33 @@ +package com.zetcode; + +import java.awt.EventQueue; +import javax.swing.JFrame; + +public class Snake extends JFrame { + + public Snake() { + + initUI(); + } + + private void initUI() { + + add(new Board()); + + setResizable(false); + pack(); + + setTitle("Snake"); + setLocationRelativeTo(null); + setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + } + + + public static void main(String[] args) { + + EventQueue.invokeLater(() -> { + JFrame ex = new Snake(); + ex.setVisible(true); + }); + } +} \ No newline at end of file diff --git a/sortingUsingsort.java b/sortingUsingsort.java new file mode 100644 index 0000000..0bfebd0 --- /dev/null +++ b/sortingUsingsort.java @@ -0,0 +1,21 @@ +import java.util.ArrayList; +import java.util.Collections; + +class Main { + public static void main(String[] args) { + + // Creating an array list + ArrayList numbers = new ArrayList<>(); + + // Add elements + numbers.add(4); + numbers.add(2); + numbers.add(3); + System.out.println("Unsorted ArrayList: " + numbers); + + // Using the sort() method + Collections.sort(numbers); + System.out.println("Sorted ArrayList: " + numbers); + + } +} diff --git a/stringpalindrome.java b/stringpalindrome.java new file mode 100644 index 0000000..e756f96 --- /dev/null +++ b/stringpalindrome.java @@ -0,0 +1,71 @@ +/*package whatever //do not write package name here */ + + + +import java.io.*; + + + +class GFG { + + public static boolean isPalindrome(String str) + + { + + // Initializing an empty string to store the reverse + + // of the original str + + String rev = ""; + + + + // Initializing a new boolean variable for the + + // answer + + boolean ans = false; + + + + for (int i = str.length() - 1; i >= 0; i--) { + + rev = rev + str.charAt(i); + + } + + + + // Checking if both the strings are equal + + if (str.equals(rev)) { + + ans = true; + + } + + return ans; + + } + + public static void main(String[] args) + + { + + // Input string + + String str = "geeks"; + + + + // Convert the string to lowercase + + str = str.toLowerCase(); + + boolean A = isPalindrome(str); + + System.out.println(A); + + } + +} diff --git a/subscribe.java b/subscribe.java new file mode 100644 index 0000000..8484c95 --- /dev/null +++ b/subscribe.java @@ -0,0 +1,204 @@ +// import java.util.Scanner; +// public class subscribe{ +// public static void main(String[] args){ + +// int age; +// System.out.println("Enter your age"); +// Scanner sc =new Scanner(System.in); +// age = sc.nextInt(); +// // if(age>56){ +// // System.out.println("you are experienced"); +// // } +// // else if(age>46){ +// // System.out.println("You are semi experienced"); +// // } +// // else{ +// // System.out.println("you are not experienced"); +// // } +// switch(age){ +// case 18: +// System.out.println("you are going to be an adult"); +// break; +// case 23: +// System.out.println("you are going to be young"); +// break; +// case 60: +// System.out.println("you are going to be old"); +// break; +// default: +// System.out.println("enjoy life"); +// break; +// } +// } +// } +// import java.util.Scanner; +// public class subscribe{ +// public static void main(String[] args){ +// int x=2; +// int y; +// System.out.println("Enter value of y:"); +// Scanner sc = new Scanner(System.in); +// y = sc.nextInt(); +// switch(y){ +// case 0 : +// System.out.println('1'); +// break; +// case 1 : +// System.out.println(x); +// break; +// case 2 : +// System.out.println( x * x); +// break; +// case 3 : +// System.out.println( x * x * x ); +// break; +// case 4 : +// System.out.println( x * x * x * x); +// break; +// default : +// System.out.println("No match exists."); +// } +// } +// } +// import java.util.Scanner; +// public class subscribe{ +// char LetterGrade; +// public static void main(String[] args){ +// System.out.println("Enter lettergrade"); +// Scanner sc = new Scanner(System.in); +// char LetterGrade = sc.next().charAt(0); +// switch (LetterGrade) { +// case 'a' : +// case 'A' : System.out.print( "Excellent"); +// break; +// case 'b' : +// case 'B' : System.out.print("Superior"); +// break; +// case 'C' : +// case 'c' : System.out.print("Average"); +// break; case 'd' : +// case 'D' : System.out.print(" Poor"); +// break; +// case 'f' : +// case 'F' : System.out.print( " Try again"); +// break; +// default : System.out.print("This is not a recognized letter grade."); +// } +// } +// } +// import java.util.Scanner; +// public class subscribe{ +// public static void main(String[] args){ +// char What; +// System.out.println("Enter lettergrade"); +// Scanner sc = new Scanner(System.in); +// What = sc.next().charAt(0); +// switch (What) { +// case 'c' : +// case 'C' : System.out.print(" Bobo "); +// case 'y' : +// case 'P' : System.out.print(" Is a Dog "); +// break; +// case 'x' : +// case 'X' : System.out.print(" Try But "); +// case 'z' : +// case 'Z' : System.out.print(" Cannot"); +// default : System.out.print(" Help You."); +// } +// } +// } +// import java.util.Scanner; +// public class subscribe{ +// public static void main(String[] args){ +// int Year; +// System.out.println("Enter your age"); +// Scanner sc =new Scanner(System.in); +// Year = sc.nextInt(); +// // if (Year == 1) +// // System.out.print(" Freshman "); else if (Year == 2) +// // System.out.print(" Sophomore "); +// // else if (Year == 3) +// // System.out.print(" Junior "); +// // else if (Year == 4) +// // System.out.print(" Senior "); +// // else +// // System.out.print(" Graduate "); +// switch(Year){ +// case 1: +// System.out.println("Freshman"); +// break; +// case 2: +// System.out.println("Sophomore"); +// break; +// case 3: +// System.out.println("Junior"); +// break; +// case 4: +// System.out.println("Senior"); +// break; +// default: +// System.out.println("Graduate"); +// } +// } +// } +// import java.util.Scanner; +// public class subscribe{ +// static void gp(int a,int r,int n){ +// int current_term; +// for(int i=0;i