I have 3 different objects that I've written in IDEA, labelled PartA, PartB, and PartC. However, when I attempt to run any of these objects, the only one that gives me the option to run is PartB. When I right click on the code for PartA and PartC, I have no option to run them. Only PartB has the option to run. What's going on here, and how can I fix it so I can run the different objects I have written?
Edit: Sorry, first time posting a question here. Here's the code I have written.
object PartB extends App {
def easter(Y:Int): Int = {
val N = Y - 1900
val A = N - (N/19) * 19
val B = (7 * A + 1) / 19
val C = 11 * A + 4 - B
val M = C - (C / 29) * 29
val Q = N / 4
val S = N + Q + 31 - M
val W = S - (S / 7) * 7
val DATE = 25 - M - W
return DATE
}
println("Enter a year: ")
val year = scala.io.StdIn.readInt()
val date = easter(year)
var easter_day : String = ""
if (date == 0) {
easter_day = "March, 31"
} else if (date < 0) {
easter_day = "March, " + (31 + year)
} else {
easter_day = "April, " + date
}
println("In " + year + ", Easter is on " + easter_day + ".")
}
////////////////////////////////////////////////////////////////////////////////
object PartC {
def ack(m:Int, n:Int) : Int = {
if (m == 0) {
return n + 1
} else if (n == 0) {
return ack(m - 1, 1)
} else {
return ack(m - 1, ack(m, n - 1))
}
}
println("Enter a value for m: ")
val m = scala.io.StdIn.readInt()
println("Enter a value for n: ")
val n = scala.io.StdIn.readInt()
println(ack(m, n))
}
PartB extends App, but PartC doesn't. Presumably PartA doesn't either.
The App trait can be used to quickly turn objects into executable programs... the whole class body becomes the “main method”.
So PartB defines a main method.
Related
I'm trying to find the min distance between multiple words in a given text.
Let's suppose I a string such as: "a b cat dog x y z n m p fox x dog b b cat"
Find the min distance of all matches of substrings: (fox, dog, cat)
there are multiple occurrences of each substring in this text:
one at the beginning:
cat - 4
dog - 8
fox - 24
dist = 24 - 4 = 20
And one at the end of string:
fox - 24
dog - 30
cat - 38
dist = 38 - 24 = 14
the min Dist = 14
This is the algorithm I came up with:
object MinKWindowSum {
def main(args: Array[String]): Unit = {
val document =
"""This Hello World is a huge text with thousands
Java of Hello words and Scala other lines and World and many other Hello docs
Words of World in many langs Hello and features
Java Scala AXVX TXZX ASDQWE OWEQ World asb eere qwerer
asdasd Scala Java Hello docs World KLKM NWQEW ZXCASD OPOOIK Scala ASDSA
"""
println(getMinWindowSize(document, "Hello World Scala"))
}
def getMinWindowSize(str:String, s:String): Int = {
/* creates a list of tuples List[(String, Int)] which contains each keyword and its
respective index found in the text sorted in order by index.
*/
val keywords = s.split(" ").toSet
val idxs = keywords.map(k => (k -> ("(?i)\\Q" + k + "\\E").r.findAllMatchIn(str).map(_.start)))
.map{ case (keyword,itr) => itr.map((keyword, _))}
.flatMap(identity).toSeq
.sortBy(_._2)
// Calculates the min window on the next step.
var min = Int.MaxValue
var minI, minJ = -1
// current window indexes and words
var currIdxs = ListBuffer[Int]()
var currWords = ListBuffer[String]()
for(idx <- idxs ) {
// check if word exists in window already
val idxOfWord = currWords.indexOf(idx._1)
if (!currWords.isEmpty && idxOfWord != -1) {
currWords = currWords.drop(idxOfWord + 1)
currIdxs = currIdxs.drop(idxOfWord + 1)
}
currWords += idx._1
currIdxs += idx._2
// if all keys are present check if it is new min window
if (keywords.size == currWords.length) {
val currMin = Math.abs(currIdxs.last - currIdxs.head)
if (min > currMin) {
min = currMin
minI = currIdxs.head
minJ = currIdxs.last
}
}
}
println("min = " + min + " ,i = " + minI + " j = " + minJ)
min
}
}
In the example above we try to find the min distance between all matches of "Hello World Scala"
The shortest window between the indexes is found between indexes:
i = 235, j = 257 --> min = 22
Was wondering if there is a better way of doing this in an idiomatic way or in a better manner in terms of efficiency, scalability, readability and simplicity?
Here is a slightly "more functional" alternative:
val document =
"""This Hello World is a huge text with thousands Java of Hello words and Scala other lines and World and many other Hello docs
Words of World in many langs Hello and features Java Scala AXVX TXZX ASDQWE OWEQ World
"""
val WORDS = Set("Hello", "World", "Scala")
var minDistance = document.trim
.split(" ")
.foldLeft(List[(String, Int)](), None: Option[Int], 0) {
case ((words, min, idx), word) if WORDS.contains(word) =>
val newWords = (word, idx) :: words.filter(_._1 != word)
if (newWords.map(_._1).toSet == WORDS) { // toSet on only 3 elmts
var idxes = newWords.map(_._2)
var dist = idxes.max - idxes.min
var newMin = min match {
case None => dist
case Some(min) if min < dist => min
case _ => dist
}
(newWords, Some(newMin), idx + word.length + 1)
}
else {
(newWords, min, idx + word.length + 1)
}
case ((words, min, idx), word) =>
(words, min, idx + word.length + 1)
}
._2
println(minDistance)
which produces:
Some(38)
My approach starts with a similar premise but uses a tail-recursive helper method to search the indexed words.
def getMinWindowSize(str :String, s :String) :Int = {
val keywords = s.split("\\s+").toSet
val re = "(?i)\\b(" + keywords.mkString("|") + ")\\b"
val idxs = re.r.findAllMatchIn(str).map(w => w.start -> w.toString).toList
def dist(input :List[(Int, String)], keys :Set[String]) :Option[Int] = input match {
case Nil => None
case (idx, word) :: rest =>
if (keys(word) && keys.size == 1) Some(idx)
else dist(rest, keys diff Set(word))
}
idxs.tails.collect{
case (idx, word)::rest => dist(rest, keywords diff Set(word)).map(_ - idx)
}.flatten.reduceOption(_ min _).getOrElse(-1)
}
No mutable variables or data structures. I also used Option to help return a more meaningful value if no minimum window is possible.
Usage:
getMinWindowSize(document, "Hello World Scala") //res0: Int = 22
getMinWindowSize(document, "Hello World Scal") //res1: Int = -1
I am trying to write a program that can find the roots of a quadratic equation using Scala. The input should be a quadratic equation in the form ax^2+bx+c (e.g: 5x^2+2x+3) as a string.
I managed to code the calculation of the roots but am having trouble extracting the coefficients from the input. Here's the code I wrote for extracting the coefficients so far:
def getCoef(poly: String) = {
var aT: String = ""
var bT: String = ""
var cT: String = ""
var x: Int = 2
for (i <- poly.length - 1 to 0) {
val t: String = poly(i).toString
if (x == 2) {
if (t forall Character.isDigit) aT = aT + t(i)
else if (t == "^") {i = i + 1; x = 1}
}
else if (x == 1) {
if (t forall Character.isDigit) bT = bT + t(i)
else if (t == "+" || t == "-") x = 0
}
else if (x == 0) {
if (t forall Character.isDigit) cT = cT + t(i)
}
val a: Int = aT.toInt
val b: Int = bT.toInt
val c: Int = cT.toInt
(a, b, c)
}
}
Simple solution with regex:
def getCoef(poly: String) = {
val polyPattern = """(\d+)x\^2\+(\d+)x\+(\d+)""".r
val matcher = polyPattern.findFirstMatchIn(poly).get
(matcher.group(1).toInt, matcher.group(2).toInt, matcher.group(3).toInt)
}
Does not handle all cases (e.g.: minus) and just throws an error if the input does not match the pattern, but it should get you going.
Here is some code I wrote to solve project Euler #14 in scala
The output is shown below as well. My issue is, I expect better performance from the cached version, but the opposite is true. I think I did something wrong, since I don't think HashMap's overhead is enough to make this this slow.
Any suggestions?
object Problem14 {
def main(args: Array[String]) {
val collatzCacheMap = collection.mutable.HashMap[Long,Long]()
def collatzLengthWithCache(num: Long): Long = {
def collatzR(currNum: Long, solution: Long): Long = {
val cacheVal = collatzCacheMap.get(currNum)
if(cacheVal != None) {
val answer = solution + cacheVal.get
collatzCacheMap.put(num, answer);
answer;
}
else if(currNum == 1) { collatzCacheMap.put(num, solution + 1); solution + 1; }
else if(currNum % 2 == 0) collatzR(currNum/2, solution + 1)
else collatzR(3*currNum + 1, solution + 1)
}
collatzR(num, 0)
}
def collatzLength(num: Long): Long = {
def collatzR(currNum: Long, solution: Long): Long = {
if(currNum == 1) solution + 1
else if(currNum % 2 == 0) collatzR(currNum/2, solution + 1)
else collatzR(currNum*3 + 1, solution + 1)
}
collatzR(num, 0)
}
var startTime = System.currentTimeMillis()
//val answer = (1L to 1000000).reduceLeft((x,y) => if(collatzLengthWithCache(x) > collatzLengthWithCache(y)) x else y)
val answer = (1L to 1000000).zip((1L to 1000000).map(collatzLengthWithCache)).reduceLeft((x,y) => if(x._2 > y._2) x else y)
println(answer)
println("Cached time: " + (System.currentTimeMillis() - startTime))
collatzCacheMap.clear()
startTime = System.currentTimeMillis()
//val answer2 = (1L to 1000000).par.reduceLeft((x,y) => if(collatzLengthWithCache(x) > collatzLengthWithCache(y)) x else y)
val answer2 = (1L to 1000000).par.zip((1L to 1000000).par.map(collatzLengthWithCache)).reduceLeft((x,y) => if(x._2 > y._2) x else y)
println(answer2)
println("Cached time parallel: " + (System.currentTimeMillis() - startTime))
startTime = System.currentTimeMillis()
//val answer3 = (1L to 1000000).reduceLeft((x,y) => if(collatzLength(x) > collatzLength(y)) x else y)
val answer3 = (1L to 1000000).zip((1L to 1000000).map(collatzLength)).reduceLeft((x,y) => if(x._2 > y._2) x else y)
println(answer3)
println("No Cached time: " + (System.currentTimeMillis() - startTime))
startTime = System.currentTimeMillis()
//val answer4 = (1L to 1000000).par.reduceLeft((x,y) => if(collatzLength(x) > collatzLength(y)) x else y)
val answer4 = (1L to 1000000).par.zip((1L to 1000000).par.map(collatzLength)).reduceLeft((x,y) => if(x._2 > y._2) x else y)
println(answer4)
println("No Cached time parallel: " + (System.currentTimeMillis() - startTime))
}
}
Output:
(837799,525)
Cached time: 1070
(837799,525)
Cached time parallel: 954
(837799,525)
No Cached time: 450
(837799,525)
No Cached time parallel: 241
There has to be a better way to do this.. I'm testing for a ray-triangle intersection and my code looks something like this
if(some condition) fail
else {
...
if(some other condition) fail
else {
...
intersection
}
}
with many nested ifs. It's disgusting. I'm doing this not to use any return statements. Is there an alternate control structure I could use here to manage the various method exit points?
You could use for comprehension:
val result: Option[BasicIntersection] = for {
edge1 <- Some(vertices(1) - vertices(0))
edge2 = vertices(2) - vertices(0)
P = ray.v cross edge2
determinant = edge1 dot P
if !(determinant > -Utils.EPSILON && determinant < Utils.EPSILON)
inv_determinant = 1.0/determinant
T = ray.p - vertices(0)
u = (T dot P) * inv_determinant
if !(u < 0 || u > 1)
Q = T cross edge1
v = (ray.v dot Q) * inv_determinant
if !(v < 0 || u + v > 1)
t = (edge2 dot Q) * inv_determinant
if !(t < Utils.EPSILON)
hit = ray.p + ray.v*t
} yield
if (hasUV) {
val d0 = Math.abs((hit - vertices(0)).length)
val d1 = Math.abs((hit - vertices(1)).length)
val d2 = Math.abs((hit - vertices(2)).length)
val uvAvg = (uv(0)*d0 + uv(1)*d1 + uv(2)*d2) / (d0 + d1 + d2)
new BasicIntersection(hit, edge1 cross edge2, t, uvAvg)
} else {
new BasicIntersection(hit, edge1 cross edge2, t)
}
result.getOrElse(new BasicIntersection()) // Your failure case
Below code searches for a motif (of length 8) in a sequence(String) and, as the result, it has to give back sequence with the best score. The problem is, although the code produces no errors, there is no output at all (probably infinite cycle, I observe blank console).
I am gonna give all my code online and if that is required. In order to reproduce the problem, just pass a number (between 0 and 3 - you can give 4 sequence, so you must choose 1 of them 0 is the first , 1 is the second etc) as args(0) (e.g. "0"), expected output should look something like "Motif = ctgatgta"
import scala.util.control._
object BranchAndBound {
var seq: Array[String] = new Array[String](20)
var startPos: Array[Int] = new Array[Int](20)
var pickup: Array[String] = new Array[String](20)
var bestMotif: Array[Int] = new Array[Int](20)
var ScoreMatrix = Array.ofDim[Int](5, 20)
var i: Int = _
var j: Int = _
var lmer: Int = _
var t: Int = _
def main(args: Array[String]) {
var t1: Long = 0
var t2: Long = 0
t1 = 0
t2 = 0
t1 = System.currentTimeMillis()
val seq0 = Array(
Array(
" >5 regulatory reagions with 69 bp",
" cctgatagacgctatctggctatccaggtacttaggtcctctgtgcgaatctatgcgtttccaaccat",
" agtactggtgtacatttgatccatacgtacaccggcaacctgaaacaaacgctcagaaccagaagtgc",
" aaacgttagtgcaccctctttcttcgtggctctggccaacgagggctgatgtataagacgaaaatttt",
" agcctccgatgtaagtcatagctgtaactattacctgccacccctattacatcttacgtccatataca",
" ctgttatacaacgcgtcatggcggggtatgcgttttggtcgtcgtacgctcgatcgttaccgtacggc"),
Array(
" 2 columns mutants",
" cctgatagacgctatctggctatccaggtacttaggtcctctgtgcgaatctatgcgtttccaaccat",
" agtactggtgtacatttgatccatacgtacaccggcaacctgaaacaaacgctcagaaccagaagtgc",
" aaacgttagtgcaccctctttcttcgtggctctggccaacgagggctgatgtataagacgaaaattttt",
" agcctccgatgtaagtcatagctgtaactattacctgccacccctattacatcttacgtccatataca",
" ctgttatacaacgcgtcatggcggggtatgcgttttggtcgtcgtacgctcgatcgttaccgtacggc"),
Array(
" 2 columns mutants",
" cctgatagacgctatctggctatccaggtacttaggtcctctgtgcgaatctatgcgtttccaaccat",
" agtactggtgtacatttgatccatacgtacaccggcaacctgaaacaaacgctcagaaccagaagtgc",
" aaacgttagtgcaccctctttcttcgtggctctggccaacgagggctgatgtataagacgaaaattttt",
" agcctccgatgtaagtcatagctgtaactattacctgccacccctattacatcttacgtccatataca",
" ctgttatacaacgcgtcatggcggggtatgcgttttggtcgtcgtacgctcgatcgttaccgtacggc"),
Array(
" 2 columns mutants",
" cctgatagacgctatctggctatccaggtacttaggtcctctgtgcgaatctatgcgtttccaaccat",
" agtactggtgtacatttgatccatacgtacaccggcaacctgaaacaaacgctcagaaccagaagtgc",
" aaacgttagtgcaccctctttcttcgtggctctggccaacgagggctgatgtataagacgaaaattttt",
" agcctccgatgtaagtcatagctgtaactattacctgccacccctattacatcttacgtccatataca",
" ctgttatacaacgcgtcatggcggggtatgcgttttggtcgtcgtacgctcgatcgttaccgtacggc"))
var k: Int = 0
var m: Int = 0
var n: Int = 0
var bestScore: Int = 0
var optScore: Int = 0
var get: Int = 0
var ok1: Boolean = false
var ok3: Boolean = false
ok1 = false
ok3 = false
j = 1
lmer = 8
m = 1
t = 5
n = 69
optScore = 0
bestScore = 0
k = java.lang.Integer.parseInt(args(0))
j = 1
while (j <= t) {
seq(j) = new String()
i = 0
while (i < n) {
seq(j) += seq0(k)(j).charAt(i)
i += 1
}
j += 1
}
j = 1
while (j <= t) {
newPickup(1, j)
j += 1
}
j = 0
bestScore = 0
i = 1
val whilebreaker = new Breaks
whilebreaker.breakable {
while (i > 0) {
if (i < t) {
if (startPos(1) == (n - lmer)) whilebreaker.break
val sc = Score()
optScore = sc + (t - i) * lmer
if (optScore < bestScore) {
ok1 = false
j = i
val whilebreak1 = new Breaks
whilebreak1.breakable {
while (j >= 1) {
if (startPos(j) < n - lmer) {
ok1 = true
newPickup(0, j)
whilebreak1.break
} else {
ok1 = true
newPickup(1, j)
val whilebreak2 = new Breaks
whilebreak2.breakable {
while (startPos(i - 1) == (n - lmer)) {
newPickup(1, i - 1)
i -= 1
if (i == 0) whilebreak2.break
}
}
if (i > 1) {
newPickup(0, i - 1)
i -= 1
}
whilebreak1.break
}
}
}
if (ok1 == false) i = 0
} else {
newPickup(1, i + 1)
i += 1
}
} else {
get = Score()
if (get > bestScore) {
bestScore = get
m = 1
while (m <= t) {
bestMotif(m) = startPos(m)
m += 1
}
}
ok3 = false
j = t
val whilebreak3 = new Breaks
whilebreak3.breakable {
while (j >= 1) {
if (startPos(j) < n - lmer) {
ok3 = true
newPickup(0, j)
whilebreak3.break
} else {
ok3 = true
newPickup(1, j)
val whilebreak4 = new Breaks
whilebreak4.breakable {
while (startPos(i - 1) == (n - lmer)) {
newPickup(1, i - 1)
i -= 1
if (i == 0) whilebreak4.break
}
}
if (i > 1) {
newPickup(0, i - 1)
i -= 1
}
whilebreak3.break
}
}
}
if (ok3 == false) i = 0
}
}
}
println("Motiv: " + Consensus())
// println()
j = 1
while (j <= t) {
t2 = System.currentTimeMillis()
j += 1
}
println("time= " + (t2 - t1) + " ms")
}
def Score(): Int = {
var j: Int = 0
var k: Int = 0
var m: Int = 0
var max: Int = 0
var sum: Int = 0
sum = 0
max = 0
m = 1
while (m <= lmer) {
k = 1
while (k <= 4) {
ScoreMatrix(k)(m) = 0
k += 1
}
m += 1
}
m = 1
while (m <= lmer) {
k = 1
while (k <= i) pickup(k).charAt(m) match {
case 'a' => ScoreMatrix(1)(m) += 1
case 'c' => ScoreMatrix(2)(m) += 1
case 'g' => ScoreMatrix(3)(m) += 1
case 't' => ScoreMatrix(4)(m) += 1
}
m += 1
}
j = 1
while (j <= lmer) {
max = 0
m = 1
while (m <= 4) {
if (ScoreMatrix(m)(j) > max) {
max = ScoreMatrix(m)(j)
}
m += 1
}
sum += max
j += 1
}
sum
}
def Consensus(): String = {
var i: Int = 0
var j: Int = 0
var k: Int = 0
var m: Int = 0
var max: Int = 0
var imax: Int = 0
var str: String = null
i = 1
while (i <= t) {
pickup(i) = " " +
seq(i).substring(bestMotif(i), bestMotif(i) + lmer)
i += 1
}
m = 1
while (m <= lmer) {
k = 1
while (k <= 4) {
ScoreMatrix(k)(m) = 0
k += 1
}
m += 1
}
m = 1
while (m <= lmer) {
k = 1
while (k <= t) pickup(k).charAt(m) match {
case 'a' => ScoreMatrix(1)(m) += 1
case 'c' => ScoreMatrix(2)(m) += 1
case 'g' => ScoreMatrix(3)(m) += 1
case 't' => ScoreMatrix(4)(m) += 1
}
m += 1
}
str = ""
imax = 0
j = 1
while (j <= lmer) {
max = 0
i = 1
while (i <= 4) {
if (ScoreMatrix(i)(j) > max) {
max = ScoreMatrix(i)(j)
imax = i
}
i += 1
}
imax match {
case 1 => str += 'a'
case 2 => str += 'c'
case 3 => str += 'g'
case 4 => str += 't'
}
j += 1
}
str
}
def newPickup(one: Int, h: Int) {
if (one == 1) startPos(h) = 1 else startPos(h) += 1
pickup(h) = " " + seq(h).substring(startPos(h), startPos(h) + lmer)
}
}
and thanks, i hope someone gonna find my failure.
Your current implementation 'hangs' on this loop:
while (k <= i) pickup(k).charAt(m) match {
case 'a' => ScoreMatrix(1)(m) += 1
case 'c' => ScoreMatrix(2)(m) += 1
case 'g' => ScoreMatrix(3)(m) += 1
case 't' => ScoreMatrix(4)(m) += 1
}
As it stands, the exit condition is never fulfilled because the relation between k and i never changes. Either increment k or decrement i.
It looks like programming is not the key aspect of this work, but increased modularity should help contain complexity.
Also, I wonder about the choice of using Scala. There're many areas in this algorithm that would benefit of a more functional approach. In this translation, using Scala in an imperative way gets cumbersome. If you have the opportunity, I'd recommend you to explore a more functional approach to solve this problem.
A tip: The intellij debugger didn't have issues with this code.