Interest Rate Function - swift

I found some code online regarding a finance calculator function but I'm not sure what it does, I'm still new to swift so if someone could explain the purpose of the function I would appreciate it a lot
func calculateAnnualInterestRate() -> Double {
let numberOfMonths = Double(self.NumberofPayments)
var x = 1 + (((self.MonthlyPayment * numberOfMonths/self.loan) - 1) / 12)
func F(_ x: Double) -> Double {
let F = self.loan * x * pow(1 + x, numberOfMonths) / (pow(1 + x, numberOfMonths) - 1) - self.MonthlyPayment
return F;
}
func F_Prime(_ x: Double) -> Double {
let F_Prime = self.loan * pow(x + 1, numberOfMonths - 1) * (x * pow(x + 1, numberOfMonths) + pow(x + 1, numberOfMonths) - (numberOfMonths * x) - x - 1) / pow(pow(x + 1, numberOfMonths) - 1, 2)
return F_Prime
}
while(abs(F(x)) > Double(0.000001)) {
x = x - F(x) / F_Prime(x)
}
let I = Double(12 * x * 100)
if I < 0 || I.isNaN || I.isInfinite {
self.interest = 0.0;
return self.interest
} else {
self.interest = I.roundTo2()
return self.interest
}
}
I know that the function is necessary for the calculation of interest rate but I'm not sure what the F and F_Prime

Related

Running different objects in IDEA - Scala

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.

Swift Compile Perfomance is too slowly for a simple source code

I trying to make a little Swift 3 code to convert Sonar Date to Lunar Date.
A very tiny code, but Xcode take around 10 minutes to compile that.
Could you please give me some advice to improve performance.
Here are my swift code:
class DateExtensions {
let PI: Double = M_PI
func jdFromDate(day: Int, month: Int, year: Int) ->Int {
let a: Int = (14 - month) / 12
let y: Int = year + 4800 - a
let m: Int = month + 12 * a - 3
var jd: Int = day + (153 * m + 2)/5 + 365 * y + y/4 - y/100 + y/400 - 32045
if (jd < 2299161) {
jd = day + (153 * m + 2)/5 + 365 * y + y/4 - 32083
}
return jd
}
func jdToDate(_ jd: Int) -> [Int] {
var a: Int = 0
var b: Int = 0
var c: Int = 0
if (jd > 2299160) { // After 5/10/1582, Gregorian calendar
a = jd + 32044
b = (4 * a + 3) / 146097
c = a - (b * 146097) / 4
} else {
b = 0
c = jd + 32082
}
let d: Int = (4 * c + 3)/1461
let e: Int = c - (1461 * d)/4
let m: Int = (5 * e + 2)/153
let day: Int = e - (153 * m + 2)/5 + 1
let month: Int = m + 3 - 12 * (m/10)
let year: Int = b * 100 + d - 4800 + m/10
return [day, month, year]
}
func SunLongitude(_ jdn: Double) -> Double {
return SunLongitudeAA98(jdn)
}
func SunLongitudeAA98(_ jdn: Double) -> Double {
let T: Double = (jdn - 2451545.0 ) / 36525 // Time in Julian centuries from 2000-01-01 12:00:00 GMT
let T2: Double = T * T
let dr: Double = PI/180 // degree to radian
let M: Double = 357.52910 + 35999.05030 * T - 0.0001559 * T2 - 0.00000048 * T * T2 // mean anomaly, degree
let L0: Double = 280.46645 + 36000.76983 * T + 0.0003032 * T2 // mean longitude, degree
var DL: Double = (1.914600 - 0.004817 * T - 0.000014 * T2) * sin(dr * M)
DL = DL + (0.019993 - 0.000101 * T) * sin(dr * 2 * M) + 0.000290 * sin(dr * 3 * M)
var L: Double = L0 + DL // true longitude, degree
L = Double(L - 360 * (INT(L/360))) // Normalize to (0, 360)
return L
}
func NewMoon(_ k: Int) -> Double {
return NewMoonAA98(k)
}
func NewMoonAA98(_ k: Int) -> Double {
var T: Double = k/1236.85 // Time in Julian centuries from 1900 January 0.5
var T2: Double = T * T
var T3: Double = T2 * T
var dr: Double = PI/180
var Jd1: Double = Double(2415020.75933 + 29.53058868*k + 0.0001178*T2 - 0.000000155*T3)
Jd1 = Jd1 + 0.00033*sin((166.56 + 132.87*T - 0.009173*T2)*dr) // Mean new moon
var M: Double = Double(359.2242 + 29.10535608*k - 0.0000333*T2 - 0.00000347*T3) // Sun's mean anomaly
var Mpr: Double = Double(306.0253 + 385.81691806*k + 0.0107306*T2 + 0.00001236*T3) // Moon's mean anomaly
var F: Double = Double(21.2964 + 390.67050646*k - 0.0016528*T2 - 0.00000239*T3) // Moon's argument of latitude
var C1: Double = (0.1734 - 0.000393*T)*sin(M*dr) + 0.0021*sin(2*dr*M)
C1 = C1 - 0.4068*sin(Mpr*dr) + 0.0161*sin(dr*2*Mpr)
C1 = C1 - 0.0004*sin(dr*3*Mpr)
C1 = C1 + 0.0104*sin(dr*2*F) - 0.0051*sin(dr*(M+Mpr))
C1 = C1 - 0.0074*sin(dr*(M-Mpr)) + 0.0004*sin(dr*(2*F+M))
C1 = C1 - 0.0004*sin(dr*(2*F-M)) - 0.0006*sin(dr*(2*F+Mpr))
C1 = C1 + 0.0010*sin(dr*(2*F-Mpr)) + 0.0005*sin(dr*(2*Mpr+M))
var deltat: Double = 0
if (T < -11) {
deltat = 0.001 + 0.000839 * T + 0.0002261 * T2 - 0.00000845 * T3 - 0.000000081 * T * T3
} else {
deltat = -0.000278 + 0.000265 * T + 0.000262 * T2
}
let JdNew: Double = Jd1 + C1 - deltat
return JdNew
}
func INT(_ d: Double) -> Int {
return Int(exactly: floor(d))!
}
func getSunLongitude(_ dayNumber: Int, _ timeZone: Double) -> Double {
return SunLongitude(dayNumber - 0.5 - timeZone/24)
}
func getNewMoonDay(_ k: Int, _ timeZone: Double) -> Int {
let jd: Double = NewMoon(k)
return INT(jd + 0.5 + timeZone/24)
}
func getLunarMonth11(_ yy: Int, _ timeZone: Double) -> Int {
var off: Double = jdFromDate(31, 12, yy) - 2415021.076998695
var k: Int = INT(off / 29.530588853)
var nm: Int = getNewMoonDay(k, timeZone)
var sunLong: Int = INT(getSunLongitude(nm, timeZone)/30)
if (sunLong >= 9) {
nm = getNewMoonDay(k-1, timeZone)
}
return nm
}
func getLeapMonthOffset(_ a11: Int, _ timeZone: Double) -> Int {
var k: Int = INT(0.5 + (a11 - 2415021.076998695) / 29.530588853)
var last: Int = 0 // Month 11 contains point of sun longutide 3*PI/2 (December solstice)
var i: Int = 1 // We start with the month following lunar month 11
var arc = INT(getSunLongitude(getNewMoonDay(k+i, timeZone), timeZone)/30)
repeat {
last = arc
i = i + 1
arc = INT(getSunLongitude(getNewMoonDay(k+i, timeZone), timeZone)/30)
} while (arc != last && i < 14)
return i - 1
}
func convertSolar2Lunar(_ dd: Int, _ mm: Int, _ yy: Int, _ timeZone: Double) -> [Int] {
var lunarDay: Int = 0
var lunarMonth: Int = 0
var lunarYear: Int = 0
var lunarLeap: Int = 0
var dayNumber: Int = jdFromDate(dd, mm, yy)
var k: Int = INT((dayNumber - 2415021.076998695) / 29.530588853)
var monthStart: Int = getNewMoonDay(k + 1, timeZone)
if (monthStart > dayNumber) {
monthStart = getNewMoonDay(k, timeZone)
}
var a11: Int = getLunarMonth11(yy, timeZone)
var b11: Int = a11
if (a11 >= monthStart) {
lunarYear = yy
a11 = getLunarMonth11(yy-1, timeZone)
} else {
lunarYear = yy + 1
b11 = getLunarMonth11(yy + 1, timeZone)
}
lunarDay = dayNumber - monthStart + 1
var diff: Int = INT((monthStart - a11)/29)
lunarLeap = 0
lunarMonth = diff + 11
if (b11 - a11 > 365) {
var leapMonthDiff: Int = getLeapMonthOffset(a11, timeZone)
if (diff >= leapMonthDiff) {
lunarMonth = diff + 10
if (diff == leapMonthDiff) {
lunarLeap = 1
}
}
}
if (lunarMonth > 12) {
lunarMonth = lunarMonth - 12
}
if (lunarMonth >= 11 && diff < 4) {
lunarYear = lunarYear - 1
}
return [lunarDay, lunarMonth, lunarYear, lunarLeap]
}
func convertLunar2Solar(_ lunarDay: Int, _ lunarMonth: Int, _ lunarYear: Int, _ lunarLeap: Int, _ timeZone: Double) -> [Int]{
var a11: Int = 0
var b11: Int = 0
if (lunarMonth < 11) {
a11 = getLunarMonth11(lunarYear-1, timeZone)
b11 = getLunarMonth11(lunarYear, timeZone)
} else {
a11 = getLunarMonth11(lunarYear, timeZone)
b11 = getLunarMonth11(lunarYear+1, timeZone)
}
var k: Int = INT(0.5 + (a11 - 2415021.076998695) / 29.530588853)
var off: Int = lunarMonth - 11
if (off < 0) {
off = off + 12
}
if (b11 - a11 > 365) {
var leapOff: Int = getLeapMonthOffset(a11, timeZone)
var leapMonth: Int = leapOff - 2
if (leapMonth < 0) {
leapMonth = leapMonth + 12
}
if (lunarLeap != 0 && lunarMonth != leapMonth) {
//debugPrint("Invalid input!")
return new [0, 0, 0]
} else if (lunarLeap != 0 || off >= leapOff) {
off = off + 1
}
}
let monthStart: Int = getNewMoonDay(k + off, timeZone)
return jdToDate(monthStart+lunarDay-1)
}
}
update 1:
//
// DateExtensions.swift
// Sonar2Lunar
//
// Created by Nguyen Thanh Hai on 5/7/17.
// Copyright © 2017 Nguyen Thanh Hai. All rights reserved.
//
import Foundation
import SwiftDate
class DateExtensions {
let PI: Double = M_PI
func jdFromDate(_ day: Int, _ month: Int, _ year: Int) ->Int {
let a: Int = (14 - month) / 12
let y: Int = year + 4800 - a
let m: Int = month + 12 * a - 3
var jd: Int = day + (153 * m + 2)/5 + 365 * y + y/4 - y/100 + y/400 - 32045
if (jd < 2299161) {
jd = day + (153 * m + 2)/5 + 365 * y + y/4 - 32083
}
return jd
}
func jdToDate(_ jd: Int) -> [Int] {
var a: Int = 0
var b: Int = 0
var c: Int = 0
if (jd > 2299160) { // After 5/10/1582, Gregorian calendar
a = jd + 32044
b = (4 * a + 3) / 146097
c = a - (b * 146097) / 4
} else {
b = 0
c = jd + 32082
}
let d: Int = (4 * c + 3)/1461
let e: Int = c - (1461 * d)/4
let m: Int = (5 * e + 2)/153
let day: Int = e - (153 * m + 2)/5 + 1
let month: Int = m + 3 - 12 * (m/10)
let year: Int = b * 100 + d - 4800 + m/10
return [day, month, year]
}
func INT(_ d: Double) -> Int {
return Int(exactly: floor(d))!
}
func SunLongitude(_ jdn: Double) -> Double {
return SunLongitudeAA98(jdn)
}
func SunLongitudeAA98(_ jdn: Double) -> Double {
let T: Double = (jdn - 2451545.0 ) / 36525 // Time in Julian centuries from 2000-01-01 12:00:00 GMT
let T2: Double = T * T
let dr: Double = PI/180 // degree to radian
let M: Double = 357.52910 + 35999.05030 * T - 0.0001559 * T2 - 0.00000048 * T * T2 // mean anomaly, degree
let L0: Double = 280.46645 + 36000.76983 * T + 0.0003032 * T2 // mean longitude, degree
var DL: Double = (1.914600 - 0.004817 * T - 0.000014 * T2) * sin(dr * M)
DL = DL + (0.019993 - 0.000101 * T) * sin(dr * 2 * M) + 0.000290 * sin(dr * 3 * M)
var L: Double = L0 + DL // true longitude, degree
L = L - Double(360 * (INT(L/360))) // Normalize to (0, 360)
return L
}
}
The problem is partly that you know nothing of Swift numerics, and partly that Swift is not very good at handling large amounts of bad numeric code. A particularly egregious spot is:
func NewMoonAA98(_ k: Int) -> Double {
var T: Double = k/1236.85 // Time in Julian centuries from 1900 January 0.5
var T2: Double = T * T
var T3: Double = T2 * T
var dr: Double = PI/180
var Jd1: Double = Double(2415020.75933 + 29.53058868*k + 0.0001178*T2 - 0.000000155*T3)
Those lines alone are enough to send both the parser and the compiler in to a complete tailspin. You cannot combine an Int and a Double in the same expression. So this line:
var T: Double = k/1236.85 // Time in Julian centuries from 1900 January 0.5
needs to be
var T: Double = Double(k)/1236.85 // Time in Julian centuries from 1900 January 0.5
and this line:
var Jd1: Double = Double(2415020.75933 + 29.53058868*k + 0.0001178*T2 - 0.000000155*T3)
needs to be
var Jd1: Double = Double(2415020.75933 + 29.53058868*Double(k) + 0.0001178*T2 - 0.000000155*T3)
Those kinds of mistakes permeate your code, and the result is that the compiler is basically spinning its wheels; your code is such a numeric mess that the compiler doesn't know where to start to pinpoint the errors, they are so numerous and so mutually dependent. You could submit your code to Apple as a bug report, but really you could make more of an effort to be kind to the compiler.

Make Int round off to nearest value

I've got two Int values (they have to be Ints) and I want them to round off to the nearest value when in an equation;
var Example = Int()
var secondExample = Int()
Example = (secondExample / 7000)
This equation makes the variable Example always round down to the lowest value. Say for example that the numbers are the following;
var Example = Int()
var secondExample : Int = 20000
Example = (20000 / 7000)
20000 / 7000 equals 2.857... But the variable Example displays 2.
How can I make Example round off to closest number without changing it to a Double
For nonnegative integers, the following function gives
the desired result in pure integer arithmetic :
func divideAndRound(numerator: Int, _ denominator: Int) -> Int {
return (2 * numerator + denominator)/(2 * denominator)
}
Examples:
print(20000.0/7000.0) // 2.85714285714286
print(divideAndRound(20000, 7000)) // 3 (rounded up)
print(10000.0/7000.0) // 1.42857142857143
print(divideAndRound(10000, 7000)) // 1 (rounded down)
The idea is that
a 1 2 * a + b
- + - = ---------
b 2 2 * b
And here is a possible implementation for arbitrarily signed
integers which also does not overflow:
func divideAndRound(num: Int, _ den: Int) -> Int {
return num / den + (num % den) / (den / 2 + den % 2)
}
(Based on #user3441734's updated solution, so we have a reference
cycle between our answers now :)
There is also a ldiv function which computes both quotient
and remainder of a division, so the last function could also be
implemented as
func divideAndRound(num: Int, _ den: Int) -> Int {
let div = ldiv(num, den)
let div2 = ldiv(den, 2)
return div.quot + div.rem / (div2.quot + div2.rem)
}
(I did not test which version is faster.)
see Martin's answer! his idea is great, so i extend his solution for negative numbers
func divideAndRound(n: Int, _ d: Int) -> Int {
let sn = n < 0 ? -1 : 1
let sd = d < 0 ? -1 : 1
let s = sn * sd
let n = n * sn
let d = d * sd
return (2 * n + d)/(2 * d) * s
}
divideAndRound(1, 2) // 1
divideAndRound(1, 3) // 0
divideAndRound(-1, 2) // -1
divideAndRound(-1, 3) // 0
divideAndRound(1, -2) // -1
divideAndRound(1, -3) // 0
the only trouble is that (2 * n + d) can overflow and code will crash.
UPDATE! with help of mathematics for children
func divr(a: Int, _ b: Int)->Int {
return (a % b) * 2 / b + a / b
}
it should work for any Int :-) except 0 denominator.

Inconsistent behavior between Scala tail recursion vs imperative

I'm currently attempting to learn functional programming (and Scala) together. I'm porting some code from a FORTRAN routine for calculating a particular modified normalisation of the associated Legendre polynomials. My direct imperative translation of the original code is modpLgndr1 (which I have checked against the original algorithm). My initial attempt at writing the code in a functional form is in modpLgdnr2.
import math.pow, abs, sqrt, Pi
def xfact(m: Int): Double = {
if (m <= 1) 1.0
else {
if (m % 2 == 1) m.toDouble / sqrt(m.toDouble) * xfact(m - 1)
else 1.0 / sqrt(m.toDouble) * xfact(m - 1)
}
}
//this is a very un-scala function....
def modpLgndr1(l: Int, m: Int, x: Double): Double = {
assert(0 <= m && m <= l && abs(x) <= 1.0)
val dl = l.toDouble
val dm = m.toDouble
val norm = sqrt(2.0 * dl + 1.0) / sqrt(4.0 * Pi)
var pmm = norm
if (m != 0) pmm = (pow(-1, m)).toDouble * pmm * xfact(2 * m) * pow((1.0-x * x), (dm / 2.0))
if (l == m) pmm
else {
var pmmp1 = x * pmm * sqrt(2.0 * m + 1.0)
if (l == m + 1) pmmp1
else {
var pll = 0.0
var dll = 0.0
for (ll <- m + 2 to l) {
dll = ll.toDouble
pll = (x * (2.0 * dll - 1.0) * pmmp1 - sqrt(pow((dll - 1.0), 2.0) - dm * dm) * pmm) / sqrt(pow(dll, 2.0) - pow(dm, 2.0))
pmm = pmmp1
pmmp1 = pll
}
pll
}
}
}
def modpLgndr2(l: Int, m: Int, x: Double): Double = {
assert(0 <= m && m <= l && abs(x) <= 1.0)
val dl = l.toDouble
val dm = m.toDouble
val norm = sqrt(2.0 * dl + 1.0) / sqrt(4.0 * Pi)
val pmm = if (m == 0) norm else (pow(-1, m)).toDouble * norm * xfact(2 * m) * pow((1.0-x * x), (dm / 2.0))
if (l == m) pmm
else {
val pmmp1 = x * pmm * sqrt(2.0 * m + 1.0)
if (l == m + 1) pmmp1
else {
def mplacc(ll: Int, acc1: Double, acc2: Double): Double = {
val dll = ll.toDouble
val pll = (x * (2.0 * dll - 1.0) * acc2 - sqrt(pow((dll - 1.0), 2.0) - dm * dm) * acc1) / sqrt(pow(dll, 2.0) - pow(dm, 2.0))
if (ll == m + 2) pll
else mplacc(ll - 1, acc2, pll)
}
mplacc(l, pmm, pmmp1)
}
}
}
If I call the two functions I get output like this:
scala> for (i <- 0 to 10) println(modpLgndr1(10,i,0.2))
0.16685408398957746
-0.2769345073769805
-0.1575129272628402
0.2948210515201088
0.12578847877176355
-0.3292975894931367
-0.058267280378036426
0.37448134558730417
-0.08024600262585084
-0.40389602261165075
0.4424459249420354
scala> for (i <- 0 to 10) println(modpLgndr2(10,i,0.2))
0.16685408398957752
-0.2772969351441124
-0.1578618478786792
0.29654926805696474
0.1349402872678466
-0.33707342609134694
-0.06901634276825179
0.38912154672892657
-0.08024600262585084
-0.40389602261165075
0.4424459249420354
Essentially, for m = 0, l-2, l-1, l the code agrees; otherwise there is a significant discrepancy. That seems to tell me that the problem is in calling the mplacc function. To me, mplacc just looks like a recursive form of the for loop in modpLgndr1. Why am I wrong?

Scala Branch And Bound Motif Search

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.