Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Given a nonempty array of positive integers, "increment" it once as follows:

  • If all the array elements are equal, append a 1 to the end of the array. For example:

    [1] -> [1, 1]
    [2] -> [2, 1]
    [1, 1] -> [1, 1, 1]
    [3, 3, 3, 3, 3] -> [3, 3, 3, 3, 3, 1]
    
  • Else, increment the first element in the array that is the array's minimum value. For example:

    [1, 2] -> [2, 2]
    [2, 1] -> [2, 2]
    [3, 1, 1] -> [3, 2, 1] -> [3, 2, 2] -> [3, 3, 2] -> [3, 3, 3]
    [3, 4, 9, 3] -> [4, 4, 9, 3] -> [4, 4, 9, 4] -> [5, 4, 9, 4] -> [5, 5, 9, 4] -> ...
    

(Each -> represents one increment, which is all your program needs to do.)

Output the resulting incremented array.

The shortest code in bytes wins.

share|improve this question
    
Does 0 count as positive integer – Downgoat 2 days ago
10  
@Downgoat 0 is not ever positive on PPCG. If 0 was allowed, the term would be "non-negative" – ETHproductions 2 days ago

28 Answers 28

Jelly, 8 7 bytes

‘;ṀỤḢṬ+

Try it online! or verify all test cases.

How it works

‘;ṀỤḢṬ+  Main link. Argument: A

‘        Increment all elements of A.
  Ṁ      Yield the maximum of A.
 ;       Concatenate both results. Note that the appended maximum will be the 
         minimum of the resulting array if and only if all elements of A are equal.
   Ụ     Grade up; yield the indices of the resulting array, sorted by their
         corresponding values in that array.
    Ḣ    Head; extract the first index, which is the index of the first occurrence
         of the minimum. For an array of equal elements, this will be the index
         of the appended maximum.
     Ṭ   Untruth; for index i, yield an array of i-1 zeroes, followed by a 1.
      +  Add this array to A, incrementing the minimum or appending a 1.
share|improve this answer

Python 3, 62 53 51 50 bytes

Function which modifies the list passed to it (allowed by meta).

def F(a):a+=1//len({*a})*[0];a[a.index(min(a))]+=1

Try on repl.it!

-9 bytes thanks to Lynn for spotting that, because the array will be of positive integers, I can append '0' to the end of the array and have that incremented.

Special thanks to mbomb007 for golfing len(set(a)) to len({*a}), and Dennis for the floordiv trick!

share|improve this answer
    
@Lynn that's clever, thank you! – Flp.Tkc 2 days ago
    
Hmm. "Output the resulting incremented array". Does this qualify? – TuukkaX 2 days ago
    
I can't quite remember where, but I remember seeing a meta post that modifying a given list in place is allowed by default. I'll have a look for it @TuukkaX – Flp.Tkc 2 days ago
1  
In Python 3, you can use len({*L})<2 to find if all elements of a list are equal. – mbomb007 2 days ago
1  
a+=1//len({*a})*[0] should save a byte. – Dennis 2 days ago

Mathematica, 70 57 55 bytes

Virtually all of the improvement is due to Martin Ender, who kicks my ass at pattern matching approaches! Also JHM came up with essentially the same solution at essentially the same time. (byte count uses ASCII encoding)

±{p:x_ ..}:={p,1};±{x___,y_,z___}/;y≤x~Min~z:={x,y+1,z}

Defines a function ± taking one list argument. If that list argument contains some number of copies of the same element (detected by x_.. and named p), then output the list with a 1 appended. Otherwise, if that list argument has a special element y (with x being the zero or more elements before y, and z being the zero or more elements after y) which is at most the minimum of the other elements, then output the list with that y incremented. Any instance of the minimum element of the list will be matched by y, but fortunately Mathematica chooses the first one to act upon.

share|improve this answer
    
Because ± is a 2-byte character, your code is 59 bytes long. Also, there must be a space between x_ and .. because Mathematica interprets x_.. as x_. . (which throws errors). Plus, the infix form of Min (x~Min~z) would make this 2 bytes shorter (which makes this solution identical to one of mine :p ...) Welp you can take the credit because my edit was later than yours.... – JHM 2 days ago
    
Nah, Martin Ender gets most of my credit anyway. Why is ± two bytes? – Greg Martin 2 days ago
    
@GregMartin ± in UTF-8 (Mathematica uses UTF-8 by default; try $CharacterEncoding) is a two-byte character (U+00B1). – JHM 2 days ago
    
@JHM UTF-8 is not the default character encoding on Windows. Mathematica can read source files in a single-byte code page that includes ±. – Martin Ender 2 days ago
1  
@ASimmons My fresh Mathematica installation on Windows, which has $CharacterEncoding set to WindowsANSI which is CP1252 (which is sufficiently compatible with ISO 8859-1 for ± and · to be usable for a single byte). – Martin Ender yesterday

JavaScript (ES6), 61 bytes

a=>new Set(a).size>1?++a[a.indexOf(Math.min(...a))]:a.push(1)

Outputs by modifying its argument. I can't find a way to determine whether an array has only one unique item in less that 17 bytes, but suggestions are welcome.

Test snippet

f=a=>new Set(a).size>1?++a[a.indexOf(Math.min(...a))]:a.push(1)
g=a=>0 in a?console.log("Input:",`[${a}]`,"Output:",`[${f(a),a}]`):console.log("Invalid input")

g([1])
g([2])
g([1,1])
g([1,2,2,3])
g([2,2,2,3])
g([3,2,2,3])
g([3,3,2,3])
g([3,3,3,3])
g([3,3,3,3,1])
<input id=I value="1,2,2,3"><button  onclick="g(I.value.match(/\d+/g)||[])">Run</button>

Other attempts

Here are a few alternate ways of deciding whether the array has more than one unique input:

a=>a.some(x=>x-a[0])?++a[a.indexOf(Math.min(...a))]:a.push(1)
a=>a.some(x=>x-m,m=Math.min(...a))?++a[a.indexOf(m)]:a.push(1)

Both of the somes can be replaced with find as well. .sort would be shorter for finding the minimum, if the default sort wasn't lexicographical (why, JS, why?):

a=>new Set(a).size>1?++a[a.indexOf(a.sort()[0])]:a.push(1)
// Instead we have to do:
a=>new Set(a).size>1?++a[a.indexOf(a.sort((x,y)=>x-y)[0])]:a.push(1)

I tried recursion to find the minimum, but it turned out way longer:

f=(a,n=1,q=a.indexOf(n))=>~q?a.some(x=>x-n)?++a[q]:a.push(1):f(a,n+1)

And here's a string-based solution which seemed like a good idea at first: (input is given in array format in a string, e.g. "[1,2,3]")

a=>a.replace(m=/(\d+),(?!\1)/.test(a)?Math.min(...eval(a)):']',+m+1||",1]")
share|improve this answer
    
Is using a.find(n=>n==Math.min(...a)) shorter? – Downgoat 2 days ago
    
@Downgoat I'm not sure how I'd use that, as it returns the item rather than the index – ETHproductions 2 days ago
    
yeah >_> whoops, I missed your ++ and didn't realize you needed a reference – Downgoat 2 days ago

C++, 178 176 174 155 142 bytes

#include<list>
#include<algorithm>
auto i=[](auto&l){auto e=end(l),b=begin(l);l.size()^count(b,e,*b)?++*min_element(b,e):(l.push_back(1),0);};

ungolfed

#include <list>
#include <algorithm>
#include <iostream>
using namespace std;

void i(list<int>& l) {
    auto e = l.end(), b = l.begin();

    if (l.size() == count(b, e, l.front())) {
        l.push_back(1);
    } else {
        ++*min_element(b, e);
    }
}

int main() {
    list<int> s = {4, 4, 9, 4};

    //invoke like this
    i(s);

    for (auto o:s)
        std::cout << o << ' ';
    std::cout << std::endl;
}

This is my first time playing golf, help is appreciated.

EDIT: forgot to mention you have to compile it with at least -std=c++11 -std=c++14

EDIT2: I realized i can leave out the space in the includes #include <list>

EDIT3: saved two more bytes by replacing l.begin() by begin(l)

EDIT4: saved another 19(!) bytes thanks to @Quentin (see his comment)

EDIT5: Quentin shaved off 13 more bytes, thanks!

share|improve this answer
5  
I can't help you with C++, but I can say: Welcome to PPCG! – Zgarb 2 days ago
1  
I think you don't need the spaces in the #include lines. – Christian Sievers 2 days ago
    
Oh thank you I just realized it myself :) – Neop 2 days ago
1  
Replacing the function with a lambda (auto i=[](auto&l){...};) saves one byte (more if we count the return type you forgot ;) ), using ^ instead of == and swapping the operands saves another. std::list's iterators are certainly std:: classes, so you can drop std:: from both std::count and std::min_element thanks to ADL (-10). l.front() is also *b (-7). I end up with a 120-byte auto i=[](auto&l){auto e=end(l),b=begin(l);l.size()^count(b,e,*b)?void(++*find(b,e,‌​*min_element(b,e))):‌​l.push_back(1);}; :) – Quentin 16 hours ago
1  
While we're at it, the documentation for std::min_element states that it returns the first smallest element, so the find() is superfluous, that's 11 bytes. In the conditional, using a pair of parentheses and the comma operator to coerce the right expression to int is shorter than casting the left one to void by 2 bytes. This leads to auto i=[](auto&l){auto e=end(l),b=begin(l);l.size()^count(b,e,*b)?++*min_element(b,‌​e):(l.push_back(1),0‌​);};, 142 bytes :) – Quentin 3 hours ago

05AB1E, 21 20 16 bytes

Saved 4 bytes thanks to Adnan.

DÙgi0¸«}ÐWksgÝQ+

Try it online!

Explanation

                      # input = [3,2,1] used as example
D                     # duplicate input
 Ùgi                  # if all elements are equal
    0¸«}              # append 0
        Ð             # triplicate list
                      # STACK: [3,2,1], [3,2,1], [3,2,1]
         Wk           # index of minimum element
                      # STACK: [3,2,1], [3,2,1], 2
           s          # swap top 2 elements of stack
                      # STACK: [3,2,1], 2, [3,2,1]
            g         # length of list
                      # STACK: [3,2,1], 2, 3
             Ý        # range [0 ... length]
                      # STACK: [3,2,1], 2, [0,1,2,3]
              Q       # equal
                      # STACK: [3,2,1], [0,0,1,0]
               +      # add
                      # OUTPUT: [3,2,2]
share|improve this answer
    
I think that DÙgi0¸«}ÐWksgÝQ+ also works. – Adnan 2 days ago
    
@Adnan: Aah, nice idea using ÝQ with k. Thanks! – Emigna 2 days ago

Scratch, 25 34 blocks + 7 6 bytes

Program

Takes input as a predefined array of integers. Note that arrays are 1-indexed in Scratch.

In Python, this would look like: (Note that unlike Scratch, Python is 0-indexed)

lowval = 0
hival = 0
n = 1
for i in range(len(input)):
    if(input[i] < input[lowval]):
        lowval = i
    if(input[i] > input[hival]):
        hival = i
    # No increment statement needed because python.
if(lowval == hival):
    input.append(1)
else:
    input[lowval] += 1
print(input)
share|improve this answer
    
Golfing comments please? – OldBunny2800 2 days ago
    
why do you declare fval? – Christoph 2 days ago
    
It appears to me that Scratch is just Python in plain text with colors... – Stewie Griffin 2 days ago
    
And 1-indexed arrays and no elif statements! – OldBunny2800 2 days ago
1  
Good point @Christoph! It was part of an earlier version that got golfed out. Editing. – OldBunny2800 2 days ago

Mathematica, 56 bytes

±{b:a_ ..}:={b,1};±a_:=a/.{p___,b:Min@a,q___}:>{p,b+1,q}

Uses named function ±. Uses ISO8859-1 encoding

Alternative solutions (58 bytes)

±{b:a_ ..}:={b,1};±{p___,b_,q___}/;b<=p~Min~q:={p,b+1,q}
(* @GregMartin and I both independently came up with this above solution *)

±{b:a_ ..}:={b,1};±a:{p___,b_,q___}/;b==Min@a:={p,b+1,q}

Usage

±{1, 1}

{1, 1, 1}

±{3, 4, 5}

{4, 4, 5}

share|improve this answer

Haskell, 71 70 62 bytes

f(a:b)|(x,y:z)<-span=<<(<).minimum$a:b++[0|all(a==)b]=x++y+1‌​:z

@Zgarb saved 8 bytes, thanks!

When I started I hoped for some elegant tying-the-knot trickery, but @Zgarb's way is just as amazing.

share|improve this answer
    
Some restructuring, 62 bytes: f(a:b)|(x,y:z)<-span=<<(<).minimum$a:b++[0|all(a==)b]=x++y+1‌​:z – Zgarb 2 days ago
    
@Zgarb Just wow! – Christian Sievers 2 days ago
    
Ugh, my brain fails to infer the type for the monad instance of functions – Angs yesterday
    
@Angs The Monad is (->)r, which applied to a type is (->)r a = r->a. Then from the types return:: a->r->a and (>>=)::(r->a)->(a->r->b)->(r->b) their implementation is (dare I say it?) obvious: return=const and m>>=f = \r->f(m r)r. The latter is exactly what is needed to express something like span(predicate_depending_on l)l while mentioning l only once. Now I only need to remember it when I need it. – Christian Sievers yesterday
    
@Angs You can find this trick, and many more, in our Haskell golf tips collection. – Zgarb yesterday

J, 25 22 bytes

(+~:*[=<./)@,0#~1=#@~.

Evaluates to an anonymous verb. Try It Online!

Explanation

(+~:*[=<./)@,0#~1=#@~.  Input is y.
                  #@    Is the length of
                    ~.   deduplicated y
                1=       equal to 1?
            ,0#~        Append that many 0s to y (one or none).
(         )@            Call the result z and apply this verb to it:
      =                  take the bit array of equality
     [                   between z
       <./               and its minimum element,
    *                    multiply that element-wise by
  ~:                     the bit array of first occurrences in z
 +                       and add the result to z.
share|improve this answer

C#, 123 121 120 79 77 bytes

using System.Linq;l=>{if(l.All(o=>o==l[0]))l.Add(0);l[l.IndexOf(l.Min())]++;}

Modifies the argument passed to the function.

Thanks to Cyoce for saving 3 bytes! -> !Any to All, +=1 to ++.

Thanks to TheLethalCoder for saving a whopping 43 bytes! -> Removed method signature code. Removed parenthesis around the parameter list.

share|improve this answer
    
could you replace !l.Any(o=>o!=l[0])) with l.All(o=>o==l[0])? – Cyoce 2 days ago
    
@Cyoce It indeed does. I thought of the same thing, but wrote Any instead of All and was in the thought, that it doesn't work :D Thanks! – TuukkaX 2 days ago
2  
Does C# not have ++? – Cyoce 2 days ago
    
@Cyoce It does, thanks! – TuukkaX 2 days ago
    
You can compile to a Action<List<int>> to remove all of the method signature code – TheLethalCoder yesterday

MATL, 16 bytes

t&=?1h}t2#X<wQw(

Try it online! Or verify all test cases

How it works

t         % Take input implicitly. Duplicate
&=        % Matrix of all pairwise equality comparisons
?         % If all comparisons were true
  1h      %   Append 1 to the original copy ofthe array
}         % Else
  t       %   Duplicate array
  2#X<    %   Push minimum and index of its first occurrence
  wQw     %   Swap, increment, swap (adds 1 to the minimum)
  (       %   Assign the incremented minimum to that position
          % End if implicitly. Display implicitly
share|improve this answer

Perl 6, 46 bytes

{.[[==]($_)??.elems!!.first(*==.min,:k)]++;$_}

(modifies the input Array, and returns it)

Expanded:

{     # bare block lambda with implicit parameter 「$_」

  .[      # use the following as an index into the array

      [==]( $_ )    # reduce the array with 「&infix:<==>」

    ??              # if they are equal

      .elems        # the value past the end ( 「.end+1」 would also work )

    !!              # else

      .first(       # find the first value
        * == .min,  # where the element is equal to the minimum
        :k          # return the key rather than the value
      )

  ]++;              # increment it ( auto vivifies if it doesn't exist )

  $_                # return the modified array
}

share|improve this answer

Jelly, 9 bytes

;1µ‘i¦E?Ṃ

Thanks to Dennis for the -2 bytes.

Body must be at least 30 characters; you entered ... .

share|improve this answer
    
If you have extra characters to enter in the body, it's always worth explaining the code, which helps everyone to understand it and makes the answer more interesting :) – Alfie Goodacre 21 hours ago

Mathematica, 53 bytes 57 bytes 59 bytes

If[Equal@@#,#~Join~{1},x=#;x[[#~FirstPosition~Min@#]]++;x]&
share|improve this answer
7  
That's 57 bytes. and are a 3-byte characters. Also, your code does not work because {##,1} part implies that the input is separate integers (i.e. f[1, 2, 3]) but the x=# part implies that the input is a List (i.e. f[{1, 2, 3}]). A quick fix would be to change x=# to x={#} and accept raw integers as input, making your code 59 bytes long. – JHM 2 days ago
    
Good catch! I didn't realize the distinction between bytes and character count, I just saw this suggestion and figured it was valid. It seems there are a lot of answers that give the character count but if I save them in Notepad++ I get a higher byte count (for example the Jelly answer). I see your answer specifies an encoding, is there somewhere you'd recommend for me to learn about this? – ngenisis yesterday
1  
I think you mean Equal@#, although #==## is shorter. – Martin Ender yesterday
    
You're right. I made a change per @JHM to accept multiple arguments rather than a list but didn't propagate the change everywhere. I've gone back to accepting a list since that is more in line with the prompt. – ngenisis 17 hours ago

Ruby, 46 bytes

->a{a.uniq.size<2?a<<1:a[a.index(a.min)]+=1;a}

I feel like there's a better way to check if all elements are the same than a.uniq.size<2, but I'm too lazy to find it.

share|improve this answer
5  
a.uniq[1] will be truthy iff there are distinct values. – histocrat 2 days ago
    
You can save a byte by turning a[a.index(a.min)] into a[a.index a.min] – Cyoce 2 days ago

Octave, 69 67 64 bytes

It was actually shorter to make this a complete named function than using both input and disp.

Saved 3 bytes thanks to Luis.

function x=f(x)
[a,b]=min(x);if any(x-a),x(b)++;else x=[x,1];end

Old answer, not using a function:

[a,b]=min(x=input(''));if any(x-a),x(b)++;else x(end+1)=1;end;disp(x)
share|improve this answer

R, 97 bytes

if(all((a=scan())==a[1])){a=c(a,1)}else{while(!all(a==a[1])){a[which(a==min(a))][1]=min(a)+1}};a

Too bad that the synthax x=+1 doesn't exist in R !

Ungolfed :

if(all((a=scan())==a[1]))
{
    a=c(a,1)
}
else
{
    while(!all(a==a[1]))
    {
        a[which(a==min(a))][1]=min(a)+1
    }
a
share|improve this answer

Pyth, 16 bytes

?tl{QXxQhSQQ1+Q1

A program that takes input of a list and prints the result.

Test suite

How it works

?tl{QXxQhSQQ1+Q1  Program. Input: Q
?                 If:
  l                The length
   {Q              of Q deduplicated
 t                 - 1
                   is non-zero:
     X     Q1       Increment in Q at index:
      xQ             Index in Q of
        h            the first element
         SQ          of Q sorted (minimum)
                  else:
             +     Append
               1   1
              Q    to Q
                   Implicitly print                    
share|improve this answer

Haskell, 93 bytes

f z|and$(==)<$>z<*>z=z++[1]|1>0=z#minimum z where(x:z)#m|x==m=x+1:z;(x:z)#m|1>0=x:z#m;[]#_=[]

Ungolfed:

incrementArray :: [Int] -> [Int]
incrementArray xs | and [x == y | x <- xs, y <- xs] = xs ++ [1]
                  | otherwise = g xs (minimum xs)
     where g (x:xs) m | x == m = (x + 1):xs
           g (x:xs) m | otherwise = x:g xs m
           g [] _ = []

Initial attempt, will try to come up with something more sophisticated later.

share|improve this answer
1  
Why not make a separate function instead of using where? – Michael Klein 2 days ago

Wonder, 44 bytes

@[dp1unq#0?:=#[:0(iO f\min#0)#0+1f]#0?++#0 1

This is not what I had in mind when I made this language... It's literally worse than Perl in terms of readability!

Usage:

(@[dp1unq#0?:=#[:0(iO f\min#0)#0+1f]#0?++#0 1])[3 4 9 3]

Explanation

More readable:

@[
  dp 1 unq #0
    ? set #[
            get 0 (iO f\ min #0) #0
            + 1 f
           ] #0
    ? con #0 1
 ]

Basically checks if dropping 1 item from the unique subset of the argument makes the list empty. If not, then we increment the minimum of the array. Otherwise, we simply concatenate 1 to the argument.

share|improve this answer

Kotlin, 75 bytes

fun a(s:MutableList<Int>){if(s.toSet().size<2)s+=0;s[s.indexOf(s.min())]++}

Modifies the function argument.

Damn you strong typing! :MutableList<Int> accounts for 17 bytes alone. I don't think there is a solution where the type can be inferred, unfortunately.

share|improve this answer

jq, 44 characters

if unique[1]then.[index(min)]+=1else.+[1]end

Sample run (-c (--compact-output) option used only here for readability):

bash-4.3$ jq -c 'if unique[1]then.[index(min)]+=1else.+[1]end' <<< '[3,1,1]'
[3,2,1]

bash-4.3$ jq -c 'if unique[1]then.[index(min)]+=1else.+[1]end' <<< '[3,2,1]'
[3,2,2]

bash-4.3$ jq -c 'if unique[1]then.[index(min)]+=1else.+[1]end' <<< '[3,2,2]'
[3,3,2]

bash-4.3$ jq -c 'if unique[1]then.[index(min)]+=1else.+[1]end' <<< '[3,3,2]'
[3,3,3]

bash-4.3$ jq -c 'if unique[1]then.[index(min)]+=1else.+[1]end' <<< '[3,3,3]'
[3,3,3,1]

On-line test:

share|improve this answer

TI-Basic, 53 bytes

If min(not(ΔList(Ans
Then
Ans->L1
cumSum(1 or Ans
min(Ans+ᴇ9(L1≠min(L1
L1(Ans)+1->L1(Ans
Else
augment(Ans,{1
End
share|improve this answer

Java, 155 bytes

a->{List b=a;Collections.sort(b);if(new Set(a).size()==1)a.add(1);else for(int i=0;i<b.size();)if(a.get(i)==b.get(0)){a.set(i,a.get(i)+1);break;}return a;}
share|improve this answer
    
AFAIK, you can't do new Set(a), as Set is an interface. You'd have to do something like new HashSet(a) Also, you have to include imports in your byte count. – Xanderhall 19 hours ago

Matlab, 83, 77 Bytes

function a=x(a)
if(~nnz(a(a~=a(1))));a=[a,1];else[~,I]=min(a);a(I)=a(I)+1;end

I'm relatively new to code golf so please be kind! I tried to use anonymous functions but googling says you can't use if/else statements and matlab doesn't have ternary operators, so this is the best i felt I could do.

Edit: Corrected and shortened thanks to stewie-griffin.

share|improve this answer
    
Welcome to PPCG! There are some flaws in this code. sum(a)/length(a)==a(1) doesn't guarantee that all elements are equal, it only shows that the average is equal to a(1). A simpler way to do this would be mean(a)==a(1). numel is one byte shorter than length, but since you know all values are positive, you can use nnz which is even shorter (it would still not give the correct result in this challenge, but it's shorter at least :P ). If you take the min(a) call in front of the loop, you may use both outputs from it and check is all elements of a are equal to min(a). – Stewie Griffin yesterday
    
You are right! it fails when the mean is equal the number in the first element. I think my new one is correct though and also shorter. The logic is that if the remaining elements don't equal the first element, a(a~=a(1)) returns the remaining elements which by definition is greater than 0 in a non-same array. Then counting and not should give the correct logic I think. If it's still wrong please let me know, I've only been coding for a few years and I still have a long ways left. – O.Morgan yesterday

PHP, 79 bytes

function i($a){max($a)>($n=min($a))?$a[array_search($n,$a)]++:$a[]=1;return$a;}

I think this needs no explanation.

share|improve this answer

Groovy - 45 bytes

A groovy closure which accepts a list of Integer as input - please note this modifies the input List.

{o->(o-o[0])?o[o.indexOf(o.min())]+=1:o<<1;o}

Test cases can be seen here:

http://ideone.com/9vRd9e

Alternative of 56 bytes if the code needs to work with int[] or List<Integer>:

{o=it.toList();(o-o[0])?o[o.indexOf(o.min())]+=1:o<<1;o}

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.