60

I have this ugly code:

if ( v > 10 ) size = 6;
if ( v > 22 ) size = 5;
if ( v > 51 ) size = 4;
if ( v > 68 ) size = 3;
if ( v > 117 ) size = 2;
if ( v > 145 ) size = 1;
return size;

How can I get rid of the multiple if statements?

18
  • 4
    Did you really mean 5 and 6 to be in that order?
    – Jon Skeet
    Sep 24, 2010 at 11:04
  • 62
    FWIW, I don't think that is particularly ugly. It's easy to see what is happening, it's trivial to add in more cases, it's clear. The only thing I'd consider doing is adding a list where the conditions/values are stored, but other than that, I have no problem with it.
    – Noon Silk
    Sep 24, 2010 at 11:12
  • 13
    This code isn't ugly! A "fancier" solution will only make your code more unreadable and harder to maintain in the future. Sep 24, 2010 at 15:33
  • 7
    @Stephen: I don't see why a switch with 145 cases is less ugly. Look closer, a > is been used as equation, not ==.
    – BalusC
    Sep 24, 2010 at 16:35
  • 20
    So many upvotes on such a simple answer to a simple question, when the actual hard questions and answers don't get upvoted that much. Is StackOverflow dysfunctional? Oct 10, 2010 at 20:36

25 Answers 25

160

How about such approach:

int getSize(int v) {
    int[] thresholds = {145, 117, 68, 51, 22, 10};

    for (int i = 0; i < thresholds.length; i++) {
        if (v > thresholds[i]) return i+1;
    }
    return 1;
}

Functionally: (Demonstrated in Scala)

def getSize(v: Int): Int = {
  val thresholds = Vector(145, 117, 68, 51, 22, 10)
  thresholds.zipWithIndex.find(v > _._1).map(_._2).getOrElse(0) + 1
}
14
  • 10
    Nice thing about this approach is that it can be easily extended to more steps or wider range without much effort.
    – sbass
    Sep 24, 2010 at 11:53
  • 2
    Missing a last return statement, this won't compile (in java)
    – Ishtar
    Sep 24, 2010 at 13:42
  • 5
    I like this, too. Just to be safe I would put a comment in case someone adds/changes steps without realizing order is important. Alternately, a reverse sort on steps before the loop would work, too. Sep 24, 2010 at 17:44
  • 7
    This is less readable. With the if/elseif solution the code is instantly understandable. This code, while easy to understand, still requires a little thought to grok. Exact same number of lines of code, but requires a tiny bit more effort to read == less optimal solution IMO. Sep 30, 2010 at 17:03
  • 2
    I dislike the idea, what if you have to change and for 22 return 17 and 51 return 50? code does change and this is a maintenance nightmare.
    – IAdapter
    Oct 5, 2010 at 14:52
88

Using the NavigableMap API :

NavigableMap<Integer, Integer> s = new TreeMap<Integer, Integer>();
s.put(10, 6);
s.put(22, 5);
s.put(51, 4);
s.put(68, 3);
s.put(117, 2);
s.put(145, 1);

return s.lowerEntry(v).getValue();
20
  • 5
    very nice solution (+1), in fact I'd say it's the only non-ugly solution here Sep 24, 2010 at 11:38
  • 11
    Well, very non-ugly until you look at the overhead. Sep 24, 2010 at 12:00
  • 4
    A HashMap doesn't work here. NavigableMap allows to find the nearest key (either lower or greater) for a given value, which is important in our case.
    – barjak
    Sep 24, 2010 at 12:23
  • 14
    @JUST : I confess I wouldn't use my solution in such a simple case, but rather a bunch of if statements. However, if some flexibility is needed (for example, if those numbers are not hard-coded but come from a configuration file), then this solution makes sense. Plus, this solution can be useful if the "f" key of my keyboard is broken :)
    – barjak
    Sep 24, 2010 at 12:31
  • 6
    Rules of Abstraction: Rule 1: Don't do it. Rule 2 (for experts only): Don't do it yet. Sep 24, 2010 at 14:23
82

The most obvious problem with the OPs solution is branching, so I would suggest a polynomial regression. This will result in a nice branchless expression on the form

size = round(k_0 + k_1 * v + k_2 * v^2 + ...)

You will of course not get an exact result, but if you can tolerate some deviance it's a very performant alternative. Since the 'leave unmodified' behavior of to original function for values where v<10 is impossible to model with a polynomial, I took the liberty of assuming a zero-order hold interpolation for this region.

For a 45-degree polynomial with the following coefficients,

-9.1504e-91 1.1986e-87 -5.8366e-85 1.1130e-82 -2.8724e-81 3.3401e-78 -3.3185e-75  9.4624e-73 -1.1591e-70 4.1474e-69 3.7433e-67 2.2460e-65 -6.2386e-62 2.9843e-59 -7.7533e-57 7.7714e-55 1.1791e-52 -2.2370e-50 -4.7642e-48 3.3892e-46 3.8656e-43 -6.0030e-41 9.4243e-41 -1.9050e-36 8.3042e-34 -6.2687e-32 -1.6659e-29 3.0013e-27 1.5633e-25 -8.7156e-23  6.3913e-21 1.0435e-18 -3.0354e-16 3.8195e-14 -3.1282e-12 1.8382e-10 -8.0482e-09 2.6660e-07 -6.6944e-06 1.2605e-04 -1.7321e-03 1.6538e-02 -1.0173e-01 8.3042e-34 -6.2687e-32 -1.6659e-29 3.0013e-27 1.5633e-25 -8.7156e-23 6.3913e-21 1.0435e-18 -3.0354e-16 3.8195e-14 -3.1282e-12 1.8382e-10 -8.0482e-09 2.6660e-07 -6.6944e-06 1.2605e-04 -1.7321e-03 1.6538e-02 -1.0173e-01 3.6100e-01 -6.2117e-01 6.3657e+00

, you get a beautifully fitted curve:

alt text

And as you can see, you get an 1-norm error of just 1.73 across the whole range from 0 to 200*!

*Results for v∉[0,200] may vary.

6
  • I love this because I've always enjoyed coming up with expressions that "pack" the data for a lookup into mathematical expressions. Take some constants, throw in some multiplication, addition, modulus, abs(), floor(), and so on, and you can do fun stuff to calculate things like the number of days in each month. But I never considered a polynomial for this sort of thing!
    – ErikE
    Sep 29, 2010 at 7:50
  • 2
    Wow! Could You elaborate more on the tools You used to produce the output?
    – Rekin
    Oct 10, 2010 at 11:16
  • How did you find out the coefficients? Is it some advanced math? Oct 10, 2010 at 21:34
  • It's just a polynomial regression, see en.wikipedia.org/wiki/Polynomial_regression. I used Octave to write the output function and computed a best fit using the polyfit function. Oct 13, 2010 at 15:34
  • 2
    +1 very good but it will be somewhat hard to understand what it does and harder to maintain.
    – fmucar
    Feb 2, 2011 at 18:02
75
if ( v > 145 ) size = 1;
else if ( v > 117 ) size = 2;
else if ( v > 68 ) size = 3;
else if ( v > 51 ) size = 4;
else if ( v > 22 ) size = 5;
else if ( v > 10 ) size = 6;

return size;     

This is better for your case.

Optionally you should choose Switch Case where ever possible

Update: If you have analyzed the value of 'v' generally resides in lower range(<10) in most of the cases than you can add this.

if(v < 10)           size = SOME_DEFAULT_VALUE;
else if ( v > 145 )  size = 1;
else if ( v > 117 )  size = 2;
else if ( v > 68 )   size = 3;
else if ( v > 51 )   size = 4;
else if ( v > 22 )   size = 5;
else if ( v > 10 )   size = 6;   

further : You can also alter the condition sequence, according to your analysis. If you know that most of the values are less than 10 and then in the second place most of values lie between 68-117, you can alter the condition sequence accordingly.

Edits:

if(v < 10)           return SOME_DEFAULT_VALUE;
else if ( v > 145 )  return 1;
else if ( v > 117 )  return 2;
else if ( v > 68 )   return 3;
else if ( v > 51 )   return 4;
else if ( v > 22 )   return 5;
else if ( v > 10 )   return 6;   
29
  • 94
    Even better: just return the value right away without using intermediate size variable. Sep 24, 2010 at 13:06
  • 11
    @Rene Saarsoo It is best practice to have only one return statement
    – jmj
    Sep 24, 2010 at 14:18
  • 58
    @org I hear that is best practice all the time, but when it makes the code awkward it seems silly to me. Do you have any substantiation of this claim that it's actually better? Note this is not the same as "it's consensus that this is best practice" but something proving that it IS best practice.
    – ErikE
    Sep 24, 2010 at 17:14
  • 59
    @org.life.java This "best practice" is entirely subjective and most probably outdated (since it is a throwback to the days of languages like C where you have to explicitly manage resources). There are many times when you get far more readable and maintainable code by multiple return statements. Smart compilers take care of the rest. See consultingblogs.emc.com/anthonysteele/archive/2008/07/14/…
    – Dan Diplo
    Sep 24, 2010 at 19:00
  • 7
    @seanizer: less understandable than using tons of useless intermediate steps for the sake of code "purity"?
    – ninjalj
    Sep 25, 2010 at 10:32
51
return v > 145 ? 1 
     : v > 117 ? 2 
     : v > 68 ? 3 
     : v > 51 ? 4 
     : v > 22 ? 5 
     : v > 10 ? 6 
     : "put inital size value here";
21
  • 13
    could you please read initial question? "How can i get rid of multiple if statements?" There are no "if" statements in my answer as you can see.
    – dhblah
    Sep 24, 2010 at 11:12
  • 12
    @gasan, sure, you removed the if's but the op claimed his code was ugly, and intended to make it more readable...do you actually believe this is...prettier?
    – st0le
    Sep 24, 2010 at 11:18
  • 30
    You're confusing me with someone else. My name is Bauke Scholtz, not Jesus Christ. As said in a comment, I added some newlines. It is less ugly and improves readability.
    – BalusC
    Sep 24, 2010 at 11:56
  • 12
    I like this form and find it readable, though I recognize that most people have a problem with it. I don't see why anyone who understands the chained if/else-if/else construct has a problem with the chained ternary ?: operator. They are perfectly parallel to one another.
    – Bert F
    Sep 24, 2010 at 17:40
  • 9
    I find this much easier to read than the accepted if/else-if answer, thanks to Balus' reformatting. I agree with Bert, yes, people seem to have a problem with this; I just don't understand why people find the ternary ?: so cryptic. Agree with badp too, neither the OP's code or the accepted answer deal with a default "otherwise" case.
    – Stephen P
    Sep 24, 2010 at 20:45
23

The original code seems fine to me, but if you don't mind multiple returns you might prefer a more tabular approach:

if ( v > 145 ) return 1;
if ( v > 117 ) return 2;
if ( v >  68 ) return 3;
if ( v >  51 ) return 4;
if ( v >  22 ) return 5;
if ( v >  10 ) return 6;
return ...;     // The <= 10 case isn't handled in the original code snippet. 

See the multiple return or not discussion in org.life.java's answer.

17

There are a ton of answers and suggestions here but I honestly don't see any of them "prettier" or "more elegant" than the original method.

If you had dozens or HUNDREDS of iterations to check then I could easily see going to some for loop but honestly, for the handful of comparisons you had, stick with the if's and move on. It's not that ugly.

3
  • 6
    Agree. But these questions let people show alternate solutions. For example, I had never heard of NavigableMap.
    – Tony Ennis
    Sep 24, 2010 at 14:21
  • Well you probably heard of a TreeMap, but you didn't know which interfaces it implements :-) Sep 24, 2010 at 15:20
  • 1
    Agreed… Take a good, hard look at your first revision and just say to yourself, [gloves]. [gloves]: thedailywtf.com/Articles/The_Complicator_0x27_s_Gloves.aspx Edit: Why does this choke the Markdown parser?! Sep 25, 2010 at 1:15
14
return (v-173) / -27;
3
  • 1
    +1 because it was an interesting approach. (173-v) / 27 to remove the -. It doesn't work for big numbers, and at near the thresholds. But interesting...
    – Déjà vu
    Sep 25, 2010 at 15:45
  • What is the formula behind this?
    – kofucii
    Sep 26, 2010 at 7:51
  • 2
    lol +1 I want to introduce some code like this in a production environment as a joke ^_^ Feb 17, 2011 at 17:23
12

Here's my shot at it...

Update: Fixed. Previous Solution gave incorrect answers for exact values (10,22,51...). This one defaults to 6 for the if val < 10

   static int Foo(int val)
    {
                          //6, 5, 4, 3, 2 ,1
        int[] v = new int[]{10,22,51,68,117,145};
        int pos = Arrays.binarySearch(v, val-1);
        if ( pos < 0) pos = ~pos;
        if ( pos > 0) pos --;
        return 6-pos;
    }
3
  • I was just about posting a solution like yours, using binarySearch. +1 for using the ~ operator on binarySearch result, I never thought about that. Note : you can get rid of the size array, it's not 5,6 but 6,5.
    – barjak
    Sep 24, 2010 at 12:57
  • 1
    @LnxPrgr3, i agree. It's not, was just offering an alternative.
    – st0le
    Sep 24, 2010 at 19:37
  • +1 for a solution that works quickly for large datasets, and doesn't have more overhead than the original for small datasets. Oct 15, 2010 at 15:26
11

I have one more version for you. I don't really think it's the best one because it adds unnecessary complexity in the name of "performance" when I'm 100% sure this function will never be a performance hog (unless someone is calculating size in a tight loop a million times ...).

But I present it just because I thought performing a hard-coded binary search to be sort of interesting. It doesn't look very binary-y because there aren't enough elements to go very deep, but it does have the virtue that it returns a result in no more than 3 tests rather than 6 as in the original post. The return statements are also in order by size which would help with understanding and/or modification.

if (v > 68) {
   if (v > 145) {
      return 1
   } else if (v > 117) {
      return 2;
   } else {
      return 3;
   }
} else {
   if (v > 51) {
      return 4;
   } else if (v > 22) {
      return 5;
   } else {
      return 6;
   }
}
4
  • 5
    Efficient and original (+1), but a maintenance nightmare Sep 29, 2010 at 6:59
  • 2
    Clearly a maintenance nightmare. But it was fun to think up! :)
    – ErikE
    Sep 29, 2010 at 7:44
  • 1
    If you use a code generation mechanism to build this automatically this could actually be pretty good. Sep 29, 2010 at 9:58
  • 1
    upvoted because I also said that in another comment, but I was too lazy to post the answer xD
    – fortran
    Oct 1, 2010 at 13:12
7
7 - (x>10 + x>22 + x>51 + x>68 + x>117 + x>145)

where 7 is the default value (x <= 10).

Edit: Initially I didn't realize this question is about Java. This expression is not valid in Java, but is valid in C/C++. I will leave the answer, as some users found it helpful.

3
  • The question is tagged Java, not C/C#/C++. Dec 5, 2012 at 3:26
  • This is NOT valid in C#. You cannot add Booleans.
    – ErikE
    Apr 26, 2017 at 6:17
  • @ErikE Thanks, fixed it. I wrongly interpreted the comment regarding C/C#/C++.
    – George
    Apr 26, 2017 at 11:44
5

My commenting ability isn't turned on yet, hopefully no one will say "rightfully" based on my answer...

Pretty-ing up the ugly code could/should be defined as trying to achieve:

  1. Readability (OK, stating the obvious -- redundant to the question perhaps)
  2. Performance -- at best seeking optimal, at worst it's not a big drain
  3. Pragmatism -- it's not far off the way most people do things, given an ordinary problem that's not in need of an elegant or unique solution, changing it later on should be a natural effort, not in need of much recollection.

IMO the answer given by org.life.java was the prettiest and extremely easy to read. I also liked the order in which the conditions were written, for reasons of reading and performance.

Looking over all the comments on this subject, at the time of my writing, it appears that only org.life.java raised the issue of performance (and maybe mfloryan, too, stating something would be "longer"). Certainly in most situations, and given this example it shouldn't bear a noticeable slowdown however you write it.

However, by nesting your conditions and optimally ordering the conditions can improve performance [worthwhile, particularly if this were looped].

All that being said, nesting and ordering conditions (that are more complex than your example) brought on by determination to achieve as fast as possible execution will often produce less readable code, and code that's harder to change. I refer again to #3, pragmatism... balancing the needs.

5

Here is an object-oriented solution, a class called Mapper<S,T> that maps values from any type that implements comparable to any target type.

Syntax:

Mapper<String, Integer> mapper = Mapper.from("a","b","c").to(1,2,3);

// Map a single value
System.out.println(mapper.map("beef")); // 2

// Map a Collection of values
System.out.println(mapper.mapAll(
    Arrays.asList("apples","beef","lobster"))); // [1, 2, 3]

Code:

public class Mapper<S extends Comparable<S>, T> {

    private final S[] source;
    private final T[] target;

    // Builder to enable from... to... syntax and
    // to make Mapper immutable
    public static class Builder<S2 extends Comparable<S2>> {
        private final S2[] data;
        private Builder(final S2[] data){
            this.data = data;
        }
        public <T2> Mapper<S2, T2> to(final T2... target){
            return new Mapper<S2, T2>(this.data, target);
        }
    }


    private Mapper(final S[] source, final T[] target){
        final S[] copy = Arrays.copyOf(source, source.length);
        Arrays.sort(copy);
        this.source = copy;
        this.target = Arrays.copyOf(target, target.length);
    }

    // Factory method to get builder
    public static <U extends Comparable<U>, V> Builder<U> from(final U... items){
        return new Builder<U>(items);
    }

    // Map a collection of items
    public Collection<T> mapAll(final Collection<? extends S> input){
        final Collection<T> output = new ArrayList<T>(input.size());
        for(final S s : input){
            output.add(this.map(s));
        }
        return output;
    }

    // map a single item
    public T map(final S input){
        final int sourceOffset = Arrays.binarySearch(this.source, input);
        return this.target[
            Math.min(
                this.target.length-1,
                sourceOffset < 0 ? Math.abs(sourceOffset)-2:sourceOffset
            )
        ];
    }
}

Edit: finally replaced the map() method with a more efficient (and shorter) version. I know: a version that searches partitions would still be faster for large arrays, but sorry: I'm too lazy.

If you think this is too bloated, consider this:

  1. It contains a builder that lets you create the Mapper using varargs syntax. I'd say that's a must-have for usability
  2. It contains both a single item and a collection mapping method
  3. It's immutable and hence thread safe

Sure, all of these features could be easily removed, but the code would be less complete, less usable or less stable.

47
  • 16
    Too complicated.... why should someone involve objects in something as simple as take decisions over primitive types?
    – JPCF
    Sep 24, 2010 at 16:07
  • 31
    Holy Grace Hopper, what monstrosity is this? They just wanted to tighten up a few IFs.
    – Incognito
    Sep 24, 2010 at 18:08
  • 10
    @seanizer Premature abstraction is the root of all evil. No… losing a benchmark to the standard library isn't a shame. Rolling your own solution anyway without gaining something over the standard library is an odd choice though, especially when it means replacing 6 if statements with 54 lines of Java (not counting the code to actually use this thing). Besides, when was being object oriented inherently an advantage? Sep 25, 2010 at 0:59
  • 4
    Intuition reading your code without reading the Mapper class would make me think 10 maps to 6, etc., which it does not. If I ran into this in someone's codebase, I'd have to read and comprehend your class (or its documentation, had you bothered to write any) to know what this really does. This takes longer than understanding a chain of if statements. Sure, your solution is more general and even clever, but who said either was needed in this context? Sep 26, 2010 at 0:53
  • 7
    Your answer has earned kind of award: forums.thedailywtf.com/forums/p/20192/234306.aspx
    – BalusC
    Sep 27, 2010 at 14:30
4

Is there an underlying mathematical rule to this? If so you should use that: but only if it comes from the problem domain, not just some formula that happens to fit the cases.

0
3
int[] arr = new int[] {145, 117, 68, 51, 22, 10};
for(int index = 0; index < arr.length; index++)
{
  if(v > arr[index]) return 1 + index; 
}

return defaultValue;
3

You could rewrite it in ARM code. It's only 7 cycles worst case and a slender 164 bytes. Hope that helps. (note: this is untested)

; On entry
;   r0 - undefined
;   r1 - value to test
;   lr - return address
; On exit
;   r0 - new value or preserved
;   r1 - corrupted
;
wtf
        SUBS    r1, r1, #10
        MOVLE   pc, lr
        CMP     r1, #135
        MOVGT   r0, #1
        ADRLE   r0, lut
        LDRLEB  r0, [r0, r1]
        MOV     pc, lr
;
; Look-up-table
lut
        DCB     0   ; padding
        DCB     6   ; r1 = 11 on entry
        DCB     6
        DCB     6
        DCB     6
        DCB     6
        DCB     6
        DCB     6
        DCB     6
        DCB     6
        DCB     6
        DCB     6
        DCB     6
        DCB     5   ; r1 = 23 on entry
        DCB     5
        ...
        ALIGN
2
  • You didn't put full lookup table, code is incomplete :(
    – ByeBye
    Nov 24, 2017 at 6:50
  • True. I was going to complete the LUT but I couldn't decide whether to use a map or a polynomial regression to generate it. Nov 24, 2017 at 10:03
2

Actually, if the sizes are likely to change, doing it in the database could be a good alternate strategy:

CREATE TABLE VSize (
   LowerBound int NOT NULL CONSTRAINT PK_VSize PRIMARY KEY CLUSTERED,
   Size int NOT NULL
)
INSERT VSize VALUES (10, 6)
INSERT VSize VALUES (22, 5)
INSERT VSize VALUES (51, 4)
INSERT VSize VALUES (68, 3)
INSERT VSize VALUES (117, 2)
INSERT VSize VALUES (145, 1)

And a stored procedure or function:

CREATE PROCEDURE VSizeLookup
   @V int,
   @Size int OUT
AS
SELECT TOP 1 @Size = Size
FROM VSize
WHERE @V > LowerBound
ORDER BY LowerBound
2
  • 1
    :-) agreed, since oracle is the master you have to use a database for this
    – bobndrew
    Sep 29, 2010 at 16:48
  • 1
    Why the down votes? You guys like releasing a new version just to accommodate data changes?
    – ErikE
    Sep 30, 2010 at 21:49
1

Just for completeness, let me suggest that you could set up an array SIZES with 145 elements so the answer could be returned directly as SIZES[v]. Pardon me for not writing the whole thing out. You would have to make sure v was in range, of course.

The only reason I can think of for doing it that way would be if you were going to create the array once and use it thousands of time in an application that had to be really fast. I mention it as an example of a trade-off between memory and speed (not the problem it once was), and also between setup time and speed.

1
  • This is the same as my solution below that got -1 for whatever reason even though it is a very reasonable situation for some situations.
    – CashCow
    Oct 11, 2010 at 14:12
1

The obvious answer is to use Groovy:

def size = { v -> [145,117,68,51,22,10].inject(1) { s, t -> v > t ? s : s + 1 } }

One liners are always better. Returns 7 for the undefined case where v <= 10.

0

This is my code sample, using SortedSet. You initialise boundaries once.

SortedSet<Integer> boundaries = new SortedSet<Integer>;

boundaries.add(10);

boundaries.add(22);

boundaries.add(51);

boundaries.add(68);

boundaries.add(117);

boundaries.add(145);

Then use it subsequently this way for multiple values of v (and initialised size)

SortedSet<Integer> subset =  boundaries.tailSet(v);
if( subset.size() != boundaries.size() )
  size = subset.size() + 1;
12
  • 1
    This is intended to show a generic way to make a "histogram" type lookup, and uses an O(log N) lookup for the number of boundaries. Where N is small this may prove to be less efficient than nested if statements.
    – CashCow
    Sep 27, 2010 at 14:51
  • First of all: this won't compile. It must be SortedSet<Integer>, not SortedSet<int>. Also this approach has already been taken more effectively using NavigableMap.lowerEntry() here: stackoverflow.com/questions/3786358/… Sep 27, 2010 at 15:29
  • No, NavigableMap is different because you had to associate the value with the entry. Now what do you think would happen if they decided to insert 89 as an extra boundary and we now return 1..7. I would require one extra add() whilst NavigableMap would require changing the values on all the lower existing ones.
    – CashCow
    Sep 27, 2010 at 16:04
  • Yup, I know, my own solution is the most flexible one :-) Sep 27, 2010 at 16:35
  • @seanizer: Your solution is indeed the most flexible one, but if the intention of the OP is that of what Neil thinks it is (count the # of boundaries above value v) his solution would be more correct. Sep 28, 2010 at 7:21
0

It is interesting that there are plenty of beautiful answers for a simple "ugly" question. I like mfloryan's answer best, however I would push it further by removing the hard-coded array inside the method. Something like,

int getIndex(int v, int[] descArray) {
    for(int i = 0; i < descArray.length; i++)
        if(v > descArray[i]) return i + 1;
    return 0;
}

It now becomes more flexible and can process any given array in descending order and the method will find the index where the value 'v' belongs.

PS. I cannot comment yet on the answers.

0

If you really want the fastest big-O complexity time solution for this particular answer this one is constant lookup.

final int minBoundary = 10;
final int maxBoundary = 145;
final int maxSize = 6;
Vector<Integer> index = new Vector<Integer>(maxBoundary);
    // run through once and set the values in your index

subsequently

if( v > minBoundary )
{
   size = (v > maxBoundary ) ? maxSize : index[v];
}

What we are doing here is marking all the possible results of v within the range and where they fall, and then we only need to test for boundary conditions.

The issue with this is that it uses more memory and of course if maxBoundary is a lot bigger it will be very space inefficient (as well as take a longer time to initialise).

This may sometimes be the best solution for the situation.

0

why somebody have not suggested switch statement. it is far better then if else ladder.

public int getSize(int input)
    {
        int size = 0;
        switch(input)
        {
        case 10:
            size = 6;
            break;

        case 22:
            size = 5;
            break;


        case 51:
            size = 4;
            break;

        case 68:
            size = 3;
            break;

        case 117:
            size = 2;
            break;

        case 145:
            size = 1;
            break;
        }

        return size;
    }
1
  • Because the condition is "greater than". For 100 the original code returns 3 but yours return 0
    – nrofis
    Oct 17, 2020 at 14:16
-1
            if (v <= 10)
                return size;
            else {
                size = 1;

                if (v > 145)
                    return size;
                else if (v > 117)
                    return ++size;
                else if (v > 68)
                    return (size+2);
                else if (v > 51)
                    return (size+3);
                else if (v > 22)
                    return (size+4);
                else if (v > 10)
                    return (size+5);
            }

This will execute the necessary if statements only.

3
  • Why -1? Will you please let me know?
    – Vikram
    Nov 30, 2012 at 15:08
  • 2
    I think it's because your solution is worse, it doesn't get rid of the ugly if statements...
    – radonys
    Dec 19, 2012 at 16:05
  • But, it surely executes less if statements (than in the original Q) making it faster.
    – Vikram
    Dec 19, 2012 at 16:08
-1

Yet another variation (less pronounced than the answer by George)

  //int v = 9;
  int[] arr = {145, 117, 68, 51, 22, 10};
  int size = 7; for(;7 - size < arr.length && v - arr[size - 2] > 0; size--) {};
  return size;

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.