Распечатка башни чисел

Я исправил это. Решение: вместо того, чтобы давать ведущее изображение в ведущем атрибуте, добавьте его в тот же rowChildren. Разрыв пропадает!

List<Widget> rowChildren = [];

rowChildren.add(
    PaddingUtils.embedInPadding(
        new Image.asset(
          $imagePath,
        ),
        new EdgeInsets.only(right: 8.0)),
  );
1
задан LetsFailNoob 19 January 2019 в 18:59
поделиться

6 ответов

Вот решение, которое не требует двух функций версии 1:

public class numberTower {
    public static void main (String args[]) {
        numberTower t = new numberTower(5);
        System.out.println(t.numberTower (5));
    }
    static int c;
    static int nn;
    public numberTower (int n) {
        nn = n;
        c = 0;
    }

    String numberTower (int n) {
        if (n < 1) return "";                                        
        String tower = "";
        if (c < nn)
            tower += numberTower (n - 1);
        ++c;
        for (int i = n; i > 0; --i)
            tower += Integer.toString(i);
        tower += '\n';
        if (c >= nn)
            tower+=numberTower (n - 1);
        return tower;
    }
}

И версии 2:

public class numberTower {                                                                           
    public static void main (String args[]) {
        numberTower t = new numberTower(5);
        t.numberTower (5);
    }   
    static int c;
    static int nn; 
    public numberTower (int n) {
        nn = n;
        c = 0;
    }   

    void numberTower (int n) {
        if (n < 1) return;                                            
        String tower = ""; 
        if (c < nn) 
            numberTower (n - 1); 

        ++c;
        for (int i = n; i > 0; --i)
            System.out.print ("" + i);;

        System.out.println();
        if (c >= nn) 
            numberTower (n - 1); 
    }
}
0
ответ дан Gox 19 January 2019 в 18:59
поделиться

Это делает именно то, что вы хотите:

   //This is the method that will be called from some other class
   public static int printSequence(int n){
       return printSequence(1, n);
   }

   /*We define this method, because the following code snippet
    is used multiple times in the method 'printSequence(int, int)'
    This method will simply print the numbers 1 - length*/
   private static void printLooper (int length){
        for(int i=1; i<=length; i++)
            System.out.print(i);
        System.out.print("\n");
    }

    /*This method has the logic. We give it 2 integers as parameters:
     int start and int end. I think the names of the parameters are self-explanatory*/
    private static int printSequence(int start, int end){
        /*This is the TERMINATING condition, so it is placed first.
         This part is really important. Always be aware of what type of recursion
         you are using. More on this later..*/
        if ( end == 1 ) {
            printLooper(end);
            return 0;
        }

        //OK. So, if start is less than end, then print 1 - start
        if (start < end){
            printLooper(start);
            //then return method recursively, with start INCREMENTED by one
            return printSequence(start+1, end);
        }

        /*Now, if start is equal to end, print number 1 - start, but this time,
        return the method recursively with end DECREMENTED by one*/
        else if (start == end){
            printLooper(start);
            return printSequence(start, end-1);
        }

        /*Now if start is larger than end, then that means that we need to start
         printing the lower part of the 'number tree'. So, call printLooper()
         to print 1 - end.*/
        else if (start > end){
            printLooper(end);
            return printSequence(start, end-1);
        }
        return 0;
    }

Что касается типов рекурсии и почему важно знать, какой тип функции вы пишете, посмотрите этот удивительный урок .

0
ответ дан P. Soutzikevich 19 January 2019 в 18:59
поделиться

Вот код, который может быть вам полезен. Код выглядит следующим образом. Это довольно очевидно. Но я добавлю подробное объяснение, если оно покажется вам сложным.

public static int printSequence(int n) {
    return printSequence(1, n); //start printing upper triangle (1 to n)
}

public static int printSequence(int currentNumber, int lastNumber){
    for (int i = 1; i <= currentNumber; i++)
        System.out.print(i);          
    System.out.println();

    if(currentNumber<lastNumber) //if in upper triangle
        return printSequence(currentNumber+1, lastNumber);

    if(currentNumber>lastNumber) //if in lower triangle
        return printSequence(currentNumber-1, lastNumber);

    if(currentNumber==lastNumber) { //if the end of a triangle is reached

        if(lastNumber==1) {  //if the end of lower triangle is reached, exit the method
            return 0;
        } else {
            return printSequence(lastNumber-1, 1); //if the end of upper triangle is reached, start the lower triangle ( n-1 to 1)
        }

    }
    return 0;
}
0
ответ дан Tanmoy Krishna Das 19 January 2019 в 18:59
поделиться

Рекурсивное решение

public static int printSequence(int n,int count){
    if(count == 2*n){
        return 0;
    }
    else{
        if(count<=n){
            int i=1;
            while(i<=count)
            {
                System.out.print(i);
                i++;
            }
            System.out.println();
            return printSequence(n,count+1);
        }
        else{
            int i=1;
            while(i<=n-(count-n)) 
            {
                System.out.print(i);
                i++;
            }
            System.out.println();
            return printSequence(n,count+1);
        }
    }
}

printSequence (n, 1);

0
ответ дан Sanath Kumar 19 January 2019 в 18:59
поделиться

Я думаю, что это решение может работать, но оно использует 2 функции. У каждой функции есть рекурсия:

public static void printSequence(int n){
    printSequenceHelp1(1, n - 1);
    for (int i = 1; i <= n; i++)
        System.out.print(i);          
    System.out.println();
    printSequenceHelp2(n - 1);  
}

public static void printSequenceHelp1(int k, int n){
    if (k <= n){
        for (int i = 1; i <= k; i++)
            System.out.print(i);          
        System.out.println();
        printSequenceHelp1(k + 1, n);
    }   
}

public static void printSequenceHelp2(int n){
    if (n >= 1){
        for (int i = 1; i <= n; i++)
            System.out.print(i);          
        System.out.println();
        printSequenceHelp2(n - 1);  
    }   
}

Я уверен, что есть более элегантное решение только с одной функцией. Я постараюсь подумать об этом, когда, если найду, я опубликую это здесь.

0
ответ дан Netanel 19 January 2019 в 18:59
поделиться

Кажется, это работает. Примечания:

  • Вместо того, чтобы сам printSequence быть рекурсивным, он просто принимает предел (n) и действует как оболочка для вызова рекурсивного метода, начинающегося с 1.
  • Рекурсивный метод принимает текущую строку в качестве аргумента, поэтому код не должен восстанавливать строку из 1 каждый раз, он просто добавляет последнюю цифру.
  • Ошибка проверки для выдачи исключения, если (начальный) аргумент находится вне диапазона.
public static void main(String[] args) {
    printSequence(5);  // test value
}

private static void printSequence(int n) {
    if (n < 1 || n > 9) {
        throw new IllegalArgumentException("Argument must be in the range 1 to 9 inclusive.");
    }
    doRecursion(1, "", n);  // call recursive method with initial values
}

private static void doRecursion(Integer counter, String currentString, int limit) {
    String newString = currentString + counter.toString();
    System.out.println(newString);
    if (counter < limit) {
        doRecursion(counter + 1, newString, limit);
        System.out.println(newString);
    }
}
0
ответ дан Gord Thompson 19 January 2019 в 18:59
поделиться
Другие вопросы по тегам:

Похожие вопросы: