Skip to content

Instantly share code, notes, and snippets.

@benallamar
Last active February 10, 2018 20:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benallamar/2aa33e6303c3e0fdc23feeb0c83ff1b4 to your computer and use it in GitHub Desktop.
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
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