text:
Line ending conversion program
Write a program or function that alters the file at a user-specified filename via replacing all instances of UNIX line endings with Windows line endings and vice versa.
Clarifications:

For the purposes of this problem, a UNIX line ending consists of the octet 0A in hexadecimal, except when it is immediately preceded by the octet 0D. A Windows line ending consists of the two octets 0D 0A.
As usual, your program only has to run on one (pre-existing) interpreter on one (pre-existing) operating system; this is particularly important for this question, where I imagine many submissions will succeed on UNIX but fail on Windows, or vice versa, due to line ending conversions built into the language.
To alter a file, you can either edit the file "in-place", or read the file, then save the contents of the file back over the original. However, the program must alter a file on disk; just taking a string as an argument and returning a string specifying the result is not acceptable for this challenge, because the challenge is partially about testing the ability to handle files.
The program's user must have some method of specifying the filename to change without needing to alter the program itself (i.e. you can't use hardcoded filenames). For example, you could read the name of the file to modify from a command-line argument, or from standard input. If you're submitting a function rather than a full program, making it take a filename as argument would be acceptable.
The input to the program must be specified as a filename specifically; you can't take input other than strings (assuming that you're using an operating system in which filenames are strings; in most, they are), and you can't place restrictions on what filenames you accept (you must accept all filenames that the operating system would accept, and that refer to a file that the user running the program has permission to read and write). For example, you can't write a function that takes a UNIX file descriptor as an argument and requires the file to already be open, and you can't write an editor macro that assumes the file has already been opened in the current buffer.
If the file is missing a trailing newline before you alter it, it should continue to be missing a trailing newline after you alter it. Likewise, if the file does have a trailing newline, you should preserve that (leaving the file with the other sort of trailing newline).
If the input file has mixed line ending conventions, you should nonetheless translate each of the line endings to the opposite sort of line ending (so the resulting line will still have mixed line ending conventions, but each individual line will have been converted).
The program is intended for use converting text files, and as such, you don't have to be able to handle nonprintable control codes in the input (although you can if you wish). The nonprintable control codes are the octets from 00 to 1F (hexadecimal) inclusive except for 09, 0A, 0B, 0C, 0D. It's also acceptable for your program to fail on input that cannot be decoded as UTF-8 (however, there is no requirement to place a UTF-8 interpretation on the input; programs which handle all the high-bit-set octets are also acceptable).
As an exception from the specification, it's acceptable for the program to do anything upon seeing the octet sequence 0D 0D 0A in the input (because it's impossible to comply with the spec when this sequence appears in the input: you'd have to generate 0D followed by an 0A which is not immediately preceded by 0D, which is a contradiction).

The shortest program wins, under usual code-golf rules (i.e. fewest bytes in the program you submit). Good luck!
Test cases
Here are some hex dumps of files you can use to test your program. All these test cases are reversible; swapping the input and output gives another valid test case. Note that your program should work for cases other than the given test-cases; these are just some examples to help testing:

Input
30 31 32 0A 33 34 35 0A 36 37 38 0A

Output
30 31 32 0D 0A 33 34 35 0D 0A 36 37 38 0D 0A

Input
30 31 0A 0D 0A 32 0A 0A 0A 33 34

Output
30 31 0D 0A 0A 32 0D 0A 0D 0A 0D 0A 33 34

Input and Output both a zero-byte file.

Could you give some examples? Like normal and edge cases?

Sure, I've added a few. Note that there's not much variety possible; the actual algorithmic part of the challenge is fairly simple.

the input/output has to be files? or could be string (representing the content)?

@Rod: has to be files. That's already stated in the question: "However, the program must alter a file on disk; just taking a string as an argument and returning a string specifying the result is not acceptable for this challenge, because the challenge is partially about testing the ability to handle files."

So just for understanding your second example in 0A 0D 0A, the transform is 0A -> 0D 0A and 0D 0A -> 0A resulting in 0D 0A 0A?

@KarlNapf: that's right; the problem's basically about replacing 0D 0A with 0A and vice versa.

-1 for requiring file I/O. Arbitrarily overriding the defaults is one of the things to avoid when writing challenges.

The override isn't arbitrary. The "read the file, then write it back at the same location" task is a) the way this particular task is normally most useful practically, and b) not actually a method of I/O that's acceptable under default rules. So it's not overriding the defaults any more than "print hello world" is overriding the defaults; it's part of the task, not part of the I/O method (and in fact, it wouldn't be allowed if it were an I/O method!). I didn't override the defaults with respect to the actual input of the challenge (which is the filename).

Can we assume the file won't include bytes equal to 0 (null) or maybe 4 (end of transmission)? Just in case...

I don't know what PPCG's standard rules are on assumptions about what the input file can contain, and I'll be shouted at if I answer the question in the comments :-(. This problem's mostly useful in the context of text files, though, which rarely contain characters like that, so I guess I'll edit the question to specify a character repertoire you have to handle.

That's very reasonable. And helped me save 2 bytes :-D

The challenge is interesting, I'm ok with IO manipulation and I've dealt with the EOL issue before, but why mixed EOL conventions?

@adrianmp: basically because this site requires you to define the puzzle explicitly, including cases like that. I'd be surprised if it makes much of a difference in the long run.

Sed (GNU), 27, 37, 24 bytes (21 byte + "-zi" flags)
(21 byte for code + 3 for "-zi" flags)
EDIT: I've just spotted an issue with an extra carriage return being appended to files with no trailing newline, when going from Unix to DOS.
This is now fixed, and I've also re-profiled my answer to pure Sed instead of Bash, and added some tests.
Golfed
s|\n|\r\n|g;s|\r\r||g

Usage
sed -zi -f newline.sed myfile.txt

Tests

An old pond!
A frog jumps in —
the sound of water.
(Matsuo Basho)

Test Case #1, Unix newlines + trailing newline
>xxd haiky.txt
0000000: 416e 206f 6c64 2070 6f6e 6420 210a 4120  An old pond !.A
0000010: 6672 6f67 206a 756d 7073 2069 6e20 e280  frog jumps in ..
0000020: 940a 7468 6520 736f 756e 6420 6f66 2077  ..the sound of w
0000030: 6174 6572 2e0a                           ater.

>sed -zi -f newline.sed haiku.txt
0000000: 416e 206f 6c64 2070 6f6e 6420 210d 0a41  An old pond !..A
0000010: 2066 726f 6720 6a75 6d70 7320 696e 20e2   frog jumps in .
0000020: 8094 0d0a 7468 6520 736f 756e 6420 6f66  ....the sound of
0000030: 2077 6174 6572 2e0d 0a                    water...

>sed -zi -f newline.sed haiku.txt
0000000: 416e 206f 6c64 2070 6f6e 6420 210a 4120  An old pond !.A
0000010: 6672 6f67 206a 756d 7073 2069 6e20 e280  frog jumps in ..
0000020: 940a 7468 6520 736f 756e 6420 6f66 2077  ..the sound of w
0000030: 6174 6572 2e0a                           ater..

Test Case #2, Unix newlines, no trailing newline
>xxd haiku.no-trailing-newline.txt
0000000: 416e 206f 6c64 2070 6f6e 6420 210a 4120  An old pond !.A
0000010: 6672 6f67 206a 756d 7073 2069 6e20 e280  frog jumps in ..
0000020: 940a 7468 6520 736f 756e 6420 6f66 2077  ..the sound of w
0000030: 6174 6572 2e                             ater.

>sed -zi -f newline.sed haiku.no-trailing-newline.txt
0000000: 416e 206f 6c64 2070 6f6e 6420 210d 0a41  An old pond !..A
0000010: 2066 726f 6720 6a75 6d70 7320 696e 20e2   frog jumps in .
0000020: 8094 0d0a 7468 6520 736f 756e 6420 6f66  ....the sound of
0000030: 2077 6174 6572 2e

>sed -zi -f newline.sed haiku.no-trailing-newline.txt
0000000: 416e 206f 6c64 2070 6f6e 6420 210a 4120  An old pond !.A
0000010: 6672 6f67 206a 756d 7073 2069 6e20 e280  frog jumps in ..
0000020: 940a 7468 6520 736f 756e 6420 6f66 2077  ..the sound of w
0000030: 6174 6572 2e                             ater.

Both are true. I've correct it to handle conversion in both sides, and added explicit $1. Thank you !

I think it works now, although you can probably save several bytes via the use of a ; in the sed program rather than using -e twice.

You can combine the -i and -e, and combine the two sed expression into one with a ;: sed -ie "s/$/\r/;s/\r\r$//" $1

@Riley, true, actually I did this in the original version (which was shown to have a flaw by @ais523). Will restore that now.

MATL, 28 bytes
&Z$[13X]OZt5E6MZtO10ZtG3$FZ#

This works in current release (19.5.1), which is predates the challenge.
I have only tested it on Windows, but it should work on Linux too.
Because of file input/ouput this can't be tested online directly. But here is an online version that accepts and produces hex-dump strings with the format shown in the challenge.
Explanation
&Z$      % Implicitly input filename, and read as chars
[13X]    % Push array [13 10]
O        % Push 0
Zt       % Replace [13 10] by 0
5E       % Push 10
6M       % Push [13 10] again
Zt       % Replace 10 by [13 10]
O        % Push 0
10       % Push 10
Zt       % Replace 0 by 10
G        % Push filename again
3$FZ#    % Overwrite the file with the modified char array

Is MATL the only golf language with file I/O?

@Razetime I’m pretty sure there are others, but I can’t remember right now

C, 240 219 211 227 bytes
Saving a little by #define...fputc and a lot by converting to a program. -8 bytes for converting some logic. +16 bytes for in-place file replacement using the temporary file T
Takes filenames via command line parameters.
#import<stdio.h>
#define P(c) fputc(c,o)
d;int main(int c,char**v){FILE*i=fopen(v[1],"r"),*o=fopen("T","w");while((c=fgetc(i))!=-1){if(c==10)P(13),P(c);else if(c==13){if((d=fgetc(i))!=10)P(c);P(d);}else P(c);}rename("T",v[1]);}

Ungolfed:
#import<stdio.h>
#define P(c) fputc(c,o)
d;
int main(int c,char**v){
  FILE*i=fopen(v[1],"r"),*o=fopen("T","w");
  while((c=fgetc(i))!=-1){
    if(c==10)
      fputc(13,o),fputc(c,o);
    else if(c==13)
      if((d=fgetc(i))!=10)
        fputc(c,o);
      fputc(d,o);
    else fputc(c,o);
  }
  rename("T",v[1]);
}

Usage:
./a.out test_in.txt

This isn't quite complete by itself; it's writing to a new file, rather than overwriting the original. I think you can most easily fix this via using a hardcoded filename for O and doing a rename(O,I) at the end of the function; there might be a way that requires fewer bytes though.

@ais523 Ah okay, I misinterpreted your third point. I guess rename is fine for this stage of the program, which might not be final.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Overlapping Line Ordering
(Inspired while drawing on a dry erase board)
Challenge:
Given an input string containing characters that represent different colors of dry erase markers on a white board, output the order in which they were drawn, from first to last.
Input:
A string which contains dry erase marker colors which are represented by alphabetical letters (upper ones are different than lowercase, you may substitute any characters used in my examples as long as each color has a distinct letter).  The rest of the whiteboard will be white-space.  There will only be one line of each color per board. There won't be inputs where all lines overlap each other (See test case 4).  All lines will be straight and either horizontal or vertical.
Output:
The order in which the lines were drawn on the board, from the first one drawn to the last one.  If there are multiple solutions for any input, you may output any one of them.  The output can be formatted anyway you'd prefer:  single string of characters or separated by spaces, newlines, etc. as long as the characters used match the ones used in your input.
Test Cases:
Input 1:
  R
  R
BBRBB
  R

Output 1:
BR

Input 2:
    GY
    GY
RRRRGYRRR
    GY
    GY
BBBBBBBB
    GY
    GY

Output 2:
RGYB // or RYGB

Input 3:
    R    P
    R    P
AAAARAAAAPA
    R    P
    R    P
GGGGRGGG P
    R

Output 3:
AGPR // or APGR

Input 4:
 O Y
RRRYR
 O Y
GOGGG
 O Y

Output 4:
// Undefined, does not need to be handled by your program

Input 5:
YYYB
   B
   B

Output 5:
// YB or BY

Rules:
This is code-golf, so shortest code in bytes wins.

@StewieGriffin There can be as many as the printable ASCII characters (33-127).  I used normal colors in my test cases, but since they are characters they don't actually correspond to the actual colors (Red, Green, Yellow, etc), they just represent unique colors (R is a different color from G and Y).

Eh yeah good point, I'll just say alphabetical characters only (65-90 and 97-122).

All the lines will be horizontal or vertical, right? You should probably specify that in the question.

@ais523 Yes, edited it in.

May we assume that the input is padded with spaces to a rectangle?

Also, can we take in a list of lines?

@Pietu1998 Yes to the padded question. but what do you mean by a list of lines?

I mean, can we take in ["abc", "def", "ghi"] instead of "abc\ndef\nghi"?

@Pietu1998 Oh yes, that is fine.

Are lines required to touch at least one edge of the board?

@Poke Yeah, you'll never have a row/column that's completely blank.

Perl, 103+2 = 105 bytes
s/$/$"x y===c/gem;$a=$_;$_.=$"while$a=~s/^./!($_.=$&)/gem;s/$1/-/g,$b="$&$b"while/\s(\w)(\1|-)+ /;say$b

Run with -n0 (2 byte penalty).
Explanation:
# -n0: read entire input into `$_` at start of program
# (technically speaking it reads to the first NUL byte, but there aren't any)

# We want to be able to extract columns from the input, so we need to add spaces
# to the ends of each line such that each column is complete. Adding too many
# space is OK, so to ensure we have enough, we add a number of spaces equal to the
# length of the input.
s/$/             # At the end of {something},
$" x             # append a number of spaces ($" is a space by default)
y===c            # obtained by counting the characters in $_
/gem;            # where {something} is each (g) line (m)

$a = $_;         # store a copy of the transformed input in $a

# The next step is to create a transposition of the input. To do that, we
# repeatedly extract the first column of $a and append it to $_. This will lead to
# a bunch of junk whitespace at the end of $_ (of varying lengths, because once a
# line is empty it's omitted from the extracted column), but we're OK with that.
# To transpose properly, we'd want to place newlines between the extracted
# columns; however, it happens that the rest of the program treats space the same
# way it would newline, and separating via spaces is shorter, so we do that.

while (          # keep looping as long as there are matches
  $a =~ s/^./    # replace the first character of {something related to $a}
  !(             # with the null string (NOT of something truthy)
    $_.=$&)      # but append that character ($&) to $_
  /gem) {        # {something} is each (g) line (m) of $a
  $_.=$"         # append a space ($", equivalent to newline here) to $_
}

# Finally, we repeatedly replace every character in the topmost line with the -
# character (treating a line as continuous through the - character but not through
# other characters), thus finding the lines from top to bottom. Because we
# appended the transpose of $_ to $_ above, each line appears twice: once
# horizontally, once vertically. We find only the horizontal copy, but replace
# both with hyphens.
# (Note: I rewrote the regex into a bit more readable of a form in this ungolfed
# version, because the original version wouldn't allow me room to write comments
# inside it. The two should be equivalent; I tested the golfed version.)
while (          # keep looping as long as there are matches
  /\s(\w)        # match a space or newline, $1 (a letter/digit/underscore),
    (\1|-)+      # any positive number of $1s and hyphens,
    \ /x) {      # and a space
  s/$1/-/g,      # changes all $1s to spaces; set $& to $1, $1 becomes invalid
  $b = "$&$b"    # prepend $& to $b
}

# We need to output the lines from first (i.e. bottom) to last (i.e. top).
# We found them in the opposite order, but reversed them via prepending
# (not appending) the partial results to $b.
say $b           # output $b

One slight subtlety here comes with input like this:

   ABC
DDDDDDDDD
   ABC
   ABC
   ABC

Look at the fourth line here. If the order of writing were BACBD, there could genuinely be a horizontal line of Bs along there without violating any of the assumptions of the problem (other than that there's only one line of each colour, something that we don't check). In order to get around this, we ensure in the last regex that each line starts with a letter (or digit or underscore, but those are impossible), and rely on the fact that parallel lines will be found left-to-right and top-to-bottom (because the regex will find the first match within the string). As such, the first character of each ambiguous line here gets overwritten before the line itself is seen as a match, and that prevents the regex matching.

Very impressive... Well done! (I was at 161 bytes, with perl -n0E '/.*/;for$i(/(\S)(?=(?:(?:.{@{+}})?(?:\1| ))*(?!.*\1))/gs){/.*/;unless(/$i+[^$i\s]+$i/||/$i(.{@{+}}[^$i ])+.{@{+}}$i/s){$r="$i$r";s/$i/ /g;last}}/\S/?redo:say$r' (which requires the input lines to be right-padded with spaces to be all the same length) )

Python 2, 199 bytes
l=input()
w=len(l[0])
j="".join(l)
c=set(j)-{" "}
def f(s):
 for h in s:
  i=j.index(h);I=j.rindex(h);o=f(s-{h})
  if{0}>c-s&set(j[i:I:w**(i+w<=I)])and`o`>"Z":return[h]+o
 if{0}>s:return[]
print f(c)

This ended up a lot longer than I initially thought it would. Apart from the rindex I could see this as a very good program to translate into Pyth.
Takes in a list of lines and outputs a list of characters. The code generates permutations recursively, making sure that none of the drawn lines are supposed to be drawn on top of the current line.
The code abuses a lot of Python's features, for example taking w to the power of a boolean, testing for empty sets by checking subsets of {0} (since my sets never contain non-strings), and my favorite, distinguishing any list from None by checking if its representation is greater than Z.
Explained code
lines = input()
width = len(lines[0])
joined = "".join(lines)
characters = set(joined) - {" "} # find unique characters except space in input

def solve(chars_left): # returns a solution for the given set of lines
    for try_char in chars_left: # try all lines left

        start_index = joined.index(try_char) # find start position of this line
        end_index = joined.rindex(try_char) # and end position

        step = width ** (start_index + width <= end_index) # take every width'th character if start
                                                           # and end indices differ by at least width

        used_chars = characters - chars_left # find all drawn lines

        line_chars = set(joined[start_index:end_index:step]) # find the characters inside the current line
        missed_chars = used_chars & line_chars # find all lines that are already drawn but should be on
                                               # top of this line

        solution = solve(chars_left - {try_char}) # find solutions if this line was drawn now

        if {0} > missed_chars and `solution` > "Z": # there should be no missed lines and a solution
                                                    # should exist
            return [try_char] + solution # solution found, prepend current character and return

    if {0} > chars_left: # if no lines are left
        return [] # solution found

print solve(characters) # solve for all lines

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Collapse ascii-art
Challenge
Given a rectangular grid of printable ascii characters as a string or through standard input, write a function or program that collapses the non-space characters into a pile on the bottom.
The rules:

The output has the same dimensions and characters as the input.
A non-space character at (row a,column b) can't have a space character ' ' at (a-1, b), (a-1,b-1) or (a-1,b+1), where rows are numbered up from the bottom-most. This has the consequence that all vertical piles should collapse sideways.
A non-space character can travel at most (initial height - final height) places to the left or right (see Fig. 1).
You can assume the picture has enough space to collapse without characters falling out of the screen.

Figure 1: possible final locations for characters @#$ shown as x,y,z, respectively.
..............
...@..........
..xxx.........
.xxxxx...#....
xxxxxxx.yyy.$.

The order in which characters collapse can be chosen freely. Trailing spaces are not okay but trailing newlines are.
This is code-golf, so the shortest answer in bytes wins!
Example
                 (__)
                 (oo)
           /------\/
          / |    ||
         *  /\---/\
            ~~   ~~
..."Have you mooed today?"...

One possible output:

                --(_
           /----|/|(o_)
          /|/~\---~\\/o)
..."Have*you~mooed~today?"...

Just to clarify, the way characters fall can be hard-coded rather than randomly generated each time?

What did that cow ever do to you?? :(

@ETHproductions that's correct. My example does it bottom to top, left to right but random order or something else is fine, as long as the rules are obeyed.

@Flp.Tkc It's only a model.

Can a piece that is above another piece end up underneath it?

@DestructibleWatermelon yes.

You can assume the picture has enough space to collapse without characters falling out of the screen. This is actual still pretty difficult, as it means a bunch of look behind and stuff to see if it is acheivable in a variety of ways. Can we instead assume that it has enough space for our algorithm to not have to worry about falling out of the screen?

@DestructibleWatermelon if a character happens to fall out of the screen, it's their fault, not yours.

@Angs I don't understand. Can we or can't we choose to assume that the input will not cause characters falling off the screen with our method, ie to not worry at all about input boundaries.

@DestructibleWatermelon yes you can assume that. If someone would still give you input that would fall out, the output is undefined.

JavaScript (ES6), 100 90 88 bytes

f=s=>s==(l=s.search`
`,s=s.replace(eval(`/(\\S)([^]{${l-1},${l+1}}) /`),` $2$1`))?s:f(s)
s=`                 (__)
                 (oo)
           /------\\/
          / |    ||
         *  /\\---/\\
            ~~   ~~
..."Have you mooed today?"...`
console.log(s)
console.log(f(s))

Requires the the string to have at least two lines and all lines padded to equal length. Output for the example image:
              ( --
            /|---/|-(o__
          */~~\---~\|\/o))
..."Have you/mooed~today?"...

Note that as it tries to move elements to the right if possible, the * did not fall between the Have and the you.
Edit: Saved 10% thanks to @ETHproductions. Saved another 2 bytes thanks to @DanielIndie.
Retina 0.8.2, 50 bytes
+`(?<=(.)*)(\S)(.*¶(?<-1>)?(?>(?<-1>.)*).?)
 $3$2

Try it online! A slightly different approach to my JavaScript answer, this uses a balancing group to match a space below the non-space character; the (?<-1>)? allows the space to be one column to the left while the .? allows the space to be one column to the right.
Retina, 40 bytes
~0L$`.(.*)¶
+s`(\S)(.{$.1,$.&}) ¶ $$2$$1

Try it online! Port of my JavaScript answer. The 0L$ atomic stage takes the input and substitutes the two lengths into the second line resulting in the command that actually performs the replacement, which is then evaluated on the original input by the ~ compound stage.

This is a great algorithm! You can replace \n with a literal newline to get it down to two digits ;-)

Also, I think you can so l=s.search`\n`  to save a few bytes.

https://tio.run/##ZY/BTsMwDIbvfYpo6sEZa6xyRAq7cudIYInadIDCPDWl0tQ0r16ycqBlPsTSZ8v/l0/TG1@1H@euOFFtp0ZOXj56KaGTXrT27ExlwfbGgUZQ6pnDy9vrkA/g0txb01bvOtO8KMddPri7chw5Q813muX3eak53/uHBjo@VXTy5KxwdIQGNPtfcDjw7JYSrSgWcylcQGTh2kL4Y9tEVdpDtToZ4/xkQojNk@ktu9A3@yKyNeuoNpf9Jk2Sc7aUvVGF1U0Mv0rJf8G3GOM1P4aA6Qt8FYlzZFxGTj8 86 bytes

@DanielIndie The f= is required for the recursion, but it still saves me 2 bytes, thanks!

you are right, sorry :P

Python 2, 298 bytes
a=input()
L=len(a);s=' '
a=[list(s*L+l.ljust(L+max(map(len,a))))for l in a]
t=1
while t:
 t=0
 for y in range(L-1):
  for x in range(len(a[y])):
   c=a[y][x];C=a[y+1][x-1:x+2]
   if s!=c and s in C:t=1;a[y][x]=s;a[y+1][[[x+1,x][C[1]==s],x-1][C[0]==s]]=c
for l in map(''.join,a):print l[L:].rstrip()

Takes input as a list of strings (one per line)
Example:
Input:
['                 (__)',
'                 (oo)',
'           /------\/',
'          / |    ||',
'         *  /\---/\ ',
'            ~~   ~~',
'..."Have you mooed today?"...']

Output:
              (
            -----/|-(o__
         //|~~\---~\|\/o))
..."Have*you/mooed~today?"...

C, 252 bytes
e=1,l,c,i,j,p,r,w,a[999];f(){while((i=getchar())>0)a[w++]=i,i<16?l++:0,l?0:c++;while(e)for(i=e=0;i<c;i++)for(j=l;j>=0;j--)e=(r=a[p=j*(c+1)+i]-32?a[r=p+c+1]-32?a[r=p+c]-32?a[r=p+c+2]-32?0:r:r:r:0)?l=a[p],a[p]=a[r],a[r]=l:e;for(i=0;i<w;)putchar(a[i++]);}

Ungolfed test code:
#include <stdio.h>

e=1,l,c,i,j,p,r,w,a[999];
f()
{
    // counting lines and columns
    while ((i = getchar())>0)a[w++] = i, i<16 ? l++ : 0, l ? 0 : c++;
    // main shaking loop
    while (e) // repeat while collapsing
        for (i = e = 0; i < c; i++) // columns loop
            for (j = l; j >= 0; j--) // lines loop
                e = ( // remember that collapsing was
                     r = // find place to collapse
                         a[p = j*(c + 1) + i] - 32 ? // if not space
                             a[r = p + c + 1] - 32 ? // if char under the current is not a space
                                 a[r = p + c] - 32 ? // see one position left
                                    a[r = p + c + 2] - 32 ? 0 // then one position right
                                                          : r
                                    : r
                                 : r
                             : 0
                         ) ? // and if place was found
                           l=a[p],a[p]=a[r],a[r]=l // replace values in positions p and r
                           : e;
    //print resulting picture
    for(i=0;i<w;)putchar(a[i++]);
}

int main(void)
{
    int cnt;
    FILE * testf = fopen("caw.txt","w");
    char testd[][31] = {
        "                 (__)        \n",
        "                 (oo)        \n",
        "           /------\\/         \n",
        "          / |    ||          \n",
        "         *  /\\---/\\          \n",
        "            ~~   ~~          \n",
        "...\"Have you mooed today ? \"...",
        "" };
    // prepare data for test
    printf("Initial data:\n");
    for(cnt = 0; cnt < 7; cnt++)
    {
        printf("%s", testd[cnt]);
        fprintf(testf, testd[cnt]);
    }
    fclose(testf);
    // redirect standard input
    freopen("caw.txt", "r", stdin);
    printf("\n\nResult:\n");
    // start test
    f();
}

Result of test:

JavaScript, 286 bytes
b=>eval('f=b=>b==null||" "==b;b=b.split`\n`.map(b=>[...b]);a:for(;;){for(c=0;c<b.length-1;c++)for(g=b[c],d=0;d<g.length;d++){h=g[d];if(!f(h)){e=0;f(b[c+1][d])?e=2:f(b[c+1][d-1])?e=1:f(b[c+1][d+1])&&(e=3);if(e){b[c+1][d+e-2]=h;b[c][d]=" ";continue a}}}break}b.map(b=>b.join``).join`\n`')

Examples
// Here I assume that you've assigned the above function to `fall`
console.log(fall(`
                 (__)
                 (oo)
           /------\/
          / |    ||
         *  /\---/\\
            ~~   ~~
..."Have you mooed today?"...`))

Output:
                -
            /--(-\--(__
          /|~~---/~||/oo))
..."Have*you/mooed~today?"...

Another example:
console.log(fall(`
 (\__/)  .~    ~. ))
 /O O  ./      .'
{O__,   \    {
  / .  . )    \\
  |-| '-' \    }
 .(   _(   )_.'
'---.~_ _ _&`))

Output:
    _ , /
  OO/__'_.. .
 {.(|-|.(O'))/.~{
/('---.~___-_&)_.'}\~.'))

Ungolfed function
function fall(input) {
  let move = true
  let lines = input.split("\n").map(line => line.split(""))
  let isSpace = c => c == null || c == " "
  loop: for (;;) {
    for (let y = 0; y < lines.length - 1; y++) {
      let line = lines[y]
      for (let x = 0; x < line.length; x++) {
        let ch = line[x]
        if (!isSpace(ch)) {
          let dx = 0
          if (isSpace(lines[y+1][x])) { dx = 2 }
          else if (isSpace(lines[y+1][x-1])) { dx = 1 }
          else if (isSpace(lines[y+1][x+1])) { dx = 3 }
          if (dx) {
            lines[y + 1][x + dx - 2] = ch
            lines[y][x] = " "
            continue loop
          }
        }
      }
    }
    break
  }
  return lines.map(line => line.join("")).join("\n")
}

A short way to test for not blank is c>" " where c represents the character you are testing.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
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 0 is not ever positive on PPCG. If 0 was allowed, the term would be "non-negative"

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!

Hmm. "Output the resulting incremented array". Does this qualify?

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

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

you can replace a+=[0] with a+=0,

Found it! @TuukkaX

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

In Python 3, you can use len({*L})<2 to find if all elements of a list are equal.

@mbomb007 That's a neat trick! It didn't work in the version I have installed, but worked online with 3.5 :)

a+=1//len({*a})*[0] should save a byte.

Good spot! @Dennis

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.

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

Nah, Martin Ender gets most of my credit anyway. Why is ± two bytes?

@GregMartin ± in UTF-8 (Mathematica uses UTF-8 by default; try $CharacterEncoding) is a two-byte character (U+00B1).

@JHM UTF-8 is not the default character encoding on Windows. Mathematica can read source files in a single-byte code page that includes ±.

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

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

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

@MartinEnder what's the reference for the mentioned single-byte code page?

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

@MartinEnder That's awesome. Thanks!

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 I'm not sure how I'd use that, as it returns the item rather than the index

yeah >_> whoops, I missed your ++ and didn't realize you needed a reference

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]

I think that DÙgi0¸«}ÐWksgÝQ+ also works.

@Adnan: Aah, nice idea using ÝQ with k. Thanks!

11 bytes

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

I can't help you with C++, but I can say: Welcome to PPCG!

I think you don't need the spaces in the #include lines.

Oh thank you I just realized it myself :)

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

Woops, forgot to count the headers. That didn't sound right. 155 bytes it is.

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.

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

Oops the find thing was pretty stupid of me.

Can't you just use a pure lambda and drop the auto i=?

You can drop the #include<list> in your golfed version and should change the title to C++14

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.

Here, it states that: "Unnamed functions/lambdas are acceptable, ex. [](int n){ return n+1; }".

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)

Golfing comments please?

why do you declare fval?

It appears to me that Scratch is just Python in plain text with colors...

And 1-indexed arrays and no elif statements!

Good point @Christoph! It was part of an earlier version that got golfed out. Editing.

I also found a bug I fixed. Inputting [5,6,5] would produce [5,6,5,1]

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.

could you replace !l.Any(o=>o!=l[0])) with l.All(o=>o==l[0])?

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

Does C# not have ++?

You can compile to a Action<List<int>> to remove all of the method signature code

@TheLethalCoder Thanks! Now compiles to an Action<List<int>>.

@TuukkaX You can remove the parenthesis around the action argument i.e. (l)=> to l=> to save another 2 bytes

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

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.

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!

https://tio.run/##K/r/XykzTUmjuDRXQ6PCtjg5MU9DU7PGUNPOUK04RaNCU0cp2kZXSaNCp9RGtzwjMzlDLzczDyRuqF0RXRqrqZMMlDPU1Pxv9B8A

@Giuseppe I tried isTRUE and isFALSE with sd it isn’t golfier :(

heh, 65 bytes replacing != with -!

@Giuseppe of course!

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.

⍵+(⍳≢⍵)=⊃⍋⍵ → 1+@(⊃⍋⍵)⊢⍵

@Adám fixed; thanks

you don't need the ∘

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

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 Just wow!

Ugh, my brain fails to infer the type for the monad instance of functions

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

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

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

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

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.

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?

I think you mean Equal@#, although #==## is shorter.

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.

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

Vyxal aW, 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 You should post that as your own answer! This is a much better method than I came up with at the time.

R, 63 bytes
`if`(any((v=scan())-v[1]),{v[m]=v[m<-which.min(v)]+1;v},c(v,1))

Try it online!
Had a shot at this without peeking at the previous R answer first.
Although the overall approaches are pretty similar, this pleasingly comes-out 2 bytes shorter.
Here we use a code block (enclosed in curly brackets {}) as an expression, which allows us to adjust a chosen element of the input vector v, and let the expression evaluate to the new value of v.
Shorter, but less fancy than the previous approach of abusing the indexing operator [<- as a function (which definitely deserves an upvote anyway).

I believe the sd trick will fail with length-one input since sd(1) returns NA, which R complains can't be interpreted as a logical.

Thanks @Giuseppe - I didn't think of that.  Rolled-back.

Brachylog, 20 17 bytes
=,1|iᶠo{+₁ʰ}ʰtᵒhᵐ

Try it online!
Explanation
The first case is easy. The second is less so.
=,1|iᶠo{+₁ʰ}ʰtᵒhᵐ
=                  Assert that all elements are equal
 ,1                Append 1
   |               If that failed, try the following instead:
    iᶠ             Get a list of [value, index] pairs for every item in the array
      o            Sort: put smallest value first, and smallest index for equal values
       {   }ʰ      Apply this predicate to the first element of the resulting list:
        +₁ʰ          Add 1 to its first element (first occurrence of min value)
             tᵒ    Sort by the second element of each sublist (index)
               hᵐ  Head of each sublist (value)

Here's a worked example of the second branch:
               Input: [2,3,1,5,1]
iᶠ             [[2,0], [3,1], [1,2], [5,3], [1,4]]
  o            [[1,2], [1,4], [2,0], [3,1], [5,3]]
   {+₁ʰ}ʰ      [[2,2], [1,4], [2,0], [3,1], [5,3]]
         tᵒ    [[2,0], [3,1], [2,2], [5,3], [1,4]]
           hᵐ  [2,3,2,5,1]

APL (Dyalog Unicode), 20 bytes
{⍵+<\⍵=⌊/⍵}⊢,0~⍬≡⊢~⊃

Try it online!
First we append a zero if the input is unique, then increment the first minimum (which will be the trailing zero in the unique case, as the numbers in the input are positive)
⊢~⊃ Input without all occurences of the first element.
⍬≡ Is this the empty vector? (are values in the input the same)
0~ 0 without the result of that (a single 0 if all values are the same, empty vector otherwise)
⊢, Append this to the input
{⍵+<\⍵=⌊/⍵} Increment the first minimum.
⌊/⍵ Minimum value
⍵= Boolean vector with 1's at all minima
<\ Less-than scan; only leaves the first 1
⍵+ Add this boolean vector to the previous vector

Thunno 2, 11 bytes
ạ?1a:MçȮ⁺Ẹȧ

Attempt This Online!
Explanation
ạ?1a:MçȮ⁺Ẹȧ  # Implicit input
ạ            # Is it all equal?
 ?           # If it is:
  1a         #  Append a 1
    :        # Otherwise:
     M       #  Take the minimum
      ç  Ẹ   #  Parallely apply:
       Ȯ     #   Index of the minimum
        ⁺    #   Increment the minimum
          ȧ  #  Assign the new value
             # Implicit output

R, 45 bytes
\(x)`if`(sd(c(x,x)),x+!rank(x,,"f")-1,c(x,1))

Attempt This Online!
This would be 4 bytes longer as a full program, which is a fairer comparison to earlier answers that had been posted when backslash functions were not yet a thing, and full program was a golfier approach:
R, 49 bytes
`if`(sd(c(x<-scan(),x)),x+!rank(x,,"f")-1,c(x,1))

Attempt This Online!

order appears to be stable so should be equivalent to rank

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)

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.

You can save a byte by turning a[a.index(a.min)] into a[a.index a.min]

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

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

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.

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

You can save 3 bytes by using range(a) instead of nnz(a-a(1))

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

@StewieGriffin sorry, misread the comments. Max(a)==min(a)?

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

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

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

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.

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

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)

Vyxal, 10 bytes
≈[1J|g₌ḟ›Ȧ  # main program

≈           # all elements in input are equal
 [1J|g₌ḟ›Ȧ  # main if statement
  1J        # if true, append 1 to input
     g₌ḟ›Ȧ  # if false...
     g      # get the minimum
      ₌ḟ›   # push the index of the min and the increment of the min
         Ȧ  # set that index to the increment
            # implicit output

I came up with this independently but surprisingly it was pretty similar in structure to @AaronMiller's answer.
Try it Online!

JavaScript, 55 bytes
a=>a.every(e=>e==a[0])?a.push(1):a.fill(Math.max(...a))

Modifies the array passed to it, otherwise, it's 3 bytes longer:
a=>a.every(e=>e==a[0])?a.push(1)&&a:a.fill(Math.max(...a))

Try it Online!
Explanation
a=>a.every          // Check that every element "e"...
  (e=>e==a[0])      // ...is equal to the first element.
    ?a.push(1)      // If it's the case push 1 at the end.
      :a.fill       // Else fill the entire array...
        (Math.max   // ...with the biggest...
          (...a))   // ...entry of the array.

Some notable parts

Checking the first element of the array is valid because all of the elements needs to be the same anyways
If the array have different elements, it will end up being an array filled with the largest number anyways, so let's do directly that

Looks like you're expected to only do one iterate [3, 4, 9, 3] -> [4, 4, 9, 3] not to the end

PowerShell, 76 60 bytes
$x,$y=($a=$args)|sort -u
$a[$a.IndexOf(+$x)]+=!!$y
$a+,1*!$y

Try it online!

Uiua, 19 bytes
(⍜⊡'+1⊢⍏.|⊂∶1)≍↻1..

Try it!
(⍜⊡'+1⊢⍏.|⊂∶1)≍↻1..
                  .  # duplicate
              ≍↻1.   # are all elements equal?
(        |   )       # run the left part if not, or right part if so
          ⊂∶1        # append 1 to end
        .            # duplicate
      ⊢⍏             # index of minimum element
 ⍜⊡'+1               # increment value at that index

Wolfram Language (Mathematica), 50 bytes
If[Equal@@#,Append@1,1+#&~MapAt~#&@@Ordering@#]@#&

Try it online!

Uiua, 14 bytes
⬚0+⍘⊚?⧻⊢≍,⊃⍖⍏.

Try it online!
Finds the 0-based index to increment (or the length if the elements are all equal), and adds 1 at that index. The ⍏ (rise; the indices in the array that would put the values in sorted order) is reused three times:

"all equal" test can be done with "rise matches fall"
"the first index of minimum element" is "first of rise"
"the length of the array" is the same as "the length of rise"

⬚0+⍘⊚?⧻⊢≍,⊃⍖⍏.    input: an array of positive integers A
            ⊃⍖⍏.   push fall(A), rise(A), A
          ≍,         keep rise(A) and evaluate "rise(A) == fall(A)"
      ?⧻⊢            if so, call length; otherwise call first on rise(A)
    ⍘⊚              inverse where; create an array B so that B[i] == count of i
                     (3 -> [0, 0, 0, 1])
⬚0+                  elementwise add the result to A, padding with zeros if needed

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

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.

Why not make a separate function instead of using where?

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.

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.

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}

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.

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:

[3,3,3,3,3]
[3,4,9,3]

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.

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!

Perl 5 -MList::Util=,reduce -pa, 75 68 bytes
$F[(grep$_-$F[0],@F)?reduce{$F[$a]>$F[$b]?$b:$a}0..$#F:@F]++;$_="@F"

Try it online!

Julia 1.8, 44 bytes
!x=allequal(x) ? [x;1] : (x[argmin(x)]+=1;x)

Attempt This Online!
allequal requires julia 1.8 or later

Vim, 49 bytes
y$i,<esc>:s/^\(,\d*\)\1*$/&,0
/\<<C-r>=min([<C-r>"])
\>
f0<C-a>|x

Takes the array as comma-separated integers in the buffer. Try it online!
Explanation
y$i,<esc>

Yank the original list of integers; then insert an extra comma at the beginning.
:s/^\(,\d*\)\1*$/&,0<cr>

Using regex, determine if the entire line consists of the same number. If so, append ,0.
/\<...\><cr>

Find the first match of ... as a full word (\< and \> represent word boundaries, corresponding to \b in PCRE), where ... is:
<C-r>=min([<C-r>"])<cr>

Using the expression register, calculate the minimum of the original list.
If the original list was heterogeneous, the cursor is now on the number we want to increment. If the original list was all equal, however, we want to increment the 0 at the end, so:
f0

Move to the next occurrence of 0 on the line. If there is no 0, this does nothing.
<C-a>|x

Increment the number under the cursor. Go to the beginning of the line and delete the extra comma.

Factor, 77 bytes
[ dup all-eq? [ 1 suffix ] [ dup [ ] infimum-by* 1 + swap pick set-nth ] if ]

Try it online!
Went through a bunch of different iterations of this. tri was shorter than stack shufflers, amazingly, when using change-nth, but locals were king. However, we can attain even fewer bytes by using infimum-by*, which places both the index and value of the smallest element on the stack.

Arturo, 60 56 bytes
$->a->([]=a--a\0)?->a++1[i:index a min a a\[i]:a\[i]+1a]

Try it

Scala, 159 bytes
Golfed version. Try it online!
a=>{def g(l:List[Int]):List[Int]=l match{case x::q if x==a.min=>(x+1)::q;case x::q=>x::g(q);case _=>Nil};if(a.distinct.length==1)a:+1 else g(a.toList).toArray}

Ungolfed version. Try it online!
object Main extends App {

  def incrementArray(arr: Array[Int]): Array[Int] = {
    val minVal = arr.min
    def g(list: List[Int], m: Int): List[Int] = list match {
      case x :: xs if x == m => (x + 1) :: xs
      case x :: xs           => x :: g(xs, m)
      case Nil               => Nil
    }
    if (arr.distinct.length == 1) arr :+ 1
    else g(arr.toList, minVal).toArray
  }

  var r = Array(3, 1, 1);
  for (i <- 1 to 10) {
    r = incrementArray(r)
    println(r.mkString(", "))
  }

}