Square into Squares. Protect trees!

kata programming

مساله:

خواهر کوچک من با وظیفه زیر از مدرسه بازگشت:

یک کاغذ مربع شکل را باید به قطعاتی طوری برش بزند که وقتی کنار هم قرار می گیرند مربع هایی را تشکیل می دهند که اضلاع آن دنباله ای از اعداد به صورت صعودی را تشکیل می دهد. در ابتدا بسیار سرگرم کننده بود اما کم کم از دیدن انبوهی از کاغذ پاره شده خسته شدیم. بنابراین تصمیم گرفتیم برنامه ای بنویسیم که بتواند به ما کمک کند و از درختان محافظت کند.

وظیفه:

یک عدد صحیح مثبت انتگرال گرفته شده (n) به شما داده می شود، یک دنباله اعداد صعودی را برگردانید که جمع به توان ۲ آنها برابر عدد n2 باشد.

اگر چندین راه حل وجود دارد (و خواهد داشت)، باید نتیجه را با بزرگترین مقادیر ممکن بازگردانید:

مثال ها:

decompose(11) باید دنباله [1,2,4,10] را برگرداند. توجه داشته باشید که در واقع دو روش برای تجزیه ۱۱۲ وجود دارد.

11² = 121 = 1 + 4 + 16 + 100 = 1² + 2² + 4² + 10² ولی نباید آرایه [2,6,9] برگردانده شود، بخاطر اینکه ۹ از 10 کوچکتر است.

برای decompose(50) آرایه [1, 1, 4, 9, 49] را نباید برگردانید چون [1, 3, 5, 8, 49] وجود دارد و آرایه [1, 1, 4, 9, 49] افزایش توالی محض را رعایت نکرده است.

نکته:

عبارت های [n] و [1,1,…,1] راه حل های معتبری نیستند. اگر راه حل معتبری وجود ندارد باید null برگردانید.

تابع “decompose” یک عدد صحیح مثبت می گیرد و تجزیه N = n² را به صورت زیر بر می گرداند:

[x1 … xk]

مثال های دیگر:

decompose 50 returns "1,3,5,8,49"
decompose 4  returns "Nothing"

نکته:

معمولا xk می تواند n-1 شود.


Description:

My little sister came back home from school with the following task: given a squared sheet of paper she has to cut it in pieces which, when assembled, give squares the sides of which form an increasing sequence of numbers. At the beginning it was lot of fun but little by little we were tired of seeing the pile of torn paper. So we decided to write a program that could help us and protects trees.

Task

Given a positive integral number n, return a strictly increasing sequence (list/array/string depending on the language) of numbers, so that the sum of the squares is equal to n².

If there are multiple solutions (and there will be), return as far as possible the result with the largest possible values:

Examples

decompose(11) must return [1,2,4,10]. Note that there are actually two ways to decompose 11², 11² = 121 = 1 + 4 + 16 + 100 = 1² + 2² + 4² + 10² but don’t return [2,6,9], since 9 is smaller than 10.

For decompose(50) don’t return [1, 1, 4, 9, 49] but [1, 3, 5, 8, 49] since [1, 1, 4, 9, 49] doesn’t form a strictly increasing sequence.

Note

Neither [n] nor [1,1,1,…,1] are valid solutions. If no valid solution exists, return nil, null, Nothing, None (depending on the language) or “[]” (C) ,{} (C++), [] (Swift, Go).

The function “decompose” will take a positive integer n and return the decomposition of N = n² as:

[x1 … xk] or

“x1 … xk” or

Just [x1 … xk] or

Some [x1 … xk] or

{x1 … xk} or

“[x1,x2, … ,xk]”

depending on the language (see “Sample tests”)

Note for Bash

decompose 50 returns "1,3,5,8,49"
decompose 4  returns "Nothing"

Hint

Very often xk will be n-1.


public class Decompose {
  
  private String tryDecomp(long nb, long rac) {
    if (nb == 0) return "";
    String l = null;
    long i = rac;
    while (i >= (long)Math.sqrt(nb/2.0) + 1) {
      long diff = nb - i * i;
      rac = (long)Math.sqrt(diff);
      l = tryDecomp(diff, rac);
      if (l != null) { return l + " " + i; }
      i -=1;
    }
    return null;
  }
  public String decompose(long n) {
    String l = tryDecomp(n * n, (long)Math.sqrt(n * n - 1));
    return l != null ? l.trim() : l;
  }
}
public class Decompose {

  public static String decompose(long n) {
    return indecompose(n,n*n);
  }
  
  public static String indecompose(long n,long sum) {
    for(long i=n-1;i>=1;i--) {
      long divlater = sum - i*i;
      if(divlater == 0) {
        return ""+i;
      }
      if(divlater > 0) {
        String res = indecompose(i, divlater);
        if(res  != null) {
          return res + " " + i;
        }
      }
    }
    return null;
  }
}
public class Decompose {

  public String decompose(long n) {
    String answer = " ";
    loop: for(int i = 1; i < n; i++)
    {
      if (i == n - 1) return null;
      long x = n - i, y = n * n;
      answer += x;
      while(y > 0) { 
        y -= x * x;
        while (x > 0 && y < x * x) x--;
        if (x == 0) break;
        answer = " " + x + answer;
      }
      String[] arr = answer.split(" ");
      for (int j = 0; j < arr.length - 1; j++)
        if (arr[j].equals(arr[j+1])) {
        answer = " "; 
        continue loop; 
      }
      return answer.trim();
    }
    return "code";
  }
}
public class Decompose {

    public String decompose(long n) {
        StringBuilder t = dc(n * n, n - 1);
        return t == null ? null : t.toString();
    }

    public StringBuilder dc(long remainer, long x) {
        for (; x > 0; x--) {            
            long diff = remainer - x * x;
            if (diff == 0) {
                return new StringBuilder(String.valueOf(x));
            }
            if (diff > 0) {
                StringBuilder t = dc(diff, Math.min(x - 1, (long) (Math.sqrt(diff))));
                if (t != null) {
                    t.append(" " + x);
                    return t;
                }
            }
        } //for
        return null;
    }
    
}
// If no valid solution exists return null
import java.util.ArrayList;
import java.util.List;
import java.util.Collections;
/**
 *
 * @author fmauz
 */
public class Decompose {

    private List<String> result = new ArrayList<>();

    public String decompose(long n) {
        result.clear();
        if (n <= 2) {
            return null;
        }
        long startValue = n;

        while (startValue >= 2) {
            try {
                if (n <= 1) {
                    return null;
                }
                result.clear();
                getNext(startValue - 1, n * n);
                startValue = 0;
            } catch (Exception e) {
                startValue--;
                result.clear();
            }
        }
        if (result.isEmpty()) {
            return null;
        } else {
            List<Integer> intResult = new ArrayList<>();
            for (String s : result) {
                intResult.add(Integer.parseInt(s));
            }
            Collections.sort(intResult);
            List<String> stringResult = new ArrayList<>();
            for (int s : intResult) {
                stringResult.add(String.valueOf(s));
            }
            return String.join(" ", stringResult);
        }

    }

    private long getNext(long n, long squaredValue) throws Exception {
        if (squaredValue == 0) {
            return n;
        }

        if (squaredValue == 1) {
            result.add(0, "1");
            return n;
        }

        long v = squaredValue - (n) * (n);
        long b = (long) Math.sqrt(v);
        result.add(0, String.valueOf(n));

        if ((b == 1 && v > 1) || result.contains(String.valueOf(b))) {
            throw new Exception("Not computable");
        }
        return getNext(b, v);
    }
    }
import java.util.*;
public class Decompose {

    public String decompose(long n) {
        long square = n * n;
        ArrayList<String> result = new ArrayList<>();
        for (long i = n - 1; i > 0; i--) {
            long currentSum = i * i;
            for (long j = i - 1; j > 0; j--) {
                if (j * j + currentSum <= square) {
                    currentSum += j * j;
                    result.add(String.valueOf(j));
                    if (currentSum == square) {
                        Collections.reverse(result);
                        result.add(String.valueOf(i));
                        return String.join(" ", result);
                    }
                }
            }
            result.clear();
        }
        return null;
    }
}
import java.util.*;
public class Decompose {

  public String decompose(long n) {
    
    return Decompose.dec(n-1, n*n, n);
  }
  
  private static String dec(long n, long x, long prev){
    while (n>0){
      long diff = x - n*n;
      if (n == 0 || n >= prev || diff < 0) return null;
      if (diff == 0){
        String nums = "";
        nums += n;
        return nums;
      } else {
        long y = (long) Math.floor(Math.sqrt(diff));    //  y is the next biggest int that has a square within the difference
        String nums = Decompose.dec(y, diff, n);
        if ( nums == null ){
          n--;
        } else {
          nums += " " + n;
          return nums;
        }
      }
    }
    return null;
  }
  
}
import java.util.*;

public class Decompose {

  public String decompose(long n) {
    StringBuffer arr = new StringBuffer();
    int count = 1;
    long tmp = n - count, n_new = n; 
    
    if (n <= 3)
      return null;  
      
    n *= n;  
      
    while(n != 0){
      if (n - tmp*tmp >= 0){
        n -= tmp*tmp;
        arr.append(" " + tmp); 
      }
      tmp--;
      
      if (tmp == 0 && n != 0){
        count++;
        tmp = n_new;
        tmp -= count;
        n = n_new * n_new;
        arr = arr.delete(0, arr.length());

        if (tmp == 1)
          return null;
      }
    }
  
    return reverseArray(arr.toString());
  }
  
  public String reverseArray(String s) {
        String[] st = s.split(" ");
        int len = st.length - 1;
        for (int i = 0; i < st.length / 2; i++){
            String tmp = st[len - i];
            st[len - i] = st[i];
            st[i] = tmp;
        }
        return String.join(" ", st).trim();
    } 
}

دیدگاهتان را بنویسید