Skip to content

Instantly share code, notes, and snippets.

@taka2
Created June 15, 2010 08:41
Show Gist options
  • Select an option

  • Save taka2/438854 to your computer and use it in GitHub Desktop.

Select an option

Save taka2/438854 to your computer and use it in GitHub Desktop.
public class JavaTest
{
public static void main(String[] args) throws Exception
{
String str = "123456789";
// 数字をどこで区切るかのパターン総当たり
int separatePatterns = (int)Math.pow(2, (str.length() - 1));
for(int i=0; i<separatePatterns; i++)
{
String bin = paddingZeroToLeft(Integer.toString(i, 2), (str.length() - 1));
int[] operands = splitNumber(str, toIntArray(bin));
// + or -の演算子パターン総当たり
int operatePatterns = (int)Math.pow(2, operands.length - 1);
for(int j=0; j<operatePatterns; j++)
{
String opeBin = paddingZeroToLeft(Integer.toString(j, 2), (operands.length - 1));
int[] operators = toIntArray(opeBin);
int result = calc(operands, operators);
if(result == 100)
{
printFormula(operands, operators);
}
}
}
}
private static String paddingZeroToLeft(String str, int columns)
{
StringBuffer result = new StringBuffer(str);
for(int i=str.length(); i<columns; i++)
{
result.insert(0, '0');
}
return result.toString();
}
private static int[] toIntArray(String str)
{
int[] result = new int[str.length()];
for(int i=0; i<str.length(); i++)
{
result[i] = Integer.parseInt(str.substring(i, i+1));
}
return result;
}
// 文字列を指定された区切りパターンで区切り、数値に変換する。
private static int[] splitNumber(String str, int[] arr)
{
StringBuffer slashedStr = new StringBuffer();
for(int i=0; i<str.length(); i++)
{
slashedStr.append(str.charAt(i));
if(i < arr.length && arr[i] == 1)
{
slashedStr.append("/");
}
}
String[] splittedStrs = slashedStr.toString().split("/");
int[] result = new int[splittedStrs.length];
for(int i=0; i<splittedStrs.length; i++)
{
result[i] = Integer.parseInt(splittedStrs[i]);
}
return result;
}
private static int calc(int[] operands, int[] operators)
{
int result = operands[0];
for(int i=1; i<operands.length; i++)
{
if(operators[i-1] == 0)
{
// プラス
result = result + operands[i];
}
else
{
// マイナス
result = result - operands[i];
}
}
return result;
}
private static void printFormula(int[] operands, int[] operators)
{
StringBuffer resultStr = new StringBuffer();
resultStr.append(Integer.toString(operands[0]));
for(int i=1; i<operands.length; i++)
{
if(operators[i-1] == 0)
{
// プラス
resultStr.append(" + ");
}
else
{
// マイナス
resultStr.append(" - ");
}
resultStr.append(operands[i]);
}
int result = calc(operands, operators);
resultStr.append(" = ");
resultStr.append(Integer.toString(result));
System.out.println(resultStr.toString());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment