[Question/Problem Statement is the Property of Techgig]
Java Advanced - Lambda Expressions [www.techgig.com]
Write the Following Methods that Return a Lambda Expression Performing a Specified Action: PerformOperation isOdd(): The Lambda Expression must return if a Number is Odd or If it is Even. PerformOperation isPrime(): The lambda expression must return if a number is prime or if it is composite. PerformOperation isPalindrome(): The Lambda Expression must return if a number is a Palindrome or if it is not.
Input Format
Input is as Show in the Format Below (Deduce Unknowns!)
Input
31 32 73 7777
Constraints
NA
NA
Output Format
Output is as Show in the Format Below (Deduce Unknowns!)
Output
ODDPRIMEPALINDROME
______________
[Explanation of the Solution]
This is a Good Question to Refresh Java 8 Lambdas. In my Solution, I Implemented the Functional Interfaces within my main() Method and assigned it to Local Reference Variables.
________________
[Source Code, Sumith Puri (c) 2021 - Free to Use & Distribute]
import java.util.Scanner;
/*
* Techgig Core Java Basics Problem - Knock Off Java Lambdas!
* Author: Sumith Puri [I Bleed Java!] // GitHub: @sumithpuri
*/
interface LambdaYogi {
public boolean opYog(int x);
}
public class CandidateCode {
public static void main(String args[]) throws Exception {
// you may choose to refactor, as this method
// becomes really long and unmanageable #TODO
LambdaYogi isOdd = a -> {
boolean retFlag = false;
if (a % 2 != 0)
retFlag = true;
return retFlag;
};
LambdaYogi isPrime = a -> {
boolean retFlag = true;
for (int i = 2; i < a - 1; i++) {
if (a % i == 0) {
retFlag = false;
break;
}
}
return retFlag;
};
LambdaYogi isPalindrome = a -> {
boolean retFlag = false;
String actStr = String.valueOf(a).trim();
String revStr = new StringBuffer(actStr).reverse().toString();
// using string basis, not mathematical
if (actStr.equals(revStr))
retFlag = true;
return retFlag;
};
Scanner scanner = new Scanner(System.in);
int val = scanner.nextInt();
for (int i = 0; i < val; i++) {
int op = scanner.nextInt();
int no = scanner.nextInt();
switch (op) {
case 1: {
if (isOdd.opYog(no))
System.out.println("ODD");
else
System.out.println("EVEN");
break;
}
case 2: {
if (isPrime.opYog(no))
System.out.println("PRIME");
else
System.out.println("COMPOSITE");
break;
}
case 3: {
if (isPalindrome.opYog(no))
System.out.println("PALINDROME");
else
System.out.println("NONPALIN");
}
}
}
}
}
No comments:
Post a Comment