Increment an Array

44

5

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.

Calvin's Hobbies

Posted 2016-11-28T19:43:29.010

Reputation: 84 000

Does 0 count as positive integer – Downgoat – 2016-11-28T23:14:46.807

20@Downgoat 0 is not ever positive on PPCG. If 0 was allowed, the term would be "non-negative" – ETHproductions – 2016-11-28T23:23:02.270

Answers

13

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.

Dennis

Posted 2016-11-28T19:43:29.010

Reputation: 196 637

11

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!

FlipTack

Posted 2016-11-28T19:43:29.010

Reputation: 13 242

Hmm. "Output the resulting incremented array". Does this qualify? – Yytsi – 2016-11-28T20:02:18.190

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 – 2016-11-28T20:04:01.227

@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 – 2016-11-28T20:04:10.317

you can replace a+=[0] with a+=0, – Cyoce – 2016-11-28T20:05:03.263

Found it! @TuukkaX – FlipTack – 2016-11-28T20:27:39.887

Good! Nice golf by the way :) I was thinking of a shorter way to check whether the list has only one distinct element, but a[1:]==a[:-1] is also 13 bytes... – Yytsi – 2016-11-28T20:37:40.997

1In Python 3, you can use len({*L})<2 to find if all elements of a list are equal. – mbomb007 – 2016-11-28T21:20:27.660

@mbomb007 That's a neat trick! It didn't work in the version I have installed, but worked online with 3.5 :) – FlipTack – 2016-11-28T21:59:06.460

1a+=1//len({*a})*[0] should save a byte. – Dennis – 2016-11-29T00:17:38.753

Good spot! @Dennis – FlipTack – 2016-11-29T20:02:56.080

9

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

ETHproductions

Posted 2016-11-28T19:43:29.010

Reputation: 47 880

Is using a.find(n=>n==Math.min(...a)) shorter? – Downgoat – 2016-11-28T23:13:17.410

@Downgoat I'm not sure how I'd use that, as it returns the item rather than the index – ETHproductions – 2016-11-28T23:15:32.427

yeah >_> whoops, I missed your ++ and didn't realize you needed a reference – Downgoat – 2016-11-28T23:16:27.217

7

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.

Greg Martin

Posted 2016-11-28T19:43:29.010

Reputation: 13 940

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 – 2016-11-29T01:08:11.983

Nah, Martin Ender gets most of my credit anyway. Why is ± two bytes? – Greg Martin – 2016-11-29T03:31:03.403

@GregMartin ± in UTF-8 (Mathematica uses UTF-8 by default; try $CharacterEncoding) is a two-byte character (U+00B1). – JungHwan Min – 2016-11-29T04:12:31.867

@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 – 2016-11-29T05:49:17.823

@MartinEnder It seems that answers are assumed to use UTF-8 unless specified elsewhere, so I believe ± should count as two bytes.

– JungHwan Min – 2016-11-29T06:03:46.707

@JHM this answer could be more explicit about it, but the meta post says that the language's default takes precedence over UTF-8 and the default encoding of Mathematica on Windows is the Windows code page, not UTF-8. – Martin Ender – 2016-11-29T06:09:50.237

@MartinEnder Welp, I don't think Mathematica has a default encoding at all, so it should be assumed to use UTF-8. For instance, my default encoding is CP-949 (because I'm using Korean Windows), so ± is two bytes, but on English Windows (using CP-1252), it is one byte. – JungHwan Min – 2016-11-29T06:13:43.073

@MartinEnder what's the reference for the mentioned single-byte code page? – A Simmons – 2016-11-29T16:08:33.020

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 – 2016-11-29T18:30:50.960

@MartinEnder That's awesome. Thanks! – A Simmons – 2016-11-30T12:24:32.977

7

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

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

Neop

Posted 2016-11-28T19:43:29.010

Reputation: 71

5I can't help you with C++, but I can say: Welcome to PPCG! – Zgarb – 2016-11-29T10:25:25.543

1I think you don't need the spaces in the #include lines. – Christian Sievers – 2016-11-29T10:29:51.710

Oh thank you I just realized it myself :) – Neop – 2016-11-29T10:30:43.497

1Replacing 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 – 2016-11-30T19:50:36.907

Woops, forgot to count the headers. That didn't sound right. 155 bytes it is. – Quentin – 2016-11-30T19:55:35.950

Wow thank you so much @Quentin! Tbh I never messed with lambdas before so I don't quite understand it but I'll definitely look into it now. I really appreciate your help. – Neop – 2016-12-01T03:27:09.347

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 – 2016-12-01T09:03:40.183

Oops the find thing was pretty stupid of me. – Neop – 2016-12-01T09:57:58.190

Can't you just use a pure lambda and drop the auto i=? – Yytsi – 2016-12-03T09:14:20.950

You can drop the #include<list> in your golfed version and should change the title to C++14 – Karl Napf – 2016-12-05T13:26:59.980

I don't understand why I can drop the include in the bytecount as it is required by the lambda, can you please explain it or post a link? I changed the Title. @TuukkaX, I also don't think this would be allowed as you'd have to invoke it with the entire body, or I don't understand your proposal. – Neop – 2016-12-05T14:43:26.573

Here, it states that: "Unnamed functions/lambdas are acceptable, ex. [](int n){ return n+1; }". – Yytsi – 2016-12-05T22:01:12.147

6

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]

Emigna

Posted 2016-11-28T19:43:29.010

Reputation: 50 798

I think that DÙgi0¸«}ÐWksgÝQ+ also works. – Adnan – 2016-11-28T20:47:22.753

@Adnan: Aah, nice idea using ÝQ with k. Thanks! – Emigna – 2016-11-28T21:16:34.130

5

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)

OldBunny2800

Posted 2016-11-28T19:43:29.010

Reputation: 1 379

Golfing comments please? – OldBunny2800 – 2016-11-29T02:13:34.857

why do you declare fval? – Christoph – 2016-11-29T06:47:29.733

It appears to me that Scratch is just Python in plain text with colors... – Stewie Griffin – 2016-11-29T11:29:25.257

And 1-indexed arrays and no elif statements! – OldBunny2800 – 2016-11-29T12:22:38.213

1Good point @Christoph! It was part of an earlier version that got golfed out. Editing. – OldBunny2800 – 2016-11-29T12:23:38.957

I also found a bug I fixed. Inputting [5,6,5] would produce [5,6,5,1] – OldBunny2800 – 2016-11-29T12:47:02.507

4

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.

Zgarb

Posted 2016-11-28T19:43:29.010

Reputation: 39 083

3

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

Luis Mendo

Posted 2016-11-28T19:43:29.010

Reputation: 87 464

3

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.

Yytsi

Posted 2016-11-28T19:43:29.010

Reputation: 3 582

could you replace !l.Any(o=>o!=l[0])) with l.All(o=>o==l[0])? – Cyoce – 2016-11-28T20:33:44.497

@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 – 2016-11-28T20:43:22.400

2Does C# not have ++? – Cyoce – 2016-11-28T22:39:27.613

You can compile to a Action<List<int>> to remove all of the method signature code – TheLethalCoder – 2016-11-30T09:26:36.867

@TheLethalCoder Thanks! Now compiles to an Action<List<int>>. – Yytsi – 2016-11-30T21:44:09.830

@TuukkaX You can remove the parenthesis around the action argument i.e. (l)=> to l=> to save another 2 bytes – TheLethalCoder – 2016-12-01T09:04:10.957

I'n not sure, but I think you can drop the using and just use the lambda, I've seen (and done) it already quite often. That would lead to 59 bytes ;) – Stefan – 2016-12-01T15:37:59.087

1@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 – 2016-12-01T16:23:50.033

3

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}

JungHwan Min

Posted 2016-11-28T19:43:29.010

Reputation: 13 290

3

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.

Christian Sievers

Posted 2016-11-28T19:43:29.010

Reputation: 6 366

Some restructuring, 62 bytes: f(a:b)|(x,y:z)<-span=<<(<).minimum$a:b++[0|all(a==)b]=x++y+1:z – Zgarb – 2016-11-29T08:12:44.730

@Zgarb Just wow! – Christian Sievers – 2016-11-29T10:20:53.990

Ugh, my brain fails to infer the type for the monad instance of functions – Angs – 2016-11-29T18:45:04.183

@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 – 2016-11-29T19:14:59.173

@Angs You can find this trick, and many more, in our Haskell golf tips collection.

– Zgarb – 2016-11-29T21:21:59.897

2

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
}

Brad Gilbert b2gills

Posted 2016-11-28T19:43:29.010

Reputation: 12 713

2

Jelly, 9 bytes

;1µ‘i¦E?Ṃ

Thanks to Dennis for the -2 bytes.

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

Zacharý

Posted 2016-11-28T19:43:29.010

Reputation: 5 710

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 – 2016-11-30T14:27:32.813

2

Mathematica, 53 bytes 57 bytes 59 bytes

If[Equal@@#,#~Join~{1},x=#;x[[#~FirstPosition~Min@#]]++;x]&

ngenisis

Posted 2016-11-28T19:43:29.010

Reputation: 4 600

7That'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 – 2016-11-29T00:35:47.790

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 – 2016-11-29T20:03:48.723

1I think you mean Equal@#, although #==## is shorter. – Martin Ender – 2016-11-30T09:39:17.470

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 – 2016-11-30T19:04:24.197

2

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!

JayCe

Posted 2016-11-28T19:43:29.010

Reputation: 2 655

@Giuseppe I tried isTRUE and isFALSE with sd it isn’t golfier :( – JayCe – 2018-06-06T02:16:41.850

heh, 65 bytes replacing != with -!

– Giuseppe – 2018-06-06T10:12:36.730

@Giuseppe of course! – JayCe – 2018-06-06T20:26:07.437

1

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)

Stewie Griffin

Posted 2016-11-28T19:43:29.010

Reputation: 43 471

1

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.

Lee W

Posted 2016-11-28T19:43:29.010

Reputation: 521

6a.uniq[1] will be truthy iff there are distinct values. – histocrat – 2016-11-28T22:50:38.957

You can save a byte by turning a[a.index(a.min)] into a[a.index a.min] – Cyoce – 2016-11-29T05:58:47.000

1

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

Frédéric

Posted 2016-11-28T19:43:29.010

Reputation: 2 059

1

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.

Owen Morgan

Posted 2016-11-28T19:43:29.010

Reputation: 221

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 – 2016-11-29T15:51:05.637

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 – 2016-11-29T18:05:27.247

~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 – 2016-12-06T15:55:19.803

You can save 3 bytes by using range(a) instead of nnz(a-a(1)) – MattWH – 2016-12-09T20:21:30.483

@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 – 2016-12-12T00:50:39.577

@StewieGriffin sorry, misread the comments. Max(a)==min(a)? – boboquack – 2016-12-12T04:07:18.847

max(a)==min(a) will give true if all elements have the same value and false if not, so that would work. But it's quite long... :) – Stewie Griffin – 2016-12-12T08:26:26.403

1

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

Timtech

Posted 2016-11-28T19:43:29.010

Reputation: 12 038

1

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

NikoNyrh

Posted 2016-11-28T19:43:29.010

Reputation: 2 361

1

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

Pon pon holla mon

Posted 2016-11-28T19:43:29.010

Reputation: 11

2You cannot hardcode the inputs, you'd need to do something like @(x) …. – ბიმო – 2017-12-14T02:12:35.450

1

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

Jakob

Posted 2016-11-28T19:43:29.010

Reputation: 2 428

1

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

snail_

Posted 2016-11-28T19:43:29.010

Reputation: 1 982

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 – 2018-06-05T19:02:41.290

1

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

12Me21

Posted 2016-11-28T19:43:29.010

Reputation: 6 110

0

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                    

TheBikingViking

Posted 2016-11-28T19:43:29.010

Reputation: 3 674

0

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.

sudee

Posted 2016-11-28T19:43:29.010

Reputation: 551

1Why not make a separate function instead of using where? – Michael Klein – 2016-11-29T03:45:32.927

0

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.

Mama Fun Roll

Posted 2016-11-28T19:43:29.010

Reputation: 7 234

0

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.

Tyler MacDonell

Posted 2016-11-28T19:43:29.010

Reputation: 701

0

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:

manatwork

Posted 2016-11-28T19:43:29.010

Reputation: 17 865

0

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}

GolfIsAGoodWalkSpoilt

Posted 2016-11-28T19:43:29.010

Reputation: 101

0

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.

Titus

Posted 2016-11-28T19:43:29.010

Reputation: 13 814

0

MATLAB, 69 67 bytes

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

range(a) is non-zero if not all elements are equal, and [~,j]=min(a) assigns the index of the minimum value in a to j, defaulting to the first value it finds. Input is a row vector. Saved 2 bytes by reversing the if/else logic to get rid of some semicolons (else[~,j] is legal, but elsea=[a 1] is not).

MattWH

Posted 2016-11-28T19:43:29.010

Reputation: 331

0

Actually, 18 bytes

The algorithm used in this answer is largely based on Dennis' Jelly answer. Golfing suggestions welcome! Try it online!

;;M@u#q;m@í0@α1@q¥

Ungolfing

      Implicit input a.
;;    Duplicate a twice.
M     Get the maximum of a.
@u#   Increment all of a and convert back to a list.
q;    Append max(a) to the end of a_plus_one, and duplicate. Call it b.
m@í   Get index of the minimum of b. Call it min_index.
        If all elements of a were equal, this is the maximum at the end.
        Else, it's somewhere else in the array.
0@α   Push a list of min_index zeroes.
1@q   Append a 1 to the end. Call this array c.
        This will increment at the desired index or otherwise append a 1.
¥     Pairwise add a and c to get our incremented array.
      Implicit return.

Sherlock9

Posted 2016-11-28T19:43:29.010

Reputation: 11 664

0

Tcl, 114 bytes

proc I a {if [llength [set S [lsort -u $a]]]<2 {lappend a 1} {lset a [lsearch $a [set m [lindex $S 0]]] [incr m]}}

Try it online!

sergiol

Posted 2016-11-28T19:43:29.010

Reputation: 3 055

-2

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;}

Roman Gräf

Posted 2016-11-28T19:43:29.010

Reputation: 2 915

2

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 – 2016-11-30T17:02:35.883

Have you even tested this? As @Xanderhall said, new Set isn't possible. Also, List b=a; copies the reference, so when you do Collections.sort(b); it will also sort a. You're also missing import java.util.*; in your byte-count for the List, Set, Collections, etc. As for golfing if you fix this instead of deleting this: Since you are modifying the input-List a, the return a; isn't necessary. – Kevin Cruijssen – 2018-04-26T08:06:39.533