-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJava_Programs
More file actions
1959 lines (1478 loc) · 48.3 KB
/
Java_Programs
File metadata and controls
1959 lines (1478 loc) · 48.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
*******************************************************************************************************************************************************************
https://www.geeksforgeeks.org/competitive-programming-a-complete-guide/?ref=shm&fireglass_rsn=true
https://www.geeksforgeeks.org/must-do-coding-questions-for-companies-like-amazon-microsoft-adobe/?ref=shm&fireglass_rsn=true
https://www.geeksforgeeks.org/puzzles/?ref=shm&fireglass_rsn=true
https://www.geeksforgeeks.org/data-structures/
*******************************************************************************************************************************************************************
Swap two numbers with third variable
class Swap{
public static void main(String args[]){
int a = 10;
int b = 20;
System.out.println("Numbers before swapping are "+ a+" and "+b);
int temp = 0;
temp = a;
a = b;
b = temp;
System.out.println("Numbers after swapping are "+ a+" and "+b);
}
}
*******************************************************************************************************************************************************************
Swap two numbers without third variable.
class SwapWithoutThirdVariable{
public static void main(String args[]){
int a = 10;
int b = 20;
System.out.println("Numbers without swapping: "+ a +" and "+ b);
a = a + b;//10 + 20 = 30
b = a - b;//30 - 20 = 10
a = a - b;//30 - 10
System.out.println("Numbers after swapping: "+ a +" and "+ b);
}
}
*******************************************************************************************************************************************************************
Find duplicate characters in a String and count Program
import java.util.HashMap;
import java.util.Map;
public class CountCharacterInString {
public static void main(String[] args) {
String s = "MADAM";
int counter = 1;
Map<Character, Integer> map = new HashMap<>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (map.containsKey(c)) {
map.put(c, map.get(c) + 1);
} else {
map.put(c, counter);
}
}
System.out.println(map);
}
}
{A=2, D=1, M=2}
*******************************************************************************************************************************************************************
Java Program to find common elements between two arrays
import java.util.HashSet;
import java.util.Set;
public class CommonElementsInTwoArrays {
public static void main(String[] args) {
int arr1[] = { 10, 34, 45, 89, 61 };
int arr2[] = { 10, 78, 99, 34, 55 };
Set<Integer> common = new HashSet<>();
for (int i = 0; i < arr1.length; i++) {
for (int j = 0; j < arr2.length; j++) {
if (arr1[i] == arr2[j]) {
common.add(arr1[i]);
}
}
}
System.out.println(common);
}
}
[34, 10]
*******************************************************************************************************************************************************************
java program to find top two maximum numbers in a array
public class MaximumTwoNumbersInArray {
public static void main(String[] args) {
int arr[] = { 10, 34, 45, 89, 61, 3 };
int firstMax = arr[0];
int secondMax = 0;
for (int i = 0; i < arr.length; i++) {
if (firstMax < arr[i]) {
secondMax = firstMax;
firstMax = arr[i];
} else if (secondMax < arr[i]) {
secondMax = arr[i];
}
}
System.out.println(firstMax);
System.out.println(secondMax);
}
}
89
61
*******************************************************************************************************************************************************************
Reverse a string without using string functions
public class ReverseStringWithoutStringMethod {
public static void main(String[] args) {
String s = "Vikas";
char c[] = s.toCharArray();
StringBuilder sb = new StringBuilder();
for (int i = c.length - 1; i >= 0; i--) {
sb.append(c[i]);
}
System.out.println(sb);
}
}
sakiV
*******************************************************************************************************************************************************************
Java Fizzbuzz program
public class Fizzbuzz {
public static void main(String[] args) {
for (int i = 1; i <= 100; i++) {
if (i % 3 == 0) {
System.out.println("Fizz");
} else if (i % 5 == 0) {
System.out.println("Buzz");
} else if (i % 15 == 0) {
System.out.println("FizzBuzz");
} else {
System.out.println(String.valueOf(i));
}
}
}
}
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
Fizz
16
17
Fizz
19
Buzz
Fizz
22
23
Fizz
Buzz
26
Fizz
28
29
Fizz
31
32
Fizz
34
Buzz
Fizz
37
38
Fizz
Buzz
41
Fizz
43
44
Fizz
46
47
Fizz
49
Buzz
Fizz
52
53
Fizz
Buzz
56
Fizz
58
59
Fizz
61
62
Fizz
64
Buzz
Fizz
67
68
Fizz
Buzz
71
Fizz
73
74
Fizz
76
77
Fizz
79
Buzz
Fizz
82
83
Fizz
Buzz
86
Fizz
88
89
Fizz
91
92
Fizz
94
Buzz
Fizz
97
98
Fizz
Buzz
*******************************************************************************************************************************************************************
Java program to find maximum repeated character from a file
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class MaximumRepeatedCharacterInFile {
private static final String FILE_NAME = "C:\\Users\\krishnaggandu\\Desktop\\myText.txt";
public static void main(String[] args) {
try {
FileReader fr = new FileReader(FILE_NAME);
int ch;
Map<Character, Integer> map = new HashMap<Character, Integer>();
while ((ch = fr.read()) != -1) {
if (map.containsKey((char) ch)) {
map.put((char) ch, map.get((char) ch) + 1);
} else { map.put((char) ch, 1);
}
}
fr.close();
System.out.println(map);
}
catch (IOException e) {
e.printStackTrace();
}
}
}
*******************************************************************************************************************************************************************
Remove specific char from String
public class Logics {
public static void main(String[] args) {
String s = "Vikash";
s = s.replace("h", "");
System.out.println(s);
}
}
*******************************************************************************************************************************************************************
java program for singleton design pattern
public class Singleton {
private static Singleton instance = null;
private Singleton() {
// Don't remove
}
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) { //if we want thread safe.
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
public class Test {
public static void main(String[] args) {
Singleton singleton1 = Singleton.getInstance();
Singleton singleton2 = Singleton.getInstance();
if (singleton1 == singleton2) {
System.out.println("Singleton");
}
}
}
*******************************************************************************************************************************************************************
Java Program to check prime number
import java.util.Scanner;
class Prime{
public static void main(String args[]){
System.out.println("Enter number to check prime number");
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
int counter = 0;
for(int i = 2; i < num; i++){
if(num % i == 0){
counter++;
}
}
if(counter == 0){
System.out.println(num+" is prime number");
}else{
System.out.println(num+" is not prime number");
}
}
}
*******************************************************************************************************************************************************************
java program to print factorial of a number
class Factorial{
public static void main(String args[]){
int num = 5;
int f = 1;
for(int i = 1; i <= num; i++){
f = f * i;
}
System.out.println(f);
}
}
*******************************************************************************************************************************************************************
java program to find maximum number in an array
class Maximum{
public static void main(String args[]){
int arr[] = new int[]{12, 34, 3 , 78, 6,890};
int max = arr[0];
for(int i : arr){
if(i > max){
max = i;
}
}
System.out.println("Maximum value is: "+max);
}
}
*******************************************************************************************************************************************************************
java program to count the number of digits in an integer
class Count{
public static void main(String args[]){
int num = 12345;
int counter = 0;
while(num != 0){
counter++;
num /= 10;
}
System.out.println(counter);
}
}
*******************************************************************************************************************************************************************
java program to reverse a number
class Reverse {
public static void main(String args[]){
int num = 12345;
int copy = num;
int reverseNumber = 0;
int mod = 0;
while(copy != 0){
mod = copy % 10;
reverseNumber = reverseNumber * 10 + mod;
copy = copy /10;
}
System.out.println("Original Number: "+num);
System.out.println("Reversed Number: "+reverseNumber);
}
}
Output:
Original Number: 12345
Reversed Number: 54321
*******************************************************************************************************************************************************************
java program to check palindrome number
class Palindrome {
public static void main(String args[]){
int num = 121;
int copy = num;
int reverseNumber = 0;
int mod = 0;
while(copy != 0){
mod = copy % 10;
reverseNumber = reverseNumber * 10 + mod;
copy = copy /10;
}
if(num == reverseNumber){
System.out.println("Palindrome");
}else{
System.out.println("Not Palindrome");
}
}
}
*******************************************************************************************************************************************************************
Java Program to print fibonacci series
class Fibonacci {
public static void main(String args[]){
int p = 1;
int c= 1;
int n = p + c;
System.out.print(p +" "+c);
while(n < 50){
c = p ;
p = n;
n = p + c;
System.out.print(" "+n);
}
}
}
*******************************************************************************************************************************************************************
java program to find minimum number in an array
class Minimum{
public static void main(String args[]){
int arr[] = new int[]{12, 34, 3 , 78, 6,890};
int min = arr[0];
for(int i : arr){
if(i < min){
min = i;
}
}
System.out.println("Minimum value is: "+ min);
}
}
*******************************************************************************************************************************************************************
java code to sort an array in ascending order
class AsendingOrder{
public static void main(String args[]){
int arr[] = new int[]{12,34,5,89,76,1};
int temp = 0;
for(int i = 0; i<=arr.length-1;i++ ){
for(int j =i; j<arr.length; j++){
if(arr[i] > arr[j]){
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
for(int i= 0 ;i<arr.length; i++){
System.out.print(" "+arr[i]);
}
}
}
*******************************************************************************************************************************************************************
Java Program to find sum of digits
class SumOfDigit{
public static void main(String args[]){
int number = 12345;
int sum = 0;
int modulus = 0;
while(number != 0){
modulus = number % 10;
sum = sum + modulus;
number = number / 10;
}
System.out.println(sum);
}
}
*******************************************************************************************************************************************************************
sum of factorial series program in java
import java.util.Scanner;
class SumOfFactorials{
public static void main(String args[]){
System.out.println("Enter Number");
Scanner sc = new Scanner(System.in);
int number = sc.nextInt();
int f = 1;
int sum = 0;
for(int i = 4; i >= 1; i--){
for(int j = i; j >= 1; j--){
f = f * j;
}
sum = sum + f;
f = 1;
}
System.out.println(sum);
}
}
another way
public static void main(String args[]){
System.out.println("Enter Number");
Scanner sc = new Scanner(System.in);
int number = sc.nextInt();
System.out.println(factRecursion(number));
}
static int factRecursion(int a) {
if(a==0)
return 1;
return a*factRecursion(a-1);
}
*******************************************************************************************************************************************************************
compress-a-string-aaabbccccd-to-a3b2c4d
public class Poly {
public static void main(String[] args) {
String a="aaaaaaaabbbbbbcccccccccccccd";
char first=a.charAt(0);
int recur=0;
StringBuilder res=new StringBuilder();
for (int i = 1; i <a.length(); i++) {
if(first==a.charAt(i)){
recur++;
}
else{
if (recur>0)
res.append(first).append(recur);
recur=0;
first=a.charAt(i);
}
}
if (recur>0)
res.append(first).append(recur);
else
res.append(first);
System.out.println(res);
}
}
compress-a-string-aababbccdccd-to-a3b3c4d2 ?
String str="axbcxbadxr";
char[] chArray = str.toCharArray();
int[] countArray=new int[255];
for(int i=0;i<chArray.length;i++) {
int in=chArray[i];
countArray[in]=countArray[in]+1;
}
StringBuffer sb = new StringBuffer();
for(int i=0;i<countArray.length-1;i++) {
if(countArray[i]!=0) {
System.out.println((char)i+":"+countArray[i]);
sb.append((char)i);
sb.append(countArray[i]);
}
}
System.out.println(sb.toString());
output : a2b2c1d1r1x3
*******************************************************************************************************************************************************************
Features
Java 4
1) Assertion (Java 4) - it is used for testing
Java 5
1) For-each loop (Java 5)
2) Varargs (Java 5)
3) Static Import (Java 5)
4) Autoboxing and Unboxing (Java 5)
5) Enum (Java 5)
6) Covariant Return Type (Java 5)
7) Annotation (Java 5)
8) Generics (Java 5)
Java 6
1) Instrumentation (premain method) (Java 6)
Java 7
1) String in switch statement (Java 7)
2) Binary Literals (Java 7)
3) The try-with-resources (Java 7)
4) Caching Multiple Exceptions by single catch (Java 7)
5) Underscores in Numeric Literals (Java 7)
****************************************************************************************************************************
Java 8
https://www.javatpoint.com/java-8-features
Java 8 Date/Time API (Java 8)
Lambda Expressions (Java 8) -> Lambda expression helps us to write our code in functional style. It is very useful in collection library in which it helps to iterate, filter and extract data.
to bring functional interface in java
Method References (Java 8) ->Method reference is used to refer method of functional interface . It is compact and easy form of lambda expression. Each time when you are using lambda expression to just referring a method,
you can replace your lambda expression with method reference.
Functional Interfaces (Java 8) --> An Interface that contains only one abstract method is known as functional interface. It can have any number of default and static methods. It can also declare methods of object class.
Stream API (Java 8) -->Java introduced a new class Optional in Java 8. It is a public final class which is used to deal with NullPointerException in Java application. We must import java.util package to use this class.
It provides methods to check the presence of value for particular variable.
Base64 Encode Decode (Java 8)
Default Methods (Java 8)
forEach() method(Java 8)
Collectors(Java 8)
StringJoiner(Java 8)
Optional class (Java 8)
Nashorn JavaScript (Java 8)
Parallel Array Sorting (Java 8)
Type Inference (Java 8)
Method Parameter Reflection (Java 8)
Type annotations and repeating annotations (Java 8)
Java JDBC Improvements/Enhancements (Java 8)
Java IO Improvement/Enhancements (Java 8)
Java Concurrency Improvement/Enhancements (Java 8)
Java 9
private methods are allowd in interface
Java 9 – Private Methods in Interface
Java 9 Immutable Collections with Factory Methods
java 9 try with resources
*******************************************************************************************************************************************************************
FunctionalInterface
Lambda Expression
Predefined functional interfaces
********************************************************************************************************************************************************************
Find next greater number with same set of digits
https://www.geeksforgeeks.org/find-next-greater-number-set-digits/
Input: n = "218765"
Output: "251678"
Input: n = "1234"
Output: "1243"
Input: n = "4321"
Output: "Not Possible"
Input: n = "534976"
Output: "536479"
I) Traverse the given number from rightmost digit, keep traversing till you find a digit which is smaller than the previously traversed digit. For example, if the input number is “534976”, we stop at 4 because 4 is smaller than next digit 9. If we do not find such a digit, then output is “Not Possible”.
II) Now search the right side of above found digit ‘d’ for the smallest digit greater than ‘d’. For “534976″, the right side of 4 contains “976”. The smallest digit greater than 4 is 6.
III) Swap the above found two digits, we get 536974 in above example.
IV) Now sort all digits from position next to ‘d’ to the end of number. The number that we get after sorting is the output. For above example, we sort digits in bold 536974. We get “536479” which is the next greater number for input 534976.
// Java program to find next greater
// number with same set of digits.
import java.util.Arrays;
public class nextGreater
{
// Utility function to swap two digit
static void swap(char ar[], int i, int j)
{
char temp = ar[i];
ar[i] = ar[j];
ar[j] = temp;
}
// Given a number as a char array number[],
// this function finds the next greater number.
// It modifies the same array to store the result
static void findNext(char ar[], int n)
{
int i;
// I) Start from the right most digit
// and find the first digit that is smaller
// than the digit next to it.
for (i = n - 1; i > 0; i--)
{
if (ar[i] > ar[i - 1]) {
break;
}
}
// If no such digit is found, then all
// digits are in descending order means
// there cannot be a greater number with
// same set of digits
if (i == 0)
{
System.out.println("Not possible");
}
else
{
int x = ar[i - 1], min = i;
// II) Find the smallest digit on right
// side of (i-1)'th digit that is greater
// than number[i-1]
for (int j = i + 1; j < n; j++)
{
if (ar[j] > x && ar[j] < ar[min])
{
min = j;
}
}
// III) Swap the above found smallest
// digit with number[i-1]
swap(ar, i - 1, min);
// IV) Sort the digits after (i-1)
// in ascending order
Arrays.sort(ar, i, n);
System.out.print("Next number with same" +
" set of digits is ");
for (i = 0; i < n; i++)
System.out.print(ar[i]);
}
}
public static void main(String[] args)
{
char digits[] = { '5','3','4','9','7','6' };
int n = digits.length;
findNext(digits, n);
}
}
******************************************************************************************************************************************************************
generation of Password
// Java code to explain how to generate random
// password
// Here we are using random() method of util
// class in Java
import java.util.*;
public class NewClass
{
public static void main(String[] args)
{
// Length of your password as I have choose
// here to be 8
int length = 10;
System.out.println(geek_Password(length));
}
// This our Password generating method
// We have use static here, so that we not to
// make any object for it
static char[] geek_Password(int len)
{
System.out.println("Generating password using random() : ");
System.out.print("Your new password is : ");
// A strong password has Cap_chars, Lower_chars,
// numeric value and symbols. So we are using all of
// them to generate our password
String Capital_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String Small_chars = "abcdefghijklmnopqrstuvwxyz";
String numbers = "0123456789";
String symbols = "!@#$%^&*_=+-/.?<>)";
String values = Capital_chars + Small_chars +
numbers + symbols;
// Using random method
Random rndm_method = new Random();
char[] password = new char[len];
for (int i = 0; i < len; i++)
{
// Use of charAt() method : to get character value
// Use of nextInt() as it is scanning the value as int
password[i] =
values.charAt(rndm_method.nextInt(values.length()));
}
return password;
}
}
Generating password using random() :
Your new password is : KHeCZBTM;-
// Java code to explain how to generate random
// password
class uniquePassword
{
public static long Code() //this code returns the unique 16 digit code
{ //creating a 16 digit code using Math.random function
long code =(long)((Math.random()*9*Math.pow(10,15))+Math.pow(10,15));
return code; //returning the code
}
//method to generate the password
//by converting every two digits as an ascii value of a character
public static void main(String args[])
{
long code=Code();//function calling
String unique_password="";
for (long i=code;i!=0;i/=100)//a loop extracting 2 digits from the code
{
long digit=i%100;//extracting two digits
if (digit<=90)
digit=digit+32;
//converting those two digits(ascii value) to its character value
char ch=(char) digit;
// adding 32 so that our least value be a valid character
unique_password=ch+unique_password;//adding the character to the string
}
System.out.println("unique password ="+unique_password);
}
}
// Here we are using random() method of util
// class in Java
Generating password using Math.random() and ascii code:
Your new password is : KHe%ZBT$
******************************************************************************************************************************************************************
generation of OTP(One Time Password)
// Java code to explain how to generate OTP
// Here we are using random() method of util
// class in Java
import java.util.*;
public class NewClass
{
static char[] OTP(int len)
{
System.out.println("Generating OTP using random() : ");
System.out.print("You OTP is : ");
// Using numeric values
String numbers = "0123456789";
// Using random method
Random rndm_method = new Random();
char[] otp = new char[len];
for (int i = 0; i < len; i++)
{
// Use of charAt() method : to get character value
// Use of nextInt() as it is scanning the value as int
otp[i] =
numbers.charAt(rndm_method.nextInt(numbers.length()));
}
return otp;
}
public static void main(String[] args)
{
int length = 4;
System.out.println(OTP(length));
}
}
Generating OTP using random() :
You OTP is : 5291
// Java code to explain how to generate OTP
public class GenerateOTP {
//declaring a of return type String
//which on calling provides the otp
public static String generateOTP()
{ //int randomPin declared to store the otp
//since we using Math.random() hence we have to type cast it int
//because Math.random() returns decimal value
int randomPin =(int) (Math.random()*9000)+1000;
String otp = String.valueOf(randomPin);
return otp; //returning value of otp
}
public static void main(String args[])//method to call and print otp
{
String otpSting =generateOTP();//function calling
System.out.println("OTP : "+otpSting);
}
}// Here we are using Math.random() function.
// class in Java
Generating OTP using random() :
You OTP is : 5291
******************************************************************************************************************************************************************
Given a sequence of words, print all anagrams together
Let us understand the steps with following input Sequence of Words:
"cat", "dog", "tac", "god", "act"
1) Create two auxiliary arrays index[] and words[]. Copy all given words to words[] and store the original indexes in index[]
index[]: 0 1 2 3 4
words[]: cat dog tac god act
2) Sort individual words in words[]. Index array doesn’t change.
index[]: 0 1 2 3 4
words[]: act dgo act dgo act
3) Sort the words array. Compare individual words using strcmp() to sort
index: 0 2 4 1 3
words[]: act act act dgo dgo
4) All anagrams come together. But words are changed in words array. To print the original words, take index from the index array and use it in the original array. We get
"cat tac act dog god"
// A Java program to print all anagrams together
import java.util.Arrays;
import java.util.Comparator;
public class GFG {
// class for each word of duplicate array
static class Word {
String str; // to store word itself
int index; // index of the word in the
// original array
// constructor
Word(String str, int index)
{
this.str = str;
this.index = index;
}
}
// class to represent duplicate array.
static class DupArray {
Word[] array; // Array of words
int size; // Size of array
// constructor
public DupArray(String str[], int size)
{
this.size = size;
array = new Word[size];
// One by one copy words from the
// given wordArray to dupArray
int i;
for (i = 0; i < size; ++i) {
// create a word Object with the
// str[i] as str and index as i
array[i] = new Word(str[i], i);
}
}
}
// Compare two words. Used in Arrays.sort() for
// sorting an array of words
static class compStr implements Comparator<Word> {
public int compare(Word a, Word b)
{
return a.str.compareTo(b.str);
}
}
// Given a list of words in wordArr[],
static void printAnagramsTogether(String wordArr[],
int size)
{
// Step 1: Create a copy of all words present
// in given wordArr. The copy will also have
// original indexes of words
DupArray dupArray = new DupArray(wordArr, size);
// Step 2: Iterate through all words in
// dupArray and sort individual words.
int i;
for (i = 0; i < size; ++i) {
char[] char_arr = dupArray.array[i].str.toCharArray();
Arrays.sort(char_arr);
dupArray.array[i].str = new String(char_arr);
}
// Step 3: Now sort the array of words in
// dupArray
Arrays.sort(dupArray.array, new compStr());
// Step 4: Now all words in dupArray are together,
// but these words are changed. Use the index
// member of word struct to get the corresponding
// original word
for (i = 0; i < size; ++i)
System.out.print(wordArr[dupArray.array[i].index] + " ");
}
// Driver program to test above functions
public static void main(String args[])
{
String wordArr[] = { "cat", "dog", "tac", "god", "act" };