Created
October 11, 2011 07:52
-
-
Save Ramasubramanian/1277516 to your computer and use it in GitHub Desktop.
Naive solution to Satvim's puzzle
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package test_crawler.test; | |
import java.util.ArrayList; | |
import java.util.List; | |
/** | |
* 1. Create a 2D array of characters | |
* 2. Gather the lower edge indexes first e.g. in a 3 x 3 array gather all y positions alone | |
* y x x | |
* y x x | |
* y y y | |
* 3. For each character in the input start with the co-ordinates gathered earlier and fill the 2D array with | |
* characters until it reaches the other edge i.e. diagonally navigate the array | |
* @author raam | |
* | |
*/ | |
public class SatvimPuzzle { | |
private static final Index INVALID = new Index(-1, -1); | |
static class Index { | |
final int i; | |
final int j; | |
public Index(int x, int y){ | |
i = x; | |
j = y; | |
} | |
} | |
private static List<Index> getLowerEdgeIndices(int numRows,int numCols){ | |
List<Index> indexes = new ArrayList<SatvimPuzzle.Index>(); | |
for(int i=0;i<numRows;i++) | |
indexes.add(new Index(i,0)); | |
for(int i=1;i<numCols;i++) | |
indexes.add(new Index(numRows-1,i)); | |
return indexes; | |
} | |
/** | |
* Returns INVALID if we have reached the other edge | |
* @param current | |
* @param result | |
* @return | |
*/ | |
private static Index getNextIndex(Index current, char[][] result){ | |
if(current.i == 0 || current.j >= result[0].length-1) | |
return INVALID; | |
else | |
return new Index(current.i-1, current.j+1); //return top right index | |
} | |
private static String buildStr(char[][] ret){ | |
StringBuilder sb = new StringBuilder(); | |
for(char[] arr: ret) | |
sb.append(new String(arr).trim()); | |
return sb.toString(); | |
} | |
public static String convert(String str,int numRows){ | |
int numCols = (int)Math.ceil((double)str.length() / numRows); | |
char[][] ret = new char[numRows][numCols]; | |
List<Index> indexes = getLowerEdgeIndices(numRows, numCols); | |
int idxCounter = 1; | |
Index temp = indexes.get(0); | |
for(char c: str.toCharArray()){ | |
ret[temp.i][temp.j] = c; | |
temp = getNextIndex(temp, ret); | |
//if we reach the top edge proceed with next lower edge index | |
if(temp == INVALID && idxCounter < indexes.size()) | |
temp = indexes.get(idxCounter++); | |
} | |
return buildStr(ret); | |
} | |
public static void main(String[] args) { | |
System.out.println(convert("PAYPALISTHEFASTERSAFERWAYTOSENDMONEY", 4)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment