J
J
Jake Taylor2020-08-22 13:33:49
Java
Jake Taylor, 2020-08-22 13:33:49

How to replace recursion in Java code?

There is this code:

source

package com.company;

import java.util.*;

public class Main {

    static int TOTAL_POINTS = 4, POINTS_ON_LINE = 3;

    static int[] temp = new int[POINTS_ON_LINE];

    public static void main(String[] args) {
        int[] points = new int[]{1,2,3,4};

        System.out.println("Без повторений:");
        p1(0,0, points);
    }

    static void p1(int nowPosition, int sizeArray, int[] points) {
        if (nowPosition == POINTS_ON_LINE) {
            System.out.println("Выводим:");
            System.out.println(Arrays.toString(temp));
        } else {
            for(int i = sizeArray + 1; i <= TOTAL_POINTS; i++) {
                temp[nowPosition] = points[i-1];
                p1(nowPosition + 1, i, points);
            }
        }
    }
}



The output is a combination of numbers of 3:
Без повторений:
Выводим:
[1, 2, 3]
Выводим:
[1, 2, 4]
Выводим:
[1, 3, 4]
Выводим:
[2, 3, 4]


The program works as intended.
But you need to get rid of the recursive call to p1.
I tried like this, but it doesn't work. Why? What's wrong where?
How tried

package com.company;

import java.util.*;

public class Main {

    static int TOTAL_POINTS = 4, POINTS_ON_LINE = 3;

    static int[] temp = new int[POINTS_ON_LINE];

    public static void main(String[] args) {
        int[] points = new int[]{1,2,3,4};

        System.out.println("Без повторений:");
    }

    static void p1(int[] points) {
        int sizeArray = points.length;

        for(int i = sizeArray + 1; i < TOTAL_POINTS; i++, sizeArray = i) {
            int nowPosition = 0;

            if(nowPosition == POINTS_ON_LINE) {
                System.out.println("Выводим: " + Arrays.toString(temp));
            } else {
                temp[nowPosition] = points[i-1];
                nowPosition++;
            }
        }
    }
}

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question