Some people complain about if
- statements and I really appreciate that attitude. Actually I plan to abandon the entire keyword in order to awesomize my code, which is:
Algorithm.java:
package net.coderodde.noxx;
import java.util.Arrays;
import java.util.Random;
/**
* This is algorithm. It works as .. there is no need for .. - statements.
* It proves that there is no need for .. - statements.
*/
public class Algorithm {
/**
* ..less algorithm for finding the index of a maximum integer in an array.
*
* @param array the array to search.
* @return the index of the maximum element or -1 if the array is
* <code>null</code> or has length zero.
*/
public static final int indexOfMaximum(final int[] array) {
int max;
int index;
// Here supposed check whether array is null or empty, but we are not
// supposed to use ..-statements. Use exceptions instead!
try {
max = array[0];
index = 0;
} catch (final NullPointerException |
ArrayIndexOutOfBoundsException ex) {
return -1;
}
for (int i = 1; i < array.length; ++i) {
// Why not to use for's test condition instead of ..?
for (int j = 0; j < testIsGreater(array[i], max); ++j) {
max = array[i];
index = i;
}
}
return index;
}
/**
* Life is so much easier now without .. .
*/
private static int testIsGreater(final int element, final int max) {
return element - max;
}
public static void main(final String... args) {
final Random rnd = new Random();
final int[] array = new int[10];
for (int i = 0; i < array.length; ++i) {
array[i] = rnd.nextInt(1301) - 300;
}
final int index = indexOfMaximum(array);
final int check = Arrays.stream(array).max().getAsInt();
System.out.println("Maximum integer: " + array[index]
+ " and "
+ check);
}
}
AlgorithmTest.java:
package net.coderodde.noxx;
import static net.coderodde.noxx.Algorithm.indexOfMaximum;
import org.junit.Test;
import static org.junit.Assert.*;
public class AlgorithmTest {
/**
* My tests use .. neither! Ain't this keeewl??
*/
@Test
public void testIndexOfMaximum() {
int[] array = new int[0];
assertEquals(-1, indexOfMaximum(array));
assertEquals(-1, indexOfMaximum(null));
array = new int[]{3, 2, 1, 4, 5, 1 };
assertEquals(4, indexOfMaximum(array));
array = new int[]{3};
assertEquals(0, indexOfMaximum(array));
array = new int[]{3, 4, 1, 7};
assertEquals(3, indexOfMaximum(array));
}
}
So is it kewl to awesomize the code this way?
..
=if
– Simon Forsberg McFeely♦ May 8 at 19:03...
operator. – Captain Man May 8 at 19:25element - max
can overflow (useInteger.compare
). – maaartinus May 8 at 21:23for
,while
, or?:
expression has anif
hidden in it. :) – cHao May 9 at 4:10