Simon
BAN USERzeroFound = false
for col = 0 to len(row 1) {
for each row in source array
if row[col] == 1, this row must have the maximum of 1s
zeroFound = true
if zeroFound, break
}
public class MostOnes {
public static String run(int[][] src) {
StringBuilder s = new StringBuilder();
int len = src[0].length;
boolean zeroFound = false;
for(int col = 0 ; col < len && !zeroFound; col ++) {
for(int row = 0; row < src.length; row++) {
if(src[row][col] == 1) {
zeroFound = true;
s.append("[").append(row + 1).append(",").append(len - col).append("]");
}
}
}
return s.toString();
}
}
test case
@Test
public void test() {
int[][] arr = {{0,0,0,0,0,0,0,1,1,1,1,1},
{0,0,0,0,1,1,1,1,1,1,1,1},
{0,0,0,0,0,0,1,1,1,1,1,1},
{0,0,0,0,0,0,0,0,0,1,1,1},
{0,0,0,0,0,0,0,1,1,1,1,1},
{0,0,0,0,1,1,1,1,1,1,1,1}};
String result = MostOnes.run(arr);
Assert.assertEquals("[2,8][6,8]", result);
}
public class NonZeroOnLeft {
public static void run(int[] src) {
for (int i = -1, j = src.length; i < j;) {
while (i < src.length - 1 && src[++i] != 0)
;
while (j > 0 && src[--j] == 0)
;
if (i >= j)
break;
int t = src[i];
src[i] = src[j];
src[j] = t;
}
}
}
test case
@Test
public void test() {
int length = new Random().nextInt(20) + 10;
int[] src = new int[length];
for (int i = 0; i < length; i++) {
src[i] = new Random().nextInt(5);
}
System.out.println(Arrays.toString(src));
NonZeroOnLeft.run(src);
System.out.println(Arrays.toString(src));
boolean zeroFound = false;
for (int i = 0; i < src.length; i++) {
if (src[i] == 0)
zeroFound = true;
Assert.assertTrue(zeroFound && src[i] == 0 || !zeroFound && src[i] != 0);
}
}
tested with the test case and some variations(some or all numbers changed to negative), more test cases needed
- Simon April 11, 2017