still code
BAN USERNice solution, but what's the rationale here? I tabulated for k=3 and n from 1 to 5 and got:
n | cubes | hidden cubes
1 1 0
2 8 0
3 27 1
4 64 8
5 125 27
You can clearly 'see' the relationship (n-2). But how one can arrive to this in a more smart way?
- still code March 03, 2013This code prints the first coil, also with tests for n = 1 or 2
public class MatrixCoil {
int[][] matrix;
public int[] coil1;
public int[] coil2;
MatrixCoil(int n){
matrix = new int[4*n][4*n];
int num=1;
for(int i=0;i<matrix.length;i++) {
for(int j=0;j<matrix[i].length;j++) {
matrix[i][j] = num++;
System.out.print(num + " ");
}
System.out.println("");
}
}
public void printCoil() {
int tn = (matrix.length*matrix.length)/2;
coil1 = new int[tn];
coil2 = new int[tn];
// start of first coil
int ci = matrix.length/2;
int cj = matrix.length/2-1;
System.out.println("ci " + ci);
System.out.println("cj " + cj);
int step = 0;
int index=0;
coil1[index] = matrix[ci][cj];
while(index<tn-1) {
step+=2;
for(int i=0;i<step&&index<tn-1;i++) {
// decrement ci
index++;
ci--;
coil1[index] = matrix[ci][cj];
if(ci==0) break;
}
for(int i=0;i<step&&index<tn-1;i++) {
// increment cj
index++;
cj++;
coil1[index] = matrix[ci][cj];
if(cj==matrix.length-1) break;
}
step+=2;
for(int i=0;i<step&&index<tn-1;i++) {
// increment ci
index++;
ci++;
coil1[index] = matrix[ci][cj];
if(ci==matrix.length-1) break;
}
for(int i=0;i<step&&index<tn-1;i++) {
// decrement cj
index++;
cj--;
coil1[index] = matrix[ci][cj];
if(cj==0) break;
}
}
for(int i=0;i<coil1.length;i++) {
System.out.print(coil1[i] + " ");
}
System.out.println("");
for(int i=0;i<coil2.length;i++) {
System.out.print(coil2[i] + " ");
}
}
}
and tests
import org.testng.Reporter;
import org.testng.annotations.Test;
import static org.testng.Assert.assertEquals;
@Test
public class MatrixCoilTest {
public void shouldPrintCoil() {
MatrixCoil mc = new MatrixCoil(1);
mc.printCoil();
assertEquals(10,mc.coil1[0]);
assertEquals(16,mc.coil1[7]);
}
public void shouldPrintCoil2() {
MatrixCoil mc = new MatrixCoil(2);
mc.printCoil();
assertEquals(36,mc.coil1[0]);
assertEquals(64,mc.coil1[31]);
}
}
Given that TreeNode has a left and right nodes and a payload that implements Comparable.
- still code March 20, 2013