Last active
April 14, 2018 06:36
-
-
Save Vivek-abstract/14da49de4cc29806f9dc0bfa5eb678ca to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.*; | |
public class CODeadCodeElimination { | |
public static void main(String[] args) { | |
Scanner sc = new Scanner(System.in); | |
System.out.println("Enter the number of expressions:"); | |
int n = sc.nextInt(); | |
sc.nextLine(); | |
System.out.println("Enter the expression: "); | |
String prog[] = new String[100]; | |
for(int i = 0; i < n; i++) { | |
prog[i] = sc.nextLine(); | |
} | |
sc.close(); | |
int k = 0, l = 0; | |
String newProg[] = new String[100]; | |
String variables[] = new String[100]; | |
for(int i = 0; i < n; i++) { | |
if(prog[i].contains("=")) { | |
String tokens[] = prog[i].split("="); | |
String variable = tokens[0].trim(); | |
boolean isUsed = false; | |
//Check if variable is used in the rest of the program | |
for(int j = i+1; j < n; j++) { | |
if(prog[j].contains(variable)) { | |
variables[l++] = tokens[0].trim(); | |
} | |
} | |
if(Arrays.asList(variables).contains(variable)) { | |
//Variable was used earlier | |
isUsed = true; | |
} | |
if(isUsed) { | |
//Only add the variables that are used later | |
newProg[k++] = prog[i]; | |
} | |
} | |
} | |
System.out.println("\nAfter performing Dead Code Elimination:"); | |
for(int i = 0; i < k; i++) { | |
System.out.println(newProg[i]); | |
} | |
} | |
} | |
/* | |
OUTPUT: | |
Enter the number of expressions: | |
4 | |
Enter the expression: | |
a=2; | |
b=3; | |
c=4; | |
a=a+2; | |
After performing Dead Code Elimination: | |
a=2; | |
a=a+2; | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment