Virus Blood Sample Positive / Negative Predication Java Code
Table of Contents
Problem Statement
We will get the virus as a string eg:(corona) and we also get the list of blood samples like (ngdev, cron) and we need to see if the given blood sample is matching with the virus sample and need to return positive/negative.
corona ngdev -> not matching so return negative cron -> its like cxronx (so matching with virus so need to return true)
Solution 1: Java Source Code [ With StartsWith ] :
This program takes first input as virus and then the number of samples it needs to test 2 and then each sample in the new lines.
package com.ngdeveloper.dsa; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class VirusBloodProgram { public static void main(String args[]) throws Exception { // Write code here Scanner scanner = new Scanner(System.in); String virus = scanner.next(); int totalPeople = scanner.nextInt(); List<String> peoples = new ArrayList<>(); for (int i = 0; i < totalPeople; i++) { peoples.add(scanner.next()); } // iterate and pass through peoples.stream().forEach(eachPerson -> { System.out.println(isVirusAffected(virus, eachPerson)); }); } private static String isVirusAffected(String virus, String blood) { char[] virusArray = virus.toCharArray(); for (int i = 0; i < virusArray.length; i++) { if (blood.startsWith(String.valueOf(virusArray[i]))) { blood = blood.replaceFirst(String.valueOf(virusArray[i]), ""); } } if (blood.trim().length() == 0) { return "POSITIVE"; } return "NEGATIVE"; } }
Program Output
Inputs: ======= corona 2 ngdev cron Outputs: ========= NEGATIVE POSITIVE
Solution 2: Java Source Code [ With Recursion ] :
package com.ngdeveloper.dsa; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class VirusBloodProgram { public static void main(String args[]) throws Exception { // Write code here Scanner scanner = new Scanner(System.in); String virus = scanner.next(); int totalPeople = scanner.nextInt(); List<String> peoples = new ArrayList<>(); for (int i = 0; i < totalPeople; i++) { peoples.add(scanner.next()); } // iterate and pass through peoples.stream().forEach(eachPerson -> { System.out.println(isVirusAffected(virus, eachPerson, 0, 0)); }); } private static String isVirusAffected(String virus, String blood, int v, int b) { if (b == blood.length()) { return "POSITIVE"; } if (v == virus.length()) { return "NEGATIVE"; } if (virus.charAt(v) == blood.charAt(b)) { v++; b++; } else { v++; } return isVirusAffected(virus, blood, v, b); } }
corona 2 ngdev cron NEGATIVE POSITIVE