OO 프로그래밍에 익숙하며 개념을 사용하기 위해 내 프로그램의 디자인에 약간의 문제가 있습니다. 튜토리얼을 끝 냈지만 여전히 문제가 있습니다.클래스를 변수로 디자인 할 때 문제가 발생합니다.
항목 값 (이 예제에서는 주식 일 수 있음)을 사용하고 특정 값 (이 코드 100)과 같아야하는 항목의 수를 계산합니다. 이 부분은 작동하지만 주식의 가중치가 임계 값을 초과하는지 알고 싶습니다. 원래는 for 루프를 수행하고 전체 값 목록을 계산하는 방법으로이 문제에 접근했지만 재귀의 모든 루프에서이를 수행하므로 비효율적입니다. 클래스를 사용하여 상태 정보를 유지하고 각 루프의 값을 증가시킬 수 있고 임계 값에 도달하면 알려주므로 클래스를 배우려고 노력하는 것이 좋은 시간이라고 생각했습니다.
코드가 있다고 생각하지만 수업에서이 문제를 어떻게 디자인해야하는지 완전히 이해하지 못했습니다. 지금까지는 처음에는 클래스 였기 때문에 순환을 반복합니다. 이것을 설계하는 더 좋은 방법이 있습니까? 내 최종 목표는 가중치를 초과하면 알림을받습니다. (어느 정도 할 수 있습니다.)하지만 최소한의 리소스를 사용하는 방식으로하고 싶습니다. (비효율적 인 루프는 필요하지 않습니다.)
코드 전체 코드) 나는 배우고 사용하고 있지만, 문제는 카운터 클래스와 findVariables 방법 내에서의 위치에 있습니다 :
import java.util.Arrays;
public class LearningClassCounting {
public static int[] stock_price = new int[]{ 20,5,20};
public static int target = 100;
public static void main(String[] args) {
// takes items from the first list
findVariables(stock_price, 100, new int[] {0,0,0}, 0, 0);
}
public static void findVariables(int[] constants, int sum,
int[] variables, int n, int result) {
Counter Checker = new Counter(stock_price, variables);
if (n == constants.length) {
if (result == sum) {
System.out.println(Arrays.toString(variables));
}
} else if (result <= sum){ //keep going
for (int i = 0; i <= 100; i++) {
variables[n] = i;
Checker.check_total_percent(n, i);
findVariables(constants, sum, variables, n+1, result+constants[n]*i);
}
}
}
}
class Counter {
private int[] stock_price;
private int[] variables;
private int value_so_far;
public Counter(int[] stock_price, int[] variables) {
this.stock_price = stock_price;
this.variables = variables;
for (int location = 0; location < variables.length; location++) {
//System.out.println(variables[location] + " * " + stock_price[location] + " = " + (variables[location] * stock_price[location]));
value_so_far = value_so_far + (variables[location] * stock_price[location]);
}
//System.out.println("Total value so far is " + value_so_far);
//System.out.println("************");
}
public void check_total_percent(int current_location, int percent) {
// Check to see if weight exceeds threshold
//System.out.println("we are at " + current_location + " and " + percent + " and " + Arrays.toString(variables));
//System.out.println("value is " + stock_price[current_location] * percent);
//formula I think I need to use is:
if (percent == 0) {
return;
}
int current_value = (stock_price[current_location] * percent);
int overall_percent = current_value/(value_so_far + current_value);
if (overall_percent > 50) {
System.out.println("item " + current_location + " is over 50%");
}
}
}
이 코드를 올바르게 읽으려면'findVariables' 메서드가'{20,5,20}'집합에서 100을 넘는 주식 추가 집합을 결정한다고 가정합니까? 그래서 그것은 탐욕스러운 알고리즘의 한 형태입니까? 이 코드는 전혀 읽기가 쉽지 않습니다. – Tejs
@Tejs 네 맞습니다. 클래스의 디자인을 이해하는 샘플을 찾았습니다. 코드가 보이는 방식에 대해 미안 하구, 나는 꽤 새로웠다. (그리고 나 자신을위한 코드) 포인터가 있다면 나는 버린다. 내 코드를 읽기 쉽도록 만들기 위해 적용하십시오. –