0

I want to write a binary search program in Scala without using any if-else statements at all. Basic strategy which i have devised uses the return value of comparison between array[mid] and search_key. In short :

1) Generate return value based on comparison between array[mid] and search_key

2) Create a unique string using that return value.

3) Call function using 'reflection' with help of that string

So my question is ...is there any computational logic which returns different values in this case ? How can i achieve this ? For example :

if array[mid] == search_key , return 0
if array[mid] > search_key , return 1
if array[mid] < search_key , return 2

If anyone have any better solution for this problem, please also suggest that.

Shubham Patil
  • 148
  • 12
  • Why do you need to use reflection based off of a unique string? – michaelsnowden Oct 09 '15 at 23:53
  • Well, I'm a beginner in Scala so don't know much.I thought of calling a method based on whatever string gets formed using that return value. After some googling, i found that calling methods using string names can be done using reflection in Scala. So that why. Here is one of the references : http://stackoverflow.com/questions/2060395/is-there-any-scala-feature-that-allows-you-to-call-a-method-whose-name-is-stored – Shubham Patil Oct 10 '15 at 00:26
  • Why can't you use ifs and else's? – michaelsnowden Oct 10 '15 at 00:29
  • Reflection really shouldn't be used for something so simple – michaelsnowden Oct 10 '15 at 00:32
  • Because it is a college assignment and problem definition states that we have to write the program without using if-else. I guess the basic idea was to avoid the branching of instructions. Not so sure. – Shubham Patil Oct 10 '15 at 00:36
  • Yeah i know ! Reflection is slow. But I'm not able to think of any other solution and also not getting much resources for this problem of eliminating if-else on the internet. Do you have any simpler way ? If you have, please tell me ! :) – Shubham Patil Oct 10 '15 at 00:40
  • I don't know about scala, but in other languages you can replace conditionals with polymorphism – michaelsnowden Oct 10 '15 at 00:47
  • @michaelsnowden you can replace some ifs with polymorphism, true. But it's not obvious how to do it in this case (in any language) – The Archetypal Paul Oct 10 '15 at 07:22

1 Answers1

2

The easy way that does something similar is

array(mid) compareTo search_key

This line is equivalent to

if (array(mid) == search_key) 0
else if (array(mid) < search_key) -1
else 1 // if (array(mid) > search_key)

As for the best way to do it, you could make a sequence of actions to take, and compute an index into that sequence. If you are interested you can see the full code in https://gist.github.com/kolmar/bcfc94ee4051ee7eb3a1

Kolmar
  • 14,086
  • 1
  • 22
  • 25