-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrecursion2.java
More file actions
103 lines (97 loc) · 2.76 KB
/
recursion2.java
File metadata and controls
103 lines (97 loc) · 2.76 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
import java.util.*;
public class recursion2 {
public static void towerOfHanoi(int n, String src, String helper, String dest){
if (n==1){
System.out.println("transfer disk "+ n +"from "+ src +"to "+dest);
return;
}
towerOfHanoi(n-1,src,dest,helper);
System.out.println("transfer disk "+ n+"from "+src+"to "+dest);
towerOfHanoi(n-1, helper, src, dest);
}
public static void reverseString(int idx, String str){
if(idx==0){
System.out.println(str.charAt(idx));
return;
}
System.out.print(str.charAt(idx));
reverseString(idx-1, str);
}
public static int f=-1,l=-1;
public static void faloccur(String str, int idx,char element){
if (idx==str.length()){
System.out.println(f);
System.out.println(l);
return;
}
char current=str.charAt(idx);
if (current==element){
if(f==-1){
f=idx;
}else{
l=idx;
}
}
faloccur(str, idx+1, element);
}
//check if array is sorted
public static boolean isSorted(int arr[], int idx){
if(idx==arr.length-1){
return true;
}
if(arr[idx]<arr[idx+1]){
//array is sorted till now
return isSorted(arr, idx+1);
}else{
return false;
}
}
public static void moveAllX(String str1,int idx,int count,String newString){
if (idx==str1.length()){
for (int i=0;i<count;i++){
newString+='x';
}
System.out.println(newString);
return;
}
char current=str1.charAt(idx);
if(current=='x'){
count++;
moveAllX(str1, idx+1, count, newString);
}else{
newString+=current;
moveAllX(str1, idx+1, count, newString);
}
}
//remove duplicates from the string
public static boolean map[]=new boolean[26];
public static void removeDup(String str2,int idx, String newString1){
if (idx==str2.length()){
System.out.println(newString1);
return;
}
char current=str2.charAt(idx);
if (map[current-'a']){
removeDup(str2, idx+1, newString1);
}else{
newString1+=current;
map[current-'a']=true;
removeDup(str2, idx+1, newString1);
}
}
public static void main(String args[]){
Scanner sc =new Scanner(System.in);
int n=sc.nextInt();
towerOfHanoi(n, "S", "H", "D");
String str="abaacdaefaah";
int idx=str.length()-1;
reverseString(idx, str);
faloccur(str, 0, 'a');
int arr[]={1,2,3,4,5};
System.out.println(isSorted(arr, 0));
String str1="axbcxxd";
moveAllX(str1, 0, 0, "");
String str2="aabcadb";
removeDup(str2, 0, "");
}
}