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.

  • \$\begingroup\$ Does 0 count as positive integer \$\endgroup\$ – Downgoat Nov 28 '16 at 23:14
  • 20
    \$\begingroup\$ @Downgoat 0 is not ever positive on PPCG. If 0 was allowed, the term would be "non-negative" \$\endgroup\$ – ETHproductions Nov 28 '16 at 23:23

37 Answers 37


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.

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!

  • \$\begingroup\$ Hmm. "Output the resulting incremented array". Does this qualify? \$\endgroup\$ – Yytsi Nov 28 '16 at 20:02
  • \$\begingroup\$ 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 \$\endgroup\$ – FlipTack Nov 28 '16 at 20:04
  • \$\begingroup\$ @TuukkaX I'm not entirely sure. It seems ok but I'll defer to the meta concensus about modifying arrays in place, if there is one. \$\endgroup\$ – Calvin's Hobbies Nov 28 '16 at 20:04
  • 1
    \$\begingroup\$ In Python 3, you can use len({*L})<2 to find if all elements of a list are equal. \$\endgroup\$ – mbomb007 Nov 28 '16 at 21:20
  • 1
    \$\begingroup\$ a+=1//len({*a})*[0] should save a byte. \$\endgroup\$ – Dennis Nov 29 '16 at 0:17

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")

<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:


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:


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]")

  • \$\begingroup\$ Is using a.find(n=>n==Math.min(...a)) shorter? \$\endgroup\$ – Downgoat Nov 28 '16 at 23:13
  • \$\begingroup\$ @Downgoat I'm not sure how I'd use that, as it returns the item rather than the index \$\endgroup\$ – ETHproductions Nov 28 '16 at 23:15
  • \$\begingroup\$ yeah >_> whoops, I missed your ++ and didn't realize you needed a reference \$\endgroup\$ – Downgoat Nov 28 '16 at 23:16

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.

  • \$\begingroup\$ 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.... \$\endgroup\$ – JungHwan Min Nov 29 '16 at 1:08
  • \$\begingroup\$ Nah, Martin Ender gets most of my credit anyway. Why is ± two bytes? \$\endgroup\$ – Greg Martin Nov 29 '16 at 3:31
  • \$\begingroup\$ @GregMartin ± in UTF-8 (Mathematica uses UTF-8 by default; try $CharacterEncoding) is a two-byte character (U+00B1). \$\endgroup\$ – JungHwan Min Nov 29 '16 at 4:12
  • \$\begingroup\$ @JHM UTF-8 is not the default character encoding on Windows. Mathematica can read source files in a single-byte code page that includes ±. \$\endgroup\$ – Martin Ender Nov 29 '16 at 5:49
  • 1
    \$\begingroup\$ @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). \$\endgroup\$ – Martin Ender Nov 29 '16 at 18:30

C++14, 178 176 174 155 142 135 bytes


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


std::list<int> s = {4, 4, 9, 4};

//invoke like this
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);};

//or like that
[](auto&l){auto e=end(l),b=begin(l);l.size()^count(b,e,*b)?++*min_element(b,e):(l.push_back(1),0);}(s);


#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())) {
    } else {
        ++*min_element(b, e);

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

    //invoke like this

    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!

EDIT6: as TuukkaX pointed out, unnamed lambdas/functions suffice so i removed the auto i= in the bytecount

  • 5
    \$\begingroup\$ I can't help you with C++, but I can say: Welcome to PPCG! \$\endgroup\$ – Zgarb Nov 29 '16 at 10:25
  • 1
    \$\begingroup\$ I think you don't need the spaces in the #include lines. \$\endgroup\$ – Christian Sievers Nov 29 '16 at 10:29
  • \$\begingroup\$ Oh thank you I just realized it myself :) \$\endgroup\$ – Neop Nov 29 '16 at 10:30
  • 1
    \$\begingroup\$ 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);}; :) \$\endgroup\$ – Quentin Nov 30 '16 at 19:50
  • 1
    \$\begingroup\$ 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 :) \$\endgroup\$ – Quentin Dec 1 '16 at 9:03

05AB1E, 21 20 16 bytes

Saved 4 bytes thanks to Adnan.


Try it online!


                      # 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]
  • \$\begingroup\$ I think that DÙgi0¸«}ÐWksgÝQ+ also works. \$\endgroup\$ – Adnan Nov 28 '16 at 20:47
  • \$\begingroup\$ @Adnan: Aah, nice idea using ÝQ with k. Thanks! \$\endgroup\$ – Emigna Nov 28 '16 at 21:16

Scratch, 25 34 blocks + 7 6 bytes


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[lowval] += 1
  • \$\begingroup\$ Golfing comments please? \$\endgroup\$ – OldBunny2800 Nov 29 '16 at 2:13
  • \$\begingroup\$ why do you declare fval? \$\endgroup\$ – Christoph Nov 29 '16 at 6:47
  • \$\begingroup\$ It appears to me that Scratch is just Python in plain text with colors... \$\endgroup\$ – Stewie Griffin Nov 29 '16 at 11:29
  • \$\begingroup\$ And 1-indexed arrays and no elif statements! \$\endgroup\$ – OldBunny2800 Nov 29 '16 at 12:22
  • 1
    \$\begingroup\$ Good point @Christoph! It was part of an earlier version that got golfed out. Editing. \$\endgroup\$ – OldBunny2800 Nov 29 '16 at 12:23

J, 25 22 bytes


Evaluates to an anonymous verb. Try It Online!


(+~:*[=<./)@,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.

MATL, 16 bytes


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

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}


±{1, 1}

{1, 1, 1}

±{3, 4, 5}

{4, 4, 5}


Haskell, 71 70 62 bytes


@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.

  • \$\begingroup\$ Some restructuring, 62 bytes: f(a:b)|(x,y:z)<-span=<<(<).minimum$a:b++[0|all(a==)b]=x++y+1:z \$\endgroup\$ – Zgarb Nov 29 '16 at 8:12
  • \$\begingroup\$ @Zgarb Just wow! \$\endgroup\$ – Christian Sievers Nov 29 '16 at 10:20
  • \$\begingroup\$ Ugh, my brain fails to infer the type for the monad instance of functions \$\endgroup\$ – Angs Nov 29 '16 at 18:45
  • \$\begingroup\$ @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. \$\endgroup\$ – Christian Sievers Nov 29 '16 at 19:14
  • \$\begingroup\$ @Angs You can find this trick, and many more, in our Haskell golf tips collection. \$\endgroup\$ – Zgarb Nov 29 '16 at 21:21

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.

  • \$\begingroup\$ could you replace !l.Any(o=>o!=l[0])) with l.All(o=>o==l[0])? \$\endgroup\$ – Cyoce Nov 28 '16 at 20:33
  • \$\begingroup\$ @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! \$\endgroup\$ – Yytsi Nov 28 '16 at 20:43
  • 2
    \$\begingroup\$ Does C# not have ++? \$\endgroup\$ – Cyoce Nov 28 '16 at 22:39
  • \$\begingroup\$ You can compile to a Action<List<int>> to remove all of the method signature code \$\endgroup\$ – TheLethalCoder Nov 30 '16 at 9:26
  • 1
    \$\begingroup\$ @Stefan Hmm. I've also seen many people drop the necessary usings with C#, so I don't trust that it's legal to drop using System.Linq off. Unless I see an explicit statement that says this isn't necessary, I'll stay with this. Thanks for the suggestion though! :) \$\endgroup\$ – Yytsi Dec 1 '16 at 16:23

Perl 6, 46 bytes


(modifies the input Array, and returns it)


{     # 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


Jelly, 9 bytes


Thanks to Dennis for the -2 bytes.

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

  • \$\begingroup\$ 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 :) \$\endgroup\$ – Alfie Goodacre Nov 30 '16 at 14:27

Mathematica, 53 bytes 57 bytes 59 bytes

  • 7
    \$\begingroup\$ 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. \$\endgroup\$ – JungHwan Min Nov 29 '16 at 0:35
  • \$\begingroup\$ 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? \$\endgroup\$ – ngenisis Nov 29 '16 at 20:03
  • 1
    \$\begingroup\$ I think you mean Equal@#, although #==## is shorter. \$\endgroup\$ – Martin Ender Nov 30 '16 at 9:39
  • \$\begingroup\$ 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. \$\endgroup\$ – ngenisis Nov 30 '16 at 19:04

R, 72 66 65 bytes


Try it online!

Increment is done using which.min which returns the first match. "[<-" allows to replace the value and returns the modified vector in one function call.

-7 bytes thanks to Giuseppe!

  • \$\begingroup\$ tio.run/##K/r/… \$\endgroup\$ – Giuseppe Jun 6 '18 at 1:42
  • \$\begingroup\$ @Giuseppe I tried isTRUE and isFALSE with sd it isn’t golfier :( \$\endgroup\$ – JayCe Jun 6 '18 at 2:16
  • \$\begingroup\$ heh, 65 bytes replacing != with -! \$\endgroup\$ – Giuseppe Jun 6 '18 at 10:12
  • \$\begingroup\$ @Giuseppe of course! \$\endgroup\$ – JayCe Jun 6 '18 at 20:26

Ruby, 46 bytes


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.

  • 6
    \$\begingroup\$ a.uniq[1] will be truthy iff there are distinct values. \$\endgroup\$ – histocrat Nov 28 '16 at 22:50
  • \$\begingroup\$ You can save a byte by turning a[a.index(a.min)] into a[a.index a.min] \$\endgroup\$ – Cyoce Nov 29 '16 at 5:58

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)

R, 97 bytes


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

Ungolfed :


TI-Basic, 53 bytes

If min(not(ΔList(Ans
cumSum(1 or Ans

Matlab, 83, 77, 71 Bytes

function a=x(a)

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 (twice!) thanks to stewie-griffin.

  • \$\begingroup\$ 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). \$\endgroup\$ – Stewie Griffin Nov 29 '16 at 15:51
  • \$\begingroup\$ 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. \$\endgroup\$ – Owen Morgan Nov 29 '16 at 18:05
  • \$\begingroup\$ ~nnz(a(a~=a(1))) is simply ~nnz(a-a(1)). Also, you don't need the parentheses. if ~nnz(a-a(1));a=[a,1];else[~,I]=min(a);a(I)=a(I)+1;end. This should be 5 bytes shorter (note: I haven't tested it). \$\endgroup\$ – Stewie Griffin Dec 6 '16 at 15:55
  • \$\begingroup\$ You can save 3 bytes by using range(a) instead of nnz(a-a(1)) \$\endgroup\$ – MattWH Dec 9 '16 at 20:21
  • \$\begingroup\$ @boboquack, that code checks if the number of elements in a is equal to the lowest value in that vector. A vector a = [3 4 6] will result in true, and a vector a = [4 4 6] will result in false. I don't think that will be useful here...? \$\endgroup\$ – Stewie Griffin Dec 12 '16 at 0:50

Clojure, 112 100 bytes

Unfortunately min-key returns the last index of the smallest index, not the first one. This works for integer inputs and shorter arrays than 10^9 elements ;)

Edit: Defining an anonymous function, using (apply = a) instead of (= 1(count(set a))).

(fn[a](if(apply = a)(conj a 1)(update a(apply min-key #(+(nth a %)(* % 1e-9))(range(count a)))inc)))


(defn f[a](if(= 1(count(set a)))(conj a 1)(update a(apply min-key #(+(nth a %)(* % 1e-9))(range(count a)))inc)))

A less hacky 134-byte solution reverses the vector before updating it and then reverse it back again:

(defn f[a](if(= 1(count(set a)))(conj a 1)(let[r #(vec(reverse %))a(r a)](r(update a(apply min-key #(nth a %)(range(count a)))inc)))))

Java 8, 85 + 38 = 123 bytes

Void lambda taking a List<Integer> (output is mutated input). Byte count includes lambda and required import.

import static java.util.Collections.*;

l->{if(min(l)==max(l))l.add(0);int i=0,n;while((n=l.get(i))>min(l))i++;l.set(i,n+1);}

Try It Online

This almost looks like Python with those method imports...


MATLAB, 66 53 bytes

if(range(a))[~,b]=min(a);a(b)=a(b)+1;else;a=[a 1];end



a = [3 2]

Successive runs:

[3 2] -> [3 3] -> [3 3 1] -> [3 3 2] -> [3 3 3] -> [3 3 3 1] ...
  • 2
    \$\begingroup\$ You cannot hardcode the inputs, you'd need to do something like @(x) …. \$\endgroup\$ – ბიმო Dec 14 '17 at 2:12

SmileBASIC 3, 101 bytes

Defines a statement function I A where A is our integer array of numbers. Output is achieved by modifying the input (as arrays are references.)

  • \$\begingroup\$ You can save 2 bytes by replacing BREAK with M=0, because A can't contain 0 so M==A[C] will never be true. \$\endgroup\$ – 12Me21 Jun 5 '18 at 19:02

SmileBASIC, 77 bytes


Pyth, 16 bytes


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)
             +     Append
               1   1
              Q    to Q
                   Implicitly print                    

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;[]#_=[]


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.

  • 1
    \$\begingroup\$ Why not make a separate function instead of using where? \$\endgroup\$ – Michael Klein Nov 29 '16 at 3:45

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!


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


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.


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.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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