[Week Eight] Programming Contest - Array Modes

To modify ever so slightly!

103 characters

public static int mode(int[]a){int c=0,x;for(int i:a){x=0;for(int j:a)if(j==i)x++;c=c<x?x:c;}return c;}

If allowed to change method name it of course becomes 100:

public static int m(int[]a){int c=0,x;for(int i:a){x=0;for(int j:a)if(j==i)x++;c=c<x?x:c;}return c;}
public static int mode(int[] a) {
    int c = 0, x;
    for (int i : a) {
        x = 0;
        for (int j : a) {
            if (j == i) {
                x++;
            }
        }
        c = c < x ? x : c;
    }
    return c;
}

121 Chars

public static int m(int[]a){return IntStream.of(a).map(x->(int)IntStream.of(a).filter(i->i==x).count()).max().orElse(0);}

Just like @Saladoc except using IntStream. :smiley:

[s]Edit: Got a shorter one:
116 Chars

public static int m(int[]a){return IntStream.of(a).map(x->IntStream.of(a).filter(i->i==x).sum()/x).max().orElse(0);}
```[/s]
div by 0 errors are fun.
1 Like

98 characters:

public static int m(int[]a){Arrays.sort(a);int i=0,j=0;for(int k:a)if(a[i]<a[j++])i++;return j-i;}

I originally came up with this, but, minified, it’s 102 characters:

public static int largestFrequency(int[] a) {
    Arrays.sort(a);
    int i = 0, j = 0;
    for (; j < a.length; j++)
        if (a[i] < a[j])
            i++;
    return j - i;
}

Then I realized that the loop header can be replaced with java’s enhanced for loop. It handles loop continuation checking automatically without having to explicitly write j < a.length, so it’s shorter. I don’t even access the variable k introduced by the enhanced for loop and I continue to increment j as if it’s still the old loop. The winning submission for week seven probably could have been shortened the same way.

public static int largestFrequency(int[] a) {
    Arrays.sort(a);
    int i = 0, j = 0;
    for (int k : a)
        if (a[i] < a[j++])
            i++;
    return j - i;
}
1 Like
public static int z(int[]r){int m=0,c;for(int e:r){c=0;for(int i:r)m=e==i&&++c>m?c:m;}return m;}

96 characters

I dunno. I feel like I could do better. Lambda blah blah. Couldn’t work it in though.

:wink:

uncompacted:


public static int ModeGolf(int[] integerArray) {
   // by declaring currentCount here we save a couple of characters not having 
   // to declare it 'int' in the inner loop...
   int maxCount=0, currentCount;

   // originally planned to use a HashSet to cull elements but it wasn't worth it,
   // when we loop through the elements, we end up counting duplicates, but the
   // only consequence is repeating with a lower count, without hurting the result...

   // plus it turned out to be a lot of characters, because you can only HashSet 
   // Objects not directly an array of 'int'. and likely convert them back to int

   for (int arrayElement : integerArray) {
      currentCount=0;

      for (int arrayElementInner : integerArray) {
         // using a ternary saved a few extra characters over the corresponding 
         // 'if' statement. so did moving the assignment outside the ternary, as
         // opposed to doing the assignment in the result, which you can't do in 
         // java, anyway, apparently.
         maxCount = 
            // phew, order of operations didn't require any parens here.
            ((arrayElement == arrayElementInner) && (++currentCount > maxCount))
            ? currentCount
            : maxCount;
      }
   }
   // QED
   return maxCount;
}
def m(i:Array[_])=i.groupBy(x=>x).values.toSeq.sortBy(-_.length).head.length

76 bytes of Scala and not that bad to read

Less readable, but only 75:

def m(i:Array[_])=i.groupBy(x=>x).toSeq.sortBy(-_._2.length).head._2.length

The most readable version and the shortest as well with 61 characters:

def m(i:Seq[_])=i.groupBy(x=>x).values.maxBy(_.length).length

(I know it does not qualify for the contest)

A Java version of the last Scala version above:

static int m(int[]i){return of(i).boxed().collect(groupingBy(x->x)).values().stream().max((a,b)->a.size()-b.size()).get().size();}

way too long with 131 characters

95 characters

public static int m(int[]a){int i=0,j=0;Arrays.sort(a);for(int x:a)i+=x>a[j++-i]?0:1;return i;}

This is based on my answer for week 7 and uses @eah’s foreach loop trick.

Unminified:

public static int m(int[] a) {
    int i = 0, j = 0;
    Arrays.sort(a);
    for (int x : a)
        i += x > a[j++ - i] ? 0 : 1;
    return i;
}

I really tried to use streams and lambdas, but Java’s Stream syntax is just too verbose.

Wow @jus1in, I looked at that forever to see if I could do something like you did for the last one, but couldn’t find anything. Congrats.

agreed, @jus1in, that’s epic :slight_smile: i twiddled around for far too long on my latest and couldn’t drop a single byte… i intend to actually try to do something productive rather than golf today. xD i like that yours is actually using a few clever concepts instead of just a lot of individual little optimizations…

digging on that final scala one too, @pschichtel.

woo. golf. way more interesting with code than with clubs and dimpled balls.

1 Like

I know that the contest is closed but… 81 characters

int m(int[]a){int i,j;Arrays.sort(a);for(int x:a)i+=x>a[j++-i]?0:1;return i+1;}

I took jus1in’s solution and removed the unnecessary part of the method declaration (who said it needed to be public static?)

Nevermind, it was against the rules (and the contest is still open).

This is still open for a week BTW

The rules

I didn’t see that because it was in a different thread, sorry.

Make it an interface not a class, java will still run the static method as main (since java 8) and all the visibilities default to public.

You can’t define a method body inside an interface. You also can’t make interface methods static.

Unless if this isn’t against the rules (disregarding the absence of static)…
14 characters.

int m(int[]a);

Incorrect, run my entry in an IDE, it works. Default Methods (The Java™ Tutorials > Learning the Java Language > Interfaces and Inheritance)

For some next context I’d be really interested in something like:
A method that takes two Strings and returns the smallest possible number of changes you need to turn the first String into the second. Possible changes would be:

  1. Adding a char
  2. Changing a char
  3. Removing a char

So compare("chllrnge", "challenge") would return 2 (Add an ‘a’ and change ‘r’ to ‘e’)
or compare("muimecraf", "minecraft") would return 3 (Remove an ‘u’ and change ‘m’ to ‘n’ and add an ‘t’)

What do you think? Could this be a good challenge? :smiley:

Oh … damn xD Ok, that’s cool :o

It’s still a good golf challenge, just helps to have some reading.

1 Like

I’d thought I would try a different approach,

public static int m(int[]a){int i=1;for(String m=".*( .+ ).*\\1.*";Arrays.toString(a).replaceAll("[\\[\\]\\, ]"," ").matches(m);m+="\\1.*")i++;return i;}

153 characters
I tried using regex to solve the challenge. This solution will work for any printable array as long as the Object’s toString() doesn’t contain any ‘[’, ‘]’ or ’ ’

public static int mode(int[] a){
    int i = 1;
    String s = Arrays.toString(a).replaceAll("[\\[\\]\\, ]"," ");
    for(String m=".*( .+ ).*\\1.*";s.matches(m);m+="\\1.*")i++;
    return i;
}

Here’s the one for String[]:

public static int mode(String[] a){
    int i = 1;
    String s = Arrays.toString(a).replaceAll("[\\[\\]\\, ]"," ");
    for(String m=".*( .+ ).*\\1.*";s.matches(m);m+="\\1.*")i++;
    return i;
}

It works by making a string with a space before and after each number then checks how many backreferences there are to the regex “( .+ )”

Congratulations to @jus1in for winning this weeks programming challenge, and another honorable mention to @eah

The next one will be up shortly, it will be @Blue’s suggestion. For future ideas please suggest them on the main thread!

1 Like