How to check if a number is a fibonacci number? - scala

Im trying to create a function that determines if a number is a fibonacci number or not in Scala. Can someone look at my code and let me know what I'm missing? Thanks
def isFibNumber(n: Int): Boolean = {
var fib1 = 0;
var fib2 = 1;
do {
var saveFib1 = fib1;
fib1 = fib2;
fib2 = saveFib1 + fib2;
}
while (fib2 < n);
if (fib2 == n)
return true;
else
return false;
}

That would help. No loop required
http://www.geeksforgeeks.org/check-number-fibonacci-number/
object Fib {
def isPerfectSq(n: Int): Boolean = {
val res = math.round(math.sqrt(n))
res * res == n.toLong
}
def isFibonacci(n: Int) = {
isPerfectSq(5 * n * n - 4) || isPerfectSq(5 * n * n + 4)
}
}

def isFibonacciNumber(n: Int): Boolean = {
var fib1 = -1;
var fib2 = 1;
var res = 0;
do {
res = fib1+fib2;
fib1 = fib2;
fib2 = res;
} while (res < n);
if (res == n)
return true;
else
return false;
}
This should work. You had error in your algorithm.

Related

Why isn't the return as expected?

Could you please run println(func("ctnkh"))? I got 4, but isn't it supposed to be 5?
def func(s: String): Int = {
if(s == "")
return 0
val len = s.length
var max = Int.MinValue
for(i <- 0 until len)
for(j <- i+1 to len) {
val ss = s.substring(i, j)
if(ss.mkString == ss.toSet.mkString) {
if(ss.length > max)
max = ss.length
}
}
max
}
I'll appreciate any of your hints
because ss.toSet.mkString will be in a different order than ss.mkString
for ex. try the following:
val str = "ctnkh"
println(str.mkString)
println(str.toSet.mkString)
output is:
ctnkh
ntchk
so the result will never be 5
edit: as mentioned in the comments you can't rely on the order of the characters in the Set as this order is not predictable.
You probably meant: ss.distinct. It drops all duplicate characters from the string, and preserves the order of the remaining characters.
def func(s: String): Int = {
val len = s.length
var max = 0
for(i <- 0 until len) {
for(j <- i+1 to len) {
val ss = s.substring(i, j)
if(ss == ss.distinct) {
max = max.max(ss.length)
}
}
}
max
}
println(func("ctnkh"))
gives 5, as you expected.
For your test, it's sufficient to check size:
if (ss.length == ss.toSet.size) max = max.max(ss.length)
since iteration order is extraneous.

Scala - while loop to for-comprehension

Is it possible to achieve the same functionality as
def filler(input: Array[Float], output: Array[Float]): Unit = {
var maxValue:Float = 0
var idx:Int = 1
output(0)= input(0)
while(idx < input.length) {
output(idx) = max(input(idx)/idx,maxValue)
maxValue = output(idx)
idx = idx + 1
}
}
with the help of for comprehension, or to rewrite it in any other "functional" way?
Thanks!
def filler(input: Array[Float]): Array[Float] = {
input.zipWithIndex.scanLeft(0.0f) {
case (maxValue, (x, i)) => max(x/Math.max(1, i), maxValue)
}.tail
}

scala tictactoe avoid mutable variable

I wrote a simple implementation of the tic tac toe game in scala.
package tiktaktoe
/**
* Created by donbeo on 28/12/15.
*/
class Board {
val size = 3
// size of the board
val goal = 3
// number in line. These values are assumed to be always 3 and 3
val board = Array.fill(size, size)(0) // the board
def isValidPosition(pos: Pos): Boolean = {
if (pos._1 >= 0 && pos._2 >= 0 && pos._1 < size && pos._2 < size && board(pos._1)(pos._2) == 0) true
else false
}
def setPosition(pos: Pos, number: Int): Unit = {
if (isValidPosition(pos)) {
board(pos._1)(pos._2) = number
println(this)
val winner = winningPlayer
if (winner != 0) println("The winner is: Player " + winner)
}
else throw new Exception("Not Valid Position")
}
def winningPlayer: Int = {
if (isLine(0) != 0) isLine(0)
if (isLine(1) != 0) isLine(1)
if (isLine(2) != 0) isLine(2)
if (isColumn(0) != 0) isColumn(0)
if (isColumn(1) != 0) isColumn(1)
if (isColumn(2) != 0) isColumn(2)
if (isDiagonal != 0) isDiagonal
else 0
}
private def isLine(line: Int): Int = {
// this works only if goal = size
val number = board(line)(0)
if (number == 0) return 0
else if (board(line) == Array.fill(size)(number)) return number
else 0
}
private def isColumn(column: Int): Int = {
val number = board(0)(column)
if (number == 0) 0
else if (board(1)(column) == number && board(2)(column) == number) number
else 0
}
private def isDiagonal: Int = {
val number = board(1)(1)
if (board(2)(2) == number && board(1)(1) == number) number
else if (board(0)(2) == number && board(2)(0) == number) number
else 0
}
override def toString = "Board=\n" + board.deep.mkString("\n") + "\n"
}
class Player(number: Int) {
private def computeNextMove(board: Board): Pos = {
(2, 3)
}
def nextMove(board: Board, pos: Pos): Unit = {
board.setPosition(pos, number)
}
}
object PlayGame {
def main(args: Array[String]) {
val board = new Board
val players = List(new Player(1), new Player(2))
println("Start the game \n\n" + board)
players(0).nextMove(board, (1, 0))
players(1).nextMove(board, (1, 1))
players(0).nextMove(board, (1, 2))
players(1).nextMove(board, (0, 0))
players(0).nextMove(board, (2, 1))
players(1).nextMove(board, (2, 2))
}
}
The game is based on the function Player.nextMove that modifies the status of the board. As far as I know it is better to avoid mutable variables in scala.
I am wondering how can I implement the game without using the mutable board

Extract multiple substrings from same string efficiently

I have a large dataset of URL strings containing key-value pairs, and I want to capture a list of values from that string. One example of a string is below:
"GET /no_cache/bi_page?Log=1&pg_inst=600474500174606089&pg=mdot_fyc_pnt&platform=mdot&ver=10.c110&pid=157876860906745096&rid=157876731027276387&srch_id=-2&row=7&seq=1&tot=1&tsp=1&test_name=m_control&logDomain=http%3A%2F%2Fwww.xyz.com&ref_url=http%3A%2F%2Fm.xyz.com%2F&z=44134 HTTP/1.1"
So if my list of values to return come from keys: "pg","test_name","some_other_key" ... I'd want the function to return ("mdot_fyc","m_control","NA") for this row.
I could just write three separate regex lines to capture each value. But some of these strings are long and I could have dozens of these values to extract instead of just three.
What's the most efficient way to extract multiple values from the same string?
Here is a simple 1-pass solution. Let me know if it's fast enough.
I'm no expert in URLs, so it might need tuning. Basically it assumes that there are no unescaped spaces, '?', '&' or '=' characters.
It can be further smoothed with low-level opti.
def extractParams(params: List[String], from: String): Map[String, String] = {
val a = from.toCharArray
val len = a.length
import scala.annotation.tailrec
#tailrec
def extract(p: Set[String], start: Int, results: Map[String, String]): Map[String, String] = {
var paramStart = start
var nextEquals = -1
var nextAmpersand = -1
if (start == 0) { // find start of params
var i = 0
while (i < len && a(i) != '?') {
i += 1
}
if (i == len) return results
paramStart = i
}
{ // find equals
var i = paramStart
while (i < len && a(i) != '=') {
i += 1
}
if (i == len) return results
nextEquals = i
}
{ // find nextAmpersand or end
var i = nextEquals
while (i < len && !(a(i) == '&' || a(i) == ' ')) {
i += 1
}
nextAmpersand = i
}
val paramNameArr = new Array[Char](nextEquals - paramStart - 1)
System.arraycopy(a, paramStart + 1, paramNameArr, 0, nextEquals - paramStart - 1)
val paramName = new String(paramNameArr)
var newResults = results
var newP = p
if (p.contains(paramName)) { // find param value
val paramValueArr = new Array[Char](nextAmpersand - nextEquals - 1)
System.arraycopy(a, nextEquals + 1, paramValueArr, 0, nextAmpersand - nextEquals - 1)
val paramValue = new String(paramValueArr)
newResults = newResults + (paramName -> paramValue)
newP = p - (paramName)
}
if (nextAmpersand == len || a(nextAmpersand) == ' ') { // check for end
return newResults
} else {
return extract(newP, nextAmpersand, newResults)
}
}
extract(params.toSet, "GET ".length, Map.empty)
}

Why do I have "Type mismatch; Found Unit, expected Boolean" in Scala-IDE?

I've got the following Scala code(ported from a Java one):
import scala.util.control.Breaks._
object Main {
def pascal(col: Int, row: Int): Int = {
if(col > row) throw new Exception("Coloumn out of bound");
else if (col == 0 || col == row) 1;
else pascal(col - 1, row - 1) + pascal(col, row - 1);
}
def balance(chars: List[Char]): Boolean = {
val string: String = chars.toString()
if (string.length() == 0) true;
else if(stringContains(")", string) == false && stringContains("(", string) == false) true;
else if(stringContains(")", string) ^ stringContains("(", string)) false;
else if(getFirstPosition("(", string) > getFirstPosition(")", string)) false;
else if(getLastPosition("(", string) > getLastPosition(")", string)) false;
else if(getCount("(", string) != getCount(")", string)) false;
var positionOfFirstOpeningBracket = getFirstPosition("(", string);
var openingBracketOccurences = 1; //we already know that at the first position there is an opening bracket so we are incrementing it right away with 1 and skipping the firstPosition variable in the loop
var closingBracketOccurrences = 0;
var positionOfClosingBracket = 0;
breakable {
for(i <- positionOfFirstOpeningBracket + 1 until string.length()) {
if (string.charAt(i) == ("(".toCharArray())(0)) {
openingBracketOccurences += 1;
}
else if(string.charAt(i) == (")".toCharArray())(0) ) {
closingBracketOccurrences += 1;
}
if(openingBracketOccurences - closingBracketOccurrences == 0) { //this is an important part of the algorithm. if the string is balanced and at the current iteration opening=closing that means we know the bounds of our current brackets.
positionOfClosingBracket = i; // this is the position of the closing bracket
break;
}
}
}
val insideBrackets: String = string.substring(positionOfFirstOpeningBracket + 1, positionOfClosingBracket)
balance(insideBrackets.toList) && balance( string.substring(positionOfClosingBracket + 1, string.length()).toList)
def getFirstPosition(character: String, pool: String): Int =
{
for(i <- 0 until pool.length()) {
if (pool.charAt(i) == (character.toCharArray())(0)) {
i;
}
}
-1;
}
def getLastPosition(character: String, pool: String): Int =
{
for(i <- pool.length() - 1 to 0 by -1) {
if (pool.charAt(i) == (character.toCharArray())(0)) {
i;
}
}
-1;
}
//checks if a string contains a specific character
def stringContains(needle: String, pool: String): Boolean = {
for(i <- 0 until pool.length()) {
if(pool.charAt(i) == (needle.toCharArray())(0)) true;
}
false;
}
//gets the count of occurrences of a character in a string
def getCount(character: String, pool: String) = {
var count = 0;
for ( i <- 0 until pool.length()) {
if(pool.charAt(i) == (character.toCharArray())(0)) count += 1;
}
count;
}
}
}
The problem is that the Scala IDE(lates version for Scaal 2.10.1) gives the following error at line 78(on which there is a closin brace): "Type mismatch; Found Unit, expected Boolean". I really can't understand what the actual problem is. The warning doesn't give any information where the error might be.
In Scala (and most other functional languages) the result of a function is the value of the last expression in the block. The last expression of your balance function is the definition of function getCount, which is of type Unit (the Scala equivalent of void), and your function is declared as returning a Boolean, thus the error.
In practice, you've just screwed up your brackets, which would be obvious if you used proper indentation (Ctrl+A, Ctrl+Shift+F in scala-ide).
To make it compile, you can put the following two lines at the end of the balance method instead of in the middle:
val insideBrackets: String = string.substring(positionOfFirstOpeningBracket + 1, positionOfClosingBracket)
balance(insideBrackets.toList) && balance(string.substring(positionOfClosingBracket + 1, string.length()).toList)
You would also have to put the inner functions at the top of balance I think -- such as getCount.