0

how to pass reference to an array to function in scala.

for example following is a function in c/c++

how to write code for array ref in scala ?

int RMQUtil(int *st, int ss, int se, int qs, int qe, int index)
{
// If segment of this node is a part of given range, then return the
// min of the segment
if (qs <= ss && qe >= se)
    return st[index];

// If segment of this node is outside the given range
if (se < qs || ss > qe)
    return INT_MAX;

// If a part of this segment overlaps with the given range
int mid = getMid(ss, se);
return minVal(RMQUtil(st, ss, mid, qs, qe, 2*index+1),
              RMQUtil(st, mid+1, se, qs, qe, 2*index+2));
}

2 Answers 2

3

For the multiple arguments of the method consider

case class Params(ss: Int, se: Int, qs: Int, qe: Int, index: Int)

The Scala re-coding for the asked method above,

def RMQUtil(st: Array[Int], p: Params): Int = {
  if (p.qs <= p.ss && p.qe >= p.se) 
    st(index)
  else if (p.se < p.qs || p.ss > p.qe)
    Int.MaxValue
  else {
    val mid: Int = getMid(ss, se)
    Math.min( RMQUtil(st, Params(p.ss, mid, p.qs, p.qe, 2*index+1)),
              RMQUtil(st, Params(mid+1, p.se, p.qs, p.qe, 2*index+2)))
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Params(p.ss, mid, p.qs, p.qe, 2*index+1) could be p.copy(se = mid, index = 2 * index + 1). This way it easier to grasp what is changed and what is not. Not much win in having parameters passed this way (wrapped in a case class).
@om-nom-nom Thanks for the good observation, indeed not much gain other than utilising the copying method...
2

Something like this should work:

def RMQUtil(st: Array[Int], ss: Int, se: Int, qs: Int, qe: Int, index: Int): Int = {
  if (qs <= ss && qe >= se)
    return st(index)
  if (se < qs || ss > qe)
    return Int.MaxValue

  val mid = getMid(ss, se) // I assume this is something like (ss + se) / 2
  Math.min(RMQUtil(st, ss, mid, qs, qe, 2*index+1), RMQUtil(st, mid+1, se, qs, qe, 2*index+2))
}

1 Comment

@user2124441 a little comment about your suggested edit - it is not necessary to include the return keyword for the last statement

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.