Skip to content

Instantly share code, notes, and snippets.

@mulya
Last active March 13, 2017 10:16
Show Gist options
  • Save mulya/f45091758e96d6efbfe875a50b013f4d to your computer and use it in GitHub Desktop.
Save mulya/f45091758e96d6efbfe875a50b013f4d to your computer and use it in GitHub Desktop.
Решение задачи Кирпичная пирамида
/**
*
*/
public class Main {
/**
* Рекурсия
* Коротко написано, но долго работает за счёт дублирования пересчёта веса
*/
public static float functionW_recursion(int row, int pos) {
System.out.println("row: " + row + " pos: " + pos);
int brickWeight = 1;
if(row == 0) {
return 0;
} else if(pos == 0) {
return (functionW_recursion(row - 1, pos) + brickWeight) / 2;
} else if(pos == row) {
return (functionW_recursion(row - 1, pos - 1) + brickWeight) / 2;
} else {
return (functionW_recursion(row - 1, pos - 1) + functionW_recursion(row - 1, pos) + 2 * brickWeight) / 2;
}
}
/**
* Цикл
* Дольше писать, но работает быстрее за счёт того что давление на каждый блок считается лишь единожды
*/
public static float functionW_cycle(int row, int pos) {
int brickWeight = 1;
float[] upperRowArray = new float[0];
float[] currentRowArray;
float result = 0f;
out:
for(int rowIndex = 0; rowIndex <= row; rowIndex++){
currentRowArray = new float[rowIndex+1];
for(int posIndex = 0; posIndex <= rowIndex; posIndex++){
if(rowIndex == 0 && posIndex == 0) {
currentRowArray[posIndex] = 0;
} else if(posIndex == 0) {
currentRowArray[posIndex] = (upperRowArray[posIndex] + brickWeight) / 2;
} else if(posIndex == rowIndex){
currentRowArray[posIndex] = (upperRowArray[posIndex - 1] + brickWeight) / 2;
} else {
currentRowArray[posIndex] = (upperRowArray[posIndex - 1] + upperRowArray[posIndex] + 2 * brickWeight) / 2;
}
if(rowIndex == row && posIndex == pos){
result = currentRowArray[posIndex];
break out;
}
}
upperRowArray = currentRowArray;
}
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment