# Increment an Array

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.

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

# Jelly, 8 7 bytes

‘;ṀỤḢṬ+

### How it works

‘        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, 625351 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!

• Hmm. "Output the resulting incremented array". Does this qualify? – Yytsi Nov 28 '16 at 20:02
• 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 – FlipTack Nov 28 '16 at 20:04
• @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. – Calvin's Hobbies Nov 28 '16 at 20:04
• In Python 3, you can use len({*L})<2 to find if all elements of a list are equal. – mbomb007 Nov 28 '16 at 21:20
• a+=1//len({*a})*[0] should save a byte. – 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")

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

# Mathematica, 7057 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.

• 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.... – JungHwan Min Nov 29 '16 at 1:08
• Nah, Martin Ender gets most of my credit anyway. Why is ± two bytes? – Greg Martin Nov 29 '16 at 3:31
• @GregMartin ± in UTF-8 (Mathematica uses UTF-8 by default; try $CharacterEncoding) is a two-byte character (U+00B1). – JungHwan Min Nov 29 '16 at 4:12 • @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 Nov 29 '16 at 5:49 • @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 Nov 29 '16 at 18:30

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

# submission

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

# invocation

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);};
i(s);

//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);

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

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

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

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

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

# MATL, 16 bytes

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

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

# 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 } # 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} ## 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.

• Some restructuring, 62 bytes: f(a:b)|(x,y:z)<-span=<<(<).minimum$a:b++[0|all(a==)b]=x++y+1:z – Zgarb Nov 29 '16 at 8:12 • @Zgarb Just wow! – Christian Sievers Nov 29 '16 at 10:20 • Ugh, my brain fails to infer the type for the monad instance of functions – Angs Nov 29 '16 at 18:45 • @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 Nov 29 '16 at 19:14 • @Angs You can find this trick, and many more, in our Haskell golf tips collection. – Zgarb Nov 29 '16 at 21:21 # C#, 12312112079 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. • could you replace !l.Any(o=>o!=l[0])) with l.All(o=>o==l[0])? – Cyoce Nov 28 '16 at 20:33 • @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! – Yytsi Nov 28 '16 at 20:43 • Does C# not have ++? – Cyoce Nov 28 '16 at 22:39 • You can compile to a Action<List<int>> to remove all of the method signature code – TheLethalCoder Nov 30 '16 at 9:26 • @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! :) – Yytsi Dec 1 '16 at 16:23 # R, 72 66 65 bytes "if"(any((x=scan())-x[1]),"[<-"(x,u<-which.min(x),1+x[u]),c(x,1)) 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! • tio.run/##K/r/… – Giuseppe Jun 6 '18 at 1:42 • @Giuseppe I tried isTRUE and isFALSE with sd it isn’t golfier :( – JayCe Jun 6 '18 at 2:16 • heh, 65 bytes replacing != with -! – Giuseppe Jun 6 '18 at 10:12 • @Giuseppe of course! – JayCe Jun 6 '18 at 20:26 # Jelly, 9 bytes ;1µ‘i¦E?Ṃ Thanks to Dennis for the -2 bytes. Body must be at least 30 characters; you entered ... . • 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 Nov 30 '16 at 14:27 Mathematica, 53 bytes 57 bytes 59 bytes If[Equal@@#,#~Join~{1},x=#;x[[#~FirstPosition~Min@#]]++;x]& • 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. – JungHwan Min Nov 29 '16 at 0:35 • 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 Nov 29 '16 at 20:03 • I think you mean Equal@#, although #==## is shorter. – Martin Ender Nov 30 '16 at 9:39 • 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 Nov 30 '16 at 19:04 # 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... # VyxalaW, 21 18 bytes -3 bytes by using the register instead of variables. :≈[1J|:g£(nn¥=[›0£ Try it Online With Equal Elements! Try it Online With Unequal Elements! Explanation: # Implicit input; a flag takes input as list : # Duplicate input ≈[1J # If all elements are equal: append 1 |:g£ # Else: save minimum value to the register ( # For every element in the input: n # Duplicate current element n n¥=[ # If current element n == register value: ›0£ # Increment current element and clear the register # Implicit output; W flag outputs full stack • Try it Online! in 10 bytes. I came up with my answer independently, but they are very similar. For the case of unequal numbers, finds the index and increment of the min, and then sets that position of the input to that. – Underslash Jul 6 at 9:22 • @Underslash You should post that as your own answer! This is a much better method than I came up with at the time. – Aaron Miller Jul 6 at 12:51 # AWK, 63 bytes a=b=1{for(;$++a;d=$b==$a&&c==$a?a+1:b)b=(c=$b)>$a?a:b;$d++}++NF

Try it online!

The code scans all the numbers presented on the input line and sets variable, d, to the position of the smallest number, or to the number of fields plus one if all values are equal. Then it increments the number at that position and prints everything. As a result it either adds a new field with a value of 1 or increments the smallest number in the given set of numbers.

The first condition/test is always true, and just does some initialization.

a=b=1

The code block is a for loop, which applies one statement to each number from the input line.

for(;$++a;d=$b==$a&&c==$a?a+1:b)b=(c=$b)>$a?a:b

The check to continue iterating just increments the a "current field" variable and stops when it's gets a 0 (by running off the end of the list).

$++a The body of the loop updates b such that it's always pointing to the position of the smallest number in the input. The code also has to save the previous position of the smallest number, stored in c, to deal with cases where the minimum is the last number on the line. b=(c=$b)>$a?a:b The "end of loop" statement sets variable d to the current field "plus one" if the current value matches the current minimum as well as the previous minimum, or to the position of the current minimum otherwise. d=$b==$a&&c==$a?a+1:b

One the loop completes, the code increments whichever field d points to. If all the fields are the same, it will increment an uninitialized field, which in AWK will default to 0. Otherwise it will increment the first field with the smallest value.

\$d++

The second condition/test just increments the number of fields in the input line, which will always evaluate to true. If all the fields were the same numeric value, that change in NF will cause a 1 to be appended to the list. And if it changed one of the presented fields the additional field printed as a result of incrementing NF will be an empty string.

++NF

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

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

# Octave, 6967 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

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

# 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

# Matlab, 83, 77, 71 Bytes

function a=x(a)
if~nnz(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 (twice!) thanks to stewie-griffin.

• 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 Nov 29 '16 at 15:51
• 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. – Owen Morgan Nov 29 '16 at 18:05
• ~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). – Stewie Griffin Dec 6 '16 at 15:55
• You can save 3 bytes by using range(a) instead of nnz(a-a(1)) – mwh Dec 9 '16 at 20:21
• @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...? – 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)))

Original:

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

# MATLAB, 66 53 bytes

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

Output:

Initialize:

a = [3 2]

Successive runs:

[3 2] -> [3 3] -> [3 3 1] -> [3 3 2] -> [3 3 3] -> [3 3 3 1] ...
• You cannot hardcode the inputs, you'd need to do something like @(x) …. – ბიმო 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.)

DEF I A
M=MIN(A)IF M==MAX(A)THEN PUSH A,1RETURN
FOR C=0TO LEN(A)IF M==A[C]THEN INC A[C]BREAK
NEXT
END
• 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. – 12Me21 Jun 5 '18 at 19:02

# SmileBASIC, 77 bytes

DEF I A
IF MIN(A)==MAX(A)THEN PUSH A,0
WHILE A[I]>MAX(A)I=I+1WEND
INC A[I]END

# APL (Dyalog Unicode), 48 bytes

f←{1≥≢∪⍵:⍵,1⋄1+@(⊃⍋⍵)⊢⍵}

Try it online!

Alternate versions of 1+@(⊃⍋⍵)⊢⍵: ⍵+(⍳≢⍵)=⊃⍋⍵, ⊢+⍳∘≢=⊃∘⍋. -2 thanks to @Adam and @Razetime.

Explanation:

{1≥≢∪⍵:⍵,1⋄1+@(⊃⍋⍵)⊢⍵}
1≥≢∪⍵                   ⍝ if all elements are identical
⍵,1               ⍝ then yield ⍵ with 1 appended to the end.
⋄              ⍝ ... else,
(⊃⍋⍵)      ⍝ index of the smallest value
1+@     ⊢⍵    ⍝ increment the value from ⍵
• =/1 2 2 gives 1. – Adám Apr 19 at 7:55
• ⍵+(⍳≢⍵)=⊃⍋⍵1+@(⊃⍋⍵)⊢⍵ – Adám Apr 19 at 8:25
• @Adám fixed; thanks – Kamila Szewczyk Apr 19 at 16:31
• you don't need the – Razetime Apr 19 at 16:56

# K (oK), 24 bytes

Solution:

{(x[x?&/x]+:1;x,1)1=#?x}

Try it online!

Explanation:

Nothing too fancy, potentially golfable further:

{(x[x?&/x]+:1;x,1)1=#?x} / the solution
{                      } / anonymous lambda taking implicit x argument
?x  / get distinct values in x
#    / count length
1=     / is it 1?
(           ;   )       / two item list which is index into
x,1        / append 1 to input
x[     ]+:1            / modify x in-place (add 1) at index given in []
&/x                / minimum of x
x?                   / lookup index (returns first one)