Last active
February 10, 2018 20:44
-
-
Save benallamar/2aa33e6303c3e0fdc23feeb0c83ff1b4 to your computer and use it in GitHub Desktop.
Get the shortest no sub sequence of a given sequence in a given alphabet
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.Scanner | |
object Boot extends App { | |
implicit def fromStringToCharArray(s: String) = s.toCharArray | |
val alphabet = "ACGT"; | |
val scanner = new Scanner(System.in) | |
val line = scanner.nextLine | |
var fn = "A" * (line.length + 1) // Initialize the string with the most probable string | |
for (c <- alphabet) { | |
val ss = shortestSequence(c, line) // We iterate over the chars to identify from wich one we could | |
if (ss.length < fn.length) // get the shortest no-subsequencial part | |
fn = ss | |
} | |
print(fn) | |
// A Simple/Iterative alogorithm to get the shortest sequence(the first naive one) | |
def shortestSequence(f: Char, string: String): String = { | |
val fchars = line.filter(_ != f) | |
val booleanMapping: Array[Boolean] = line.split(f).filter(!_.isEmpty).map(containsAllChar(_, fchars)) | |
val boolean: Boolean = booleanMapping.reduce((a, b) => a.equals(b)); | |
if (boolean) | |
f.toString * (booleanMapping.length + 1) | |
else { | |
val sb = new StringBuilder | |
val index = booleanMapping.indexOf(false); | |
val seq = line.split(f).filter(!_.isEmpty)(index) | |
val sp = alphabet.filter(i => (i != f) && !seq.contains(i)).charAt(0) | |
booleanMapping.foreach(a => if (a) sb.append(f) else sb.append(sp)) | |
sb.toString | |
} | |
} | |
/** | |
* Check if the given string contains all the characters given in an array of chars | |
*/ | |
def containsAllChar(s: String, c: Array[Char]): Boolean = { | |
for (i <- c) | |
if (!s.contains(i)) | |
return false | |
true | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment