Match up to 10 in an array

Python 2.7 (70)

y=input()
while y:
 g=10-y.pop()
 if g in y:y.remove(g);print(g,10-g)

Testcases:

$ echo '[1, 2, 3, 4, 5, 5, 6, 7]' | python p.py
(3, 7)
(4, 6)
(5, 5)

$ echo '[1,2,3,4,5]' | python p.py

$ echo '[5,5,5,5,5]' | python p.py
(5, 5)
(5, 5)

$ echo '[1,2,3,3,4,5,6,7]' | python p.py
(3, 7)
(4, 6)

$ echo '[9,8,7,6,4,4,3,1]' | python p.py
(9, 1)
(7, 3)
(6, 4)

One byte extra for the nice parenthesis.


GolfScript, 45 42 37 chars

~{([.~11+.])@{1$=.{2$p!\}*!},\;\;.}do

The new approach does also take arrays with a single item as input. Moreover, it is several chars shorter.

Previous version:

~{$(\)@.2$+10-.{0>{\}*;+}{;[\]p}if.,1>}do;

The algorithm used in this code is described as follows:

  • Sort the array.
  • Take the sum of the first and the last item.
    • If the sum is 10 print both numbers and remove them from the array.
    • If the sum is greater than 10, discard the larger number.
    • If the sum is less than 10, discard the smaller number.
  • Loop until the array contains only a single digit or is even empty.

The code expects an array of at least two digits on STDIN.

Examples (see online):

>[9 8 7 6 4 4 3 1]
[1 9]
[3 7]
[4 6]

>[5 5 5 5 5]
[5 5]
[5 5]

Javascript, 188 183 181 153 141 121 123 112 105 98 chars

Golfing in JS is somewhat difficult, but I just wanted to have a bash on this problem, so here's the code:

for(a=eval(prompt(i=o=[]));k=a[j=++i];)for(;p=a[--j];)k+p-10||(k=a[i]=a[j]=-o.push([p,k]));console.log(o)

Input: e.g. [1,2,3,3,4,5,6,7]. Output e.g. [[4,6],[3,7]] to the console.

105->98: Used Daniel's awesome algorithm to completely rewrite the code! See his answer for a readable algorithm. Completely messed up stuff so reverted to 105 chars.

112->105: Initialised i to zero, used output of o.push to set k (k=a[i]=a[j]=-o.push...) and logged output to console instead of alerting to eliminate "["+ and +"]" since the console outputs nicely already.

123->112: Now removed outer brackets in output, since golfscript may :) Also finally applied suggestion of removing |=0.

121->123: Changed o+="("+p+","+k+")," to o.push("("+[p,k]+")") (adds 2 chars :( ) and made o an array instead of a string (o=""->o=[]). Now output isn't wrong anymore (like ((5,5),(5,5),)).

141->121: From now on assumed that the question meant that we could get input in the language's array format, which in JS's case is [a,b,c,...] and made o, the output "accumulator" a string instead of an array (o.push(...),->o+=...,).

153->141: Reset array entries instead of removing them after usage.

181->153: Applied changes to u=[], rearranged loops, a[i]&a[j]->temp vars, converted if logic and converted int logic to a[i]|=0.

183->181: Replaced i<=0 with i+1 and the same for j.

188->183: Placed o=[] inside prompt() (;) and replaced for(j=i; with for(j=i-1; (i==j&&).

(Thanks mellamokb, Paul Walls and ryan!)

Tags:

Code Golf