Mohamad Dirieh - 1 year ago 82
Java Question

# Improving my greedy Algorithm

**This is my code that look a way to find a sum in an array **

`````` public class Piecedemonei {
public static void recherche(int[] tab) {
int num;
int quo;
int somme = 18;
for (int i = 0; i <= tab.length - 1; i++) {

System.out.println("Solution  " + i);

for (int j = 0; j < tab.length; j++){

if (tab[j] <= somme) {

num = somme / tab[j];
System.out.print(num+"*" + " " + tab[j]);
System.out.println(" ");

somme -= num * tab[j];

}

}
}
}

public static void main(String[] args) {
int aba[] = { 7, 6, 4, 5 };
recherche(aba);
System.out.println();

}

}
``````

Output

``````Solution  0
2 7 + 1 4
Solution  1
Solution  2
Solution  3
``````

**I am looking a way to improve my code so that the output looks like this : **

`````` Solution  0
2*7 + 1*4
Solution  1
3*6
Solution  2
4*4 + 1*4
Solution  3
``````

**Why cant I reset my loop so that it does the same thing again and again ? **

Change

``````int somme = 18;
for (int i = 0; i <= tab.length - 1; i++) {
System.out.println("Solution  " + i);

for (int j = 0; j < tab.length; j++){
...
``````

to

``````for (int i = 0; i <= tab.length - 1; i++) {
int somme = 18;
System.out.println("Solution  " + i);

for (int j = i; j < tab.length; j++) {
...
``````

Notice the `int j = i` in the inner loop.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download