-8

Input: any number in 1-15 or 64-79 range which is a sum of either (1, 2, 4, 8, 64) in any combination

Output: an array of integers from this list: (1, 2, 4, 8, 64) the sum of which equals the input number.

e.g.

  • input 72, output array(8, 64)
  • input 13, output array(1, 4, 8)
Stack
  • 348
  • 3
  • 17
  • 5
    We are not a code writing service. Please show us what you already have tried. – Rizier123 May 08 '15 at 19:33
  • I tried a knapsack problem approach, but it seems like an overkill for the task. – Stack May 08 '15 at 19:39
  • Show us your code/attempts! Just edit your question and add your code and where you are stuck! – Rizier123 May 08 '15 at 19:40
  • @StackExchanger You already didn't showed any effort in your last question: http://stackoverflow.com/q/30108691 and SO is not a code writing service. Show your code and where you are stuck and need help. – Rizier123 May 08 '15 at 19:57
  • 2
    This is a simple example of converting a number to binary. Read about how to do that. – mkasberg May 08 '15 at 19:59
  • Just to add this here: I'm going to assume that for your second example the output should be: `1, 4, 8` and not `1, 2, 8` – Rizier123 May 08 '15 at 20:09

2 Answers2

1

Since you have not included your code in the question, no one can help you with your code. But here is a general approach without any code that should work for this problem.

Start with your input number and an empty array to hold the sum elements. Iterate over your array of addends in descending order, appending each one to your sum array and subtracting it from the input number until the input number reaches zero.

Don't Panic
  • 41,125
  • 10
  • 61
  • 80
  • Try to write some code that does this. If it works, great. If it doesn't, edit it into your question and people will be much more likely to help you. – Don't Panic May 08 '15 at 20:13
  • In other words: If OP wants his code without doing something he will need to hire a developer. (Also I kinda doubt it that he wants to do any work, since he already didn't showed any effort in his last question: http://stackoverflow.com/q/30108691) – Rizier123 May 08 '15 at 20:19
  • The way I interpreted it, this question was not asking for help with code, but for help producing a usable algorithm, so I thought it was answerable. If OP wants help debugging/understanding code, then obviously the code must be provided in the question. – Don't Panic May 08 '15 at 20:27
  • 1
    @StackExchanger Not the answer is the problem here, it's your question, which isn't complete – Rizier123 May 08 '15 at 22:24
-2

mkasberg provided the solution:

   $in = 72;
   $out = array();
   $a = array_reverse(str_split((string)decbin($in)));
    foreach($a as $k => $v){
       if ($v != "0") array_push($out, pow(2,$k));
    }
Community
  • 1
  • 1
Stack
  • 348
  • 3
  • 17