text:
The tedious array of 7 rules
The rundown
Create a program that generates an array of random length with random numbers, then apply a series of rules that alter the array. After the rules have been applied, print the sum of the array unless specified otherwise
Array setup
The array must be a random length between 5 and 10 inclusive, with random integers between 1 and 20 inclusive. Each array length should have equal probability of happening and each integer should have an equal probability of being picked per element.
The 7 rules
The rules should act as if they were applied in sequence (eg: rule 1 acts before rule 2) and are only applied once. For proof of rule application, the array must be printed to console after each rule application and once before any rules are applied.

If the array contains a 7, subtract 1 from every element
If rule 1 is applied and the array now contains a 0, add 1 to each element
If the array contains a 13, exclude the 13, and all elements that follow, from the array
If the array contains a 2, exclude all odd numbers
If the array contains a 20, and the third element is even, return 20 as the sum then terminate. If a 20 is present and the third element is odd, return 20 times the length of the array as the sum then terminate.
If the sum is greater than 50, remove the last element repeatedly until it is less than or equal to 50
If the array contains a 16, print the sum in both decimal and hexadecimal.

Example
Here is an initial array,
[20, 2, 5, 7, 14, 8]

Rule 1 can be applied:
[19, 1, 4, 6, 13, 7]

Rule 3 is applied next:
[19, 1, 4, 6]

No other rules are needed, so the program returns 30 as the sum.
Notes

I'm not an experienced code golfer, although I can say my personal record is in Python 3 with 369 bytes.
The rules don't have to actually be applied in order, but have to act as if they did.

How random does "random" have to be?

@HyperNeutrino it can be as sudo-random as you want, but not challenge throwing. Repeats are allowed.

How are you going to check if we actually applied the rules? I can just generate a random number under 50 and it would still technically not break any of the rules, and I could just say it "followed" the rules. EDIT: I realise now that this won't work, but people are going to find ways to circumvent the random rules. Are you going to prevent that?

@Qwerp-Derp Good point. I'll add the rule of printing the array after a rule is applied.

At the moment, choosing one of the two arrays [3 3 3 3 4 3] and [4 4 3 4 4], each with probability 50%, is in compliance with what's written under "array setup". So I can just output 19 every time? (Of course, what I really think is that the definition of "random" needs to be clarified.)

If the array contains a 20, and the third element is even/odd, what if the array has less than 3 elements at this step?

What should happen if we end up with an empty array after, say, applying rule 3? Do we need to print to console if a rule isn't applied?

@Emigna, just print 20

@Shaggy by definition an empty array has a sum of 0, so print 0. That works too.

Thanks, @YamB. At the time of asking, I was using a method to sum the array that returns undefined if it's empty (eval(array.join("+"))) but that's no longer an issue. A couple more questions, if I may: 1) Does the order that the decimal & hex are returned in matter? 2) Can we use alerts in JavaScript, rather than logging to console? Apologies if these are basic questions, I'm still fairly new to Code Golf.

@Shaggy For sure, both of those are totally acceptable.

Sweet, thanks, @YamB.

Can I use [4,4,4,4,4,4,4] as the array? It is random...

@programmer5000, as long as the array isn't hard coded

@Graviton "pseudo-random"

Is allowed to use a (lisp) list instead of a (lisp) array?

@Renzo, yes, the term "array" isn't set in stone for this challenge.

Python 3, 294 301 287 356 bytes
import random as r
r=r.randint
k=[r(i)+1for i in[20]*r(5,11)]
p=print
if 7in k:k=[i-1for i in k]
p(k)
if 0in k:k=[i+1for i in k]
p(k)
i=k.find(13)
if not~i:k=k[:i]
p(k)
if 2in k:k=[i for i in k if~i%2]
p(k)
a=0
z=len(k)>2and k[2]%2
if 20in k:a=20*len(k)**z
if~z:p(k)
while sum(k)>50:k=k[:-1]
if~z:p(k)
if a:p(a)
else:a=sum(k);p(a,hex(a)*(16in k))
if~z:p(k)

I don't know how you're going to prevent people circumventing the rules, but this one uses the procedure specified.
+7 bytes; thanks to @YamB for saving a few bytes; added a lot more to fix a previous error.
-14 bytes thanks to @RootTwo and myself and also corrected the error.
+83 bytes; this is getting horribly long because OP keeps changing the  rules.
-some number of bytes thanks to @ZacharyT

All checks out to me, thanks for being honest.

You can save 4 bytes by importing 'randint as r' and changing 'if 7in k and 1not in k:k=[i-1...'  to 'if 7in k:k=[i+1-int(1in k)...'

When initializing k, you don't need the value of i, so you can save 6 bytes with k=[r(1,20)for _ in'-'*r(5,11)]. You can save another byte using k=[i+~-(1in k)*(7in k)for i in k] for rules 1 and 2.

@Notts90 The rules were changed after I wrote this challenge. I will fix it when I get to a computer. Thanks.

On lines five and seven, you have an unneeded space after the 1, and you can change the print on the second and third to last lines to p. And you ... haven't updated your bytecount.

@ZacharyT Oh thanks. And... whoops. :P

You still have a print statement left.

@ZacharyT ... I was wondering where it went. Thanks.

And, I think that there's one last thing I can think of: 20*[1,len(k)][z] might be able to become 20*len(k)**z.

@ZacharyT Ah yes, nice. Thanks!

05AB1E, 91 bytes
5TŸ.RF20©L.R})=D7åi<=D0åi>=}}D13åiD13k£=}D2åiDÈÏ=}D®åiDgs2èÉ®si*},q}[DO50›_#¨=]D16åiDOH,}O,

Try it online!
or With input

84 bytes, and potentially correct? Different? No idea.  https://tio.run/nexus/05ab1e#@@9ifnhppk2tiwGQsqt1MTQG0kAy@9DiWhcjEPtwx@H@2sMTjEAKio0PrzjcmZluZKBVeHi1kUFhba2Lv6nBo4ZdmdEuh1b4H1ppamCXeWgdUDzWxdAMqMPfJeNRw6zCWv///6MNdYyB0ETH0FjHTMc89mtevm5yYnJGKgA

@carusocomputing: I haven't looked through it thoroughly, but it doesn't generate the random array in the beginning nor does it print intermediate results. Will be a bit longer when adding those parts.

JavaScript, 344 342 340 342 335 331 333 313 311 305 298 297 290 289 283 279 271 265 263 bytes
Following this exchange* in the challenge's comments and after much deliberation I opted to use new Date as the seed for the random number generator instead of Math.random(). Doing so means that all the integers in the array will be of the same value.
Now a full programme, rather than a function
D=new Date
P=print
I=n=>~a.indexOf(n)
C=(n,c)=>I(n)&&P(a=+c?a.map(x=>x+c):a.filter(c))
P(a=[...Array(D%6+5)].map(x=>D%20+1))
C(7,-1)
C(s=0,1)
C(13,(_,x)=>x<~I(13))
C(2,x=>x%2)
P(I(t=20)?a[2]%2?t*a.length:t:P(a.filter(x=>s+x<51?s+=x:0))|I(16)?[s,s.toString(16)]:s)

Try it online! or with Math.random

*Screenshot, in case it's deleted:

C (gcc), 621 619 593 585 570 562 557 552 529 517 500 482 461 444 442 441 438 bytes
There's a whole lot of golfing needed here...
Fixed a bug where it would print the hexidecimal once for each 16 in the list...
Special thanks to ZacharyT with the golf help
#define R r[i]
#define P printf("%d "
#define L for(d=i=0;i<l;i++)
d,i,j,l,r[11];p(i){L P,R);puts("");}main(){srand(time(0));for(l=5+rand()%5;i<l;R=1+rand()%20,i++);for(p();i--;)if(R==7){L--R;j=i=1;}for(p();j&&i<l;i++)if(!R){L++R;j=i=l;}p();L if(R==13)l=i;p();L if(R==2)for(d=1;d;)L if(R&1)for(d=1,--l;i<=l;i++)R=r[i+1];p();L if(R==20)return P,r[3]&1?20*l:20);for(j=i=0;i<l&&j+R<51;j+=R,i++);l=i;p();P,j);L if(R==16)printf("0x%x",j,i=l);}

Try it online!

Even though you can still golf a lot, you're already 1 byte below my Java answer.. XD Let's see if I can golf it somehow to beat your current submission. ;)

Ok, found something for -3 bytes ;p

If you can golf this down, you might be able to get a "crossed out 444 is still 444" in there! :D

@HyperNeutrino Golfed off another 2 bytes

Yay! Nice job :D

Could you replace j+R<=50 with j+R<51?

@ZacharyT that seems to work, thanks!

Could you change for(p();i;)if(r[--i]==7) to for(p();i--;)if(R==7)?

@ZacharyT It's amazing to me that anyone else can make sense of this mess.

It helps to look at small portions of the code (rather then try to change the logic), especially when golfing someone else's code.

419 bytes

K (ngn/k), 160 147 139 bytes
-13 from consolidating 0N! prints/other tweaks
-8 by converting to ngn/k
{0N!'|(a@:&(~2!a)|^a?2;a:(a?13)#a;a+:|/~a;a-:|/a=7;a:1+(*5+1?6)?20);$[^a?20;;:20*(1;#a)2!a 2];0N!a@:&51>+\a;(+/a),$[^a?16;!0;,`hex@`c$+/a]}

Try it online!
From the beginning to the end...

0N!'| print each of the following in reverse order (when building lists, ngn/k executes the right-most/last list item first, the second-to-last item second, etc. For ease of explanation, the below are listed in the order they are executed)

a:1+(*5+1?6)?20 generate 5-10 random numbers between 1 and 20, storing in a
a-:|/a=7; decrement a if it contains a 7
a+:|/~a; increment a if it contains a 0
a:(a?13)#a; take elements occurring before the first 13
a@:&(~2!a)|^a?2; if a 2 is present, remove odds from a

$[^a?20;;:20*(1;#a)2!a 2]; if 20 is present, check the third value a 2 and early return from the function (otherwise do nothing)
0N!a@:&51>+\a; remove values where the cumulative sum up to that point is >50
$[^a?16;+/a;(+/a;`hex@`c$+/a)] return either the sum of a (if no 16 is present), or return the sum as both an integer and in hexadecimal representation (the latter as a string)

JavaScript (ES6), 296 295 290 289 bytes
A full program that logs the initial array, the intermediate results and the final sum to the console.

f="z=[...Array(5+6j)]Z1+20jw7`-1w0`+1w13_qi+1<-kw2_qn&1^1w20_z[2]&1?a.length*20:20);else{q(s+=n)<51,s=0w16_b.toString(16_;b)}zconsole.log(aw_;if(k=~a.indexOf(v((n,i)=>qz=a.filtervj*Math.random()|0bz.reducevn+i,0)`_z=aZn_))Z.mapv";for(g of "Z_`bjqvwz")e=f.split(g),f=e.join(e.pop());eval(f)

How it works
This was compressed using this JS packer.
Breakdown:

Packed string: 226 225 bytes
Unpacking code: 69 64 bytes

Below is the original source code with some additional whitespace and line feeds for readability. Rather than applying standard golfing tricks, it was written in a way that produces as many repeating strings as possible in order to please the packer. For instance, the syntax if(k=~a.indexOf(N)) is duplicated everywhere although k is only used in the 3rd rule.
console.log(a=[...Array(5+6*Math.random()|0)].map((n,i)=>1+20*Math.random()|0));
if(k=~a.indexOf(7))
  console.log(a=a.map((n,i)=>n-1));
if(k=~a.indexOf(0))
  console.log(a=a.map((n,i)=>n+1));
if(k=~a.indexOf(13))
  console.log(a=a.filter((n,i)=>i+1<-k));
if(k=~a.indexOf(2))
  console.log(a=a.filter((n,i)=>n&1^1));
if(k=~a.indexOf(20))
  console.log(a[2]&1?20*a.length:20);
else {
  console.log(a=a.filter((n,i)=>(s+=n)<51,s=0));
  if(k=~a.indexOf(16))
    console.log(a.reduce((n,i)=>n+i,0).toString(16));
  console.log(a.reduce((n,i)=>n+i,0))
}

Unpacking methods
The original unpacking code is:
f="packed_string";for(i in g="ABCDEFGHI")e=f.split(g[i]),f=e.join(e.pop());eval(f)

All the following ES6 variants have exactly the same size:
eval([..."ABCDEFGHI"].reduce((f,g)=>(e=f.split(g)).join(e.pop()),"packed_string"))
[..."ABCDEFGHI"].map(g=>f=(e=f.split(g)).join(e.pop()),f="packed_string")&&eval(f)
eval([..."ABCDEFGHI"].map(g=>f=(e=f.split(g)).join(e.pop()),f="packed_string")[8])

The only way I've found so far to shave off a few bytes is to use for ... of:
f="packed_string";for(g of "ABCDEFGHI")e=f.split(g),f=e.join(e.pop());eval(f)

Reading this on a phone so I may be wrong but, in your unpacked code, it looks like rule 2 is being applied regardless of whether or not rule 1 is.

@Shaggy That's correct. But you can't get a zero unless rule 1 is triggered.

D'oh! Of course! Man, I've been having a ridiculous number of brainfarts during this challenge :(

Would it have any effect on the size on the packed version if you replaced !(n&1) with n%2 and a[2]&1?20*a.length*20 with a[2]%2?a.length*20:20?

@Shaggy Unfortunately not. However, we can save one byte with n&1^1 (it doesn't get packed at all, but is just one byte shorter than !(n&1)). I thought about that at some point and forgot to include it.

Hang on, why am I trying to help you out when you're the one I'm trying to beat with my own answer?! :D I was getting closer and closer to that 295 mark and now you've stretched the gap even further - have an upvote anyway. I'll have to give that packing tool a try myself sometime.

@Shaggy By the way, your entry is already a few bytes shorter than my initial golfing attempt. :-) (Before I decided to switch to the packer method.)

I finally got there!

@Shaggy Ahah! Nice job!

Java 10, 622 619 618 613 576 575 bytes
v->{var L=new java.util.Stack<Integer>();String r="",N="\n";int c=(int)(Math.random()*6+5),i=c;for(;i-->0;L.add((int)(Math.random()*20+1)));r+=L+N;if(L.contains(7)){for(;++i<c;L.set(i,L.get(i)-1));r+=L+N;}if(L.contains(i=0)){for(;i<c;L.set(i,L.get(i++)+1));r+=L+N;}if((i=L.indexOf(13))>=0){L.subList(i,c).clear();r+=L+N;}if(L.contains(2)){for(i=0;i<L.size();)if(L.get(i)%2>0)L.remove(i);else++i;r+=L+N;}if(L.contains(20))return r+20*(L.get(2)%2<1?1:L.size());i=0;for(var x:L)i+=x;for(;i>50;)i-=L.remove(L.size()-1);return r+L+N+(L.contains(16)?Byte.valueOf(i+"",16)+N:"")+i;}

-1 byte thanks to @Poke
-6 bytes thanks to @ceilingcat.
Try it online.
Explanation:
v->{                          // Method with empty unused parameter and String return
  var L=new java.util.Stack<Integer>();
                              //  Integer-list, starting empty
  String r="",                //  Result-String, starting empty
         N="\n";              //  Temp-String `N`, containing a newline
  int c=(int)(Math.random()*6 //  Get a random integer in the range [0,6]
              +5),            //  And add 5
  i=c;for(;i-->0;             //  Loop that amount of times:
    L.add((int)(Math.random()*20+1)));
                              //   Add a random integer in the range [1,20] to the list
  r+=L+N;                     //  Append the current list + newline to the result-String
  if(L.contains(7)){          //  If the list now contains a 7:
    for(;++i<c;L.set(i,L.get(i)-1));
                              //   Decrease each value by 1
    r+=L+N;}                  //   And append the current list + newline again
  if(L.contains(i=0)){        //  If the list now contains 0:
    for(;i<c;L.set(i,L.get(i++)+1));
                              //   Increase each value by 1
    r+=L+N;}                  //   And append the current list + newline again
  if((i=L.indexOf(13))>=0){   //  If the list now contains a 13:
    L.subList(i,c).clear();   //   Remove all values from that 13 onward from the list
    r+=L+N;}                  //   Append the current list + newline again
  if(L.contains(2)){          //  If the list now contains a 2:
    for(i=0;i<L.size();)      //   Loop over the list:
      if(L.get(i)%2>0)        //    If the current value is odd:
        L.remove(i);          //     Remove it
      else                    //    Else:
        ++i;                  //     Skip it, and go to the next value
    r+=L+N;}                  //   Append the current list + newline again
  if(L.contains(20))          //  If the list now contains a 20:
    return r                  //   Return the result-String
           +20*               //   And append 20 multiplied by:
               (L.get(2)%2<1? //    If the third item is even:
                 1            //     Multiply the 20 by 1 so it'll remain 20
                :             //   Else (it's odd instead):
                 L.size());   //    Multiply the 20 by the list-size
  i=0;for(var x:L)i+=x;       //   Set `i` to the sum of the list
  for(;i>50;)                 //  Loop as long as the list-sum is larger than 50:
    i-=L.remove(L.size()-1);  //   Remove the last item of the list
  return r                    //  Return the result-String
         +L+N                 //  Appended with the current list + newline again
         +(L.contains(16)?    //  If the list now contains a 16:
            Byte.valueOf(i+"",16)+N
                              //   Append the sum as hexadecimal
           :                  //  Else:
            "")               //   Append nothing
         +i;}                 //  And append the sum (as regular base-10 integer)

Sample outputs:
Comments behind the sample outputs aren't printed, but I added them as clarification.
[17, 5, 3, 1, 16, 17, 11, 7, 13]   // Initial print (size 9)
[16, 4, 2, 0, 15, 16, 10, 6, 12]   // Rule 1 (contains a 7)
[17, 5, 3, 1, 16, 17, 11, 7, 13]   // Rule 2 (contains a 0)
[17, 5, 3, 1, 16, 17, 11, 7]       // Rule 3 (contains a 13)
[17, 5, 3, 1, 16]                  // Rule 6 (sum must be <= 50)
66                                 // Rule 7 (contains a 16 -> print as Hexadecimal)
42                                 // Print sum as integer

[4, 18, 17, 12, 11, 8]             // Initial print (size 6)
[4, 18, 17]                        // Rule 6 (sum must be <= 50)
39                                 // Print sum as integer

[4, 14, 6, 14, 7, 20, 2, 2]        // Initial print (size 8)
[3, 13, 5, 13, 6, 19, 1, 1]        // Rule 1 (contains a 7)
[3]                                // Rule 3 (contains a 13)
[3]                                // Print is always done after rule 6
3                                  // Print sum as integer

I'm down to 594 bytes now :-D

@cleblanc I see you're down to 444 now.. I can't compete with that with Java. :) (Funny to say that since 444 is no where near winning compared to all the other answers..)

I know it, even the golfing languages like 05AB1E are almost 100 bytes long.  This challenge was a pain.

Can you leave your list generic List a = new ArrayList()? Might save some bytes. You might need to add a typecast when doing actual arithmetic, though. If not, Long is shorter than Integer

@Poke With a generic List I have to use an (int) cast five times, as well as change the for-each loop from int to Object and add a sixth cast. As for Long: thanks, that saves 1 byte :) (still have to change the for-each from int to long, and r.nextInt(20)+1 to r.nextInt(20)+1L).

Seems perverse to stick with Java 7 when Java 8 has e.g., Random r = new Random(); List<Long> l = r.longs(r.nextInt(6)+5, 1, 21).boxed().collect(Collectors.toList()); And lots of other streamy goodness. If you do it with Java 9 JShell you get pretty much all the imports you need by default as well. ;)

@ceilingcat Thanks. Dang, this is an old answer lol.. Been able to remove about 40 more bytes, and it also contained two bugs that resulted in Exceptions lol.. :/

PowerShell, 525 413 bytes
filter a{"$a"};0..(4..9|random)|%{$a+=@(1..20|random)};a;if(7-in$a){$a=($a|%{$_-1});a;if(0-in$a){$a=($a|%{$_+1});a}}$b=$a;$a=@();foreach($z in $b){if($z-ne13){$a+=@($z)}else{a;break}}if(2-in$a){$a=($a|?{$_%2-eq0});a}if(20-in$a){if($a[2]%2){20*$a.count;exit}else{20;exit}}while(($h=$a-join'+'|iex)-gt50){$a=$a[0..($a.count-2)];a}if(16-in$a){$l=0..9+'a b c d e f'-split' ';$q=[math]::floor($h/16);"$q"+$l[$h%16]};$h

Try it online!
I wanted to attempt this one although I figured I wouldn't beat the answers already here :P I have been attempting to golf this down still, I'm sure it's possible with less bytes. Found a better method for hex, but could probably still improve.
Had to cast $a to a string so many times it was better to create a filter for it...
There were quite a few easy golfs I missed such as parentheses and spaces. Might still be some out there?
Somewhat easier to read code:
filter a{"$a"};0..(4..9|random)|%{$a+=@(1..20|random)};a;
if(7-in$a){$a=($a|%{$_-1});a;if(0-in$a){$a=($a|%{$_+1});a}}
$b=$a;$a=@();foreach($z in $b){if($z-ne13){$a+=@($z)}else{a;break}}
if(2-in$a){$a=($a|?{$_%2-eq0});a}
if(20-in$a){if($a[2]%2){20*$a.count;exit}else{20;exit}}
while(($h=$a-join'+'|iex)-gt50){$a=$a[0..($a.count-2)];a}
if(16-in$a){$l=0..9+'a b c d e f'-split' ';$q=[math]::floor($h/16);"$q"+$l[$h%16]};$h

First try at code golf!
Already beat by other javascripters! Dangit! I will improve!!! =)
Javascript -> 550 402 bytes
Could definitely be improved.
Compressed Now:
f="ba=[];bl;yz5+5`^=0;i<y;i++)a[i]z20+1|~7j-1|~0j+1|}}~13_l=indexOf(13`ql,y-l-Y_^ in a)if(a[i]%2)qi,Y0)&&(!a[3]%2_k'20'`throw new Error(`}do{l=Vreduce((X,num)=>X+num`ifW)qy-1,1`}whileW|kl`~16))kl.toString(16)`~if(Vincludes(|`ka`z=Zound(Zandom()*yVlengthqVsplice(kalert(j_Vmap((i)=>ibvar `);_)){^for(biZMath.rY1|}~2XtotalW(l>50Va.";for(i in g="VWXYZ^_`bjkqyz|~")e=f.split(g[i]),f=e.join(e.pop());eval(f)

Originial:
var a=[];var l;a.length=Math.round(Math.random()*5+5);for(var i=0;i<a.length;i++)a[i]=Math.round(Math.random()*20+1);alert(a);if(a.includes(7)){a.map((i)=>i-1);alert(a);if(a.includes(0)){a.map((i)=>i+1);alert(a);}}if(a.includes(13)){l=indexOf(13);a.splice(l,a.length-l-1);alert(a);}if(a.includes(2)){for(var i in a)if(a[i]%2)a.splice(i,1);alert(a);}if(a.includes(20)&&(!a[3]%2)){alert('20');throw new Error();}do{l=a.reduce((total,num)=>total+num);if(l>50)a.splice(a.length-1,1);}while(l>50);alert(a);alert(l);if(a.includes(16))alert(l.toString(16));

Ruby 2.4, 260 bytes
Ruby 2.4 is required for Enumerable#sum.
p a=(1..s=5+rand(5)).map{1+rand(19)}
a.map!{|i|i-1}if a.index 7
p a
a.map!{|i|i+1}if a.index 0
p a
a.pop s-(a.index(13)||s)
p a
a.reject! &:odd?if a.index 2
p a
a.index(20)?p(20*[1,s][(a[2]||1)%2]):((a.pop;p a)while a.sum>50
p m=a.sum;puts"%x"%m if a.index 16)

Try it online! (Neither repl.it nor tio.run support Ruby 2.4 yet, so this online version replaces sum with inject(:+), which has the same behavior.)

R (3.3.1), 325 bytes
Pretty naive implementation; I think I can probably make it a bit shorter.
s=sample(1:20,sample(5:10,1));print(s);if(7%in%s){s=s-1;print(s);if(0%in%s)s=s+1;print(s)};if(13%in%s){s=s[1:(which(s==13)-1)];print(s)};if(2%in%s){s=s[!(s%%2)];print(s)};if(20%in%s){if(s[3]%%2){20*length(s);print(s)}else{20;print(s)}};while(sum(s)>50){s=s[-length(s)];print(s)};if(16%in%s){print(as.hexmode(sum(s)))};sum(s)

MATLAB, 275 bytes
I originally planned on maybe a one-liner Octave answer, but requiring output of all applied rules thwarted my plans. Instead, a fairly straightforward MATLAB answer with a few interesting optimisations, e.g. the use of cumsum instead of the obvious while for rule 6. Still, a lot of the byte count is wasted on ifs to prevent output if a rule is not applied.
A=randi(20,1,randi(6)+4)
if any(A==7)
A=A-1
if any(~A)
A=A+1
end;end
q=find(A==13,1);if q
A=A(1:q-1)
end
if any(A==2)
A=A(2:2:end)
end
if any(A==20)
if mod(A(3),2)
20*length(A)
else
20
end;return;end
q=cumsum(A)<51;if any(~q)
A=A(q)
end
q=sum(A)
if(any(A==16))
dec2hex(q)
end

Try it online!

Scala 587 bytes one liner
import scala.util.Random;object A{def main(args:Array[String])={val s=5+Random.nextInt(6);var a=new Array[Int](s);for(i<-1 to s){a(i-1)=1+Random.nextInt(20)};p(a);if(a.contains(7)&& !a.contains(1)){a.map(a=>a-1);p(a)};if(a.contains(13)){if(a(0)==13)a=new Array[Int](0)else a=a.slice(0,a.indexOf(13));p(a)};if(a.contains(2)){a=a.filter(pred=>pred%2==0);p(a)};if(a.contains(20)){if(a(2)%2==0)println(20)else println(20*a.length)}else{while(a.sum>50)a=a.dropRight(1);val u=a.sum;if(a.contains(16))println(Integer.toHexString(u));println(u)}};def p[T](a: Array[T])=println(a.mkString(","))}

Scala, 763 bytes as is
import scala.util.Random
object TA {
  def main(args:Array[String])={
    val s=5+Random.nextInt(6)
    var a=new Array[Int](s)
    for (i<-1 to s)
      a(i-1)=1+Random.nextInt(20)
    p(a)
    if(a.contains(7) && !a.contains(1)){
      a.map(a=>a-1)
      p(a)
    }
    if(a.contains(13)){
      if (a(0)==13) a=new Array[Int](0) else a=a.slice(0,a.indexOf(13))
      p(a)
    }
   if(a.contains(2)){
      a=a.filter(pred=>pred%2== 0)
      p(a)
    }
    if(a.contains(20)){
      if (a(2)%2==0) println(20) else println(20*a.length)
    }else{
      while(a.sum>50)
        a=a.dropRight(1)
      val u =a.sum
      if (a.contains(16)) println(Integer.toHexString(u))
      println(u)
    }
  }
  def p[T](a: Array[T])={
    println(a.mkString(","))
  }
}

Since this is  a [tag:code-golf] question we do ask that you make at least the easy golfs such as removing unnecessary whitespace.

I added the one line low byte version

I don't know Scala, but is the space in a: Array[T] required? You have no space in args:Array[String], which is what resulted in my inquiry.

no I think I missed it.

Python 3, 297 293 289, 278 bytes
As Arnauld spotted, you can't get 0 unless rule 1 was applied, which saved on indenting. Thanks to everyone else who commented with suggestions too.
from random import*
p=print
a=b=sample(range(1,20),randint(5,10))
p(a)
if 7in a:a=[i-1for i in a];p(a)
if 0in a:a=b;p(a)
if 13in a:a=a[:a.index(13)];p(a)
if 2in a:a=[i for i in a if~i%2];p(a)
if 20in a and~a[2]%2:a=[20]
while sum(a)>50:a=a[:-1]
b=sum(a)
p(b)
if 16in a:p(hex(b))

Try it online

I don't think you need the space between the and and ~.

i believe from random import* a=b=sample(range(1,20),randint(5,10)) saves some bytes since you can delete line 2.

MATLAB, 228 241bytes
a=randi(20,1,randi(6)+4)
b=@any;
a=a-b(a==7)
a=a+b(a==0)
a(find(a==13,1):end)=[]
a(and(mod(a,2),b(a==2)))=[]
if b(a==20)
a=[a 0 0 0];
s=20*(1+mod(a(3),1)*(numel(a)-4))
else
a(cumsum(a)>50)=[]
s=sum(a)
if b(a==16)
h=['0x' dec2hex(s)]
end
end

This will apply all rules in order, printing the array value after each step.
The program will crash on rule 5 if the resulting number of elements is less than three. There is currently nothing to say what should happen if there is no third element, so I am assuming that a crash is acceptable. The program will now print 20 if there are less than 3 elements and one or more is a 20.
Interestingly step 2 can be applied regardless of whether step 1 was. This is because the input array will never have a 0 in it meaning that if there are any 0's in the array it must be as a result of step 1 having occurred.
All rules are applied in turn, up until 5, even if there are no changes made. As a result the array will be printed at the start and then after each step up until 5. After step 5 you will either get the sum if it is applied, or no output until after step 6. An extra line containing a could be added after the else statement to ensure that the array value is printed after step 5 at the cost of 2 bytes.

I'd also like to mention that I didn't look at the other answers until after I had written this. I see now that there is another MATLAB answer with some similarities - all of which are coincidental.

Common Lisp, 490 bytes
Here the array is represented as a Common Lisp list.
(let((a(loop for i from 1 to(+ 5(random 5))collect(1+(random 19)))))(flet((p()(format t"~a~%"a))(m(x)(member x a))(h(x)(map-into a x a)))(p)(and(m 7)(h'1-))(p)(and(m 0)(h'1+))(p)(let((p(position 13 a)))(and p(setf a(butlast a (-(length a)p)))))(p)(and(m 2)(setf a(remove-if'oddp a)))(p)(or(and(m 20)(or(and(third a)(oddp(third a))(* 20(length a)))20))(p)(and(setf a(loop for x in a sum x into s while (<= s 50) collect x)) nil)(p)(let((s(reduce'+ a)))(print s)(and(m 16)(format t"~x"s))))))

As usual, large use of and and or as control structures.
(let ((a (loop for i from 1 to (+ 5 (random 5))  ; create initial list
            collect (1+ (random 19)))))
  (flet ((p () (format t "~a~%" a))     ; auxiliary functions: print list
         (m (x) (member x a))           ; check membership
         (h (x) (map-into a x a)))      ; operate on elements
    (p)
    (and (m 7) (h '1-))                 ; if 7 is present decrement all values
    (p)
    (and (m 0) (h '1+))                 ; if 0 is now present increment all values
    (p)
    (let ((p (position 13 a)))          ; remove from 13 (if exists)
      (and p (setf a (butlast a (- (length a) p)))))
    (p)
    (and (m 2) (setf a (remove-if 'oddp a)))   ; if 2 is present remove odd values
    (p)
    (or (and (m 20)                            ; if 20 is present
             (or (and (third a)                ;    when third is present
                      (oddp (third a))         ;         and it is odd
                      (* 20 (length a)))       ;         return 20 times the length
                 20))                          ;    otherwise return 20
        (p)                                    ; otherwise (20 is not present)
        (and (setf a (loop for x in a sum x into s ; compute sum of elements
                        while (<= s 50)            ; limited to 50
                        collect x))                ; and return those elements
             nil)                                  ; (to execute the rest of the code)
        (p)
        (let ((s (reduce '+ a)))                   ; compute the final sum
          (print s)                                ; print the result in decimal
          (and (m 16) (format t "~x" s))))))       ; if 16 is present print also in hexadecimal

Perl 6, 246 bytes
my&f={.grep($^a)};my&s=->{.say};$_=[(1..20).pick xx(5..10).pick];s;$_»--
if f 7;s;$_»++ if f 0;s;.splice(.first(13):k//+$_);s;$_=[f*%%2]if f 2;
s;say(20*(.[2]%%2||$_)),exit if $_>2&&f 20;s;.pop while
.sum>49;$/=f 16;$_=.sum;s;.base(16).say if $/

Ungolfed:
my &f = { .grep($^a) };  # Helper function: search $_ for something
my &s = -> { .say };     # Helper function: print $_
$_ = [ (1..20).pick xx (5..10).pick ];  # Generate the initial array
s;  # Print the array
$_»-- if f 7;  # Decrement all elements if it contains a 7
s;  # Print the array
$_»++ if f 0;  # Increment all elements if a zero is found
s;  # Print the array
.splice(.first(13):k // +$_);  # Splice out everything from the first 13 onward
s;  # Print the array
$_ = [ f *%%2 ] if f 2;  # Remove all odd elements if a 2 is found
s;  # Print the array
say(20*(.[2] %% 2 || $_)), exit if $_ > 2 && f 20;  # Print and exit, maybe
s;  # Print the array
.pop while .sum > 49;  # Remove elements from the end until sum is below 50
$/ = f 16;  # Save in $/ whether $_ contains a 16
$_ = .sum;  # Set $_ to its own sum
s;  # Print the sum
.base(16).say if $/  # Print the sum in hexadecimal if the last array contained a 16

Perl 5 -MList::Util=sum, 256 bytes
$,=$";say$_="@{[map{0|1+rand 20}1..5+rand 6]}";/\b7/&&s/\d+/$&-1/ge&&(say)&&/\b0/&&s/\d+/$&+1/ge&say;s/ ?13.*//&&say;@a=/\d+/g;/\b2\b/&&say@a=grep$_%2-1,@a;/20/&&(say$a[2]%2?20*@a:20)&exit;$t=pop@a while($_=sum@a)>50;$t&&say@a;say;"@a"=~/16/&&printf"%x",$_

Try it online!

Vyxal, 82 bytes
6℅4+ƛ20℅;…:7c[‹…:A¬[›…}1J:13ḟẎ…:2cß~₂…D20c[2i₂[20|L20*],Q}1J:¦‡50>ǑẎ…:16c[∑₌,H,|∑,

Try it Online!
Explained
6℅4+ƛ20℅;…:7c[‹…:A¬[›…}1J:13ḟẎ…:2cß~₂…D20c[2i₂[20|L20*],Q}1J:¦‡50>ǑẎ…:16c[∑₌,H,|∑,
6℅4+ƛ20℅;…  # Generate the original array with randint(1, 6) + 4 items, each being randint(1, 20). Print it without popping.
:7c[‹…      # If the array contains a 7, subtract 1 from everything
:A¬[›…}     # If there's 0s after doing that, add 1 to everything
1J:13ḟẎ…    # Find the first occurance of `13` in the array with a 1 appended, and keep everything up to that index. If `13` is not in the array, this will return -1, and will keep everything except the appended 1. Basically, the appended 1 is always removed.
2cß~₂…      # If the array contains a 2, keep only even numbers
D20c[2i₂[   # If there's 20 in the array and the 3rd item (0 if < 3 items) is even:
20          #   Push 20
|L20*       # else, push len(array) * 20
,Q}         # print and terminate
1J:¦‡50>ǑẎ… # find the first item in the cumulative sums of the array where the sum is > 50 and keep until that index. Same logic as the 13 check.
:16c[       # If 16 is in the array
∑₌,H,       # Print the sum as dec and hex
|∑,         # else, just print the sum


text:
Indices of elements in an array in order from smallest to largest
Task
Basically you have an array of random integers e.g.
I() = [1, 4, 3, 2, 5, 3, 2, 1]

and you have to create another array of the same length with the numbers 1 to the size of the array in place of the smallest to largest numbers respectively, e.g.
O() = [1, 7, 5, 3, 8, 6, 4, 2]

For duplicates, the first occurrence is taken as the smaller of the indices.
Test Cases:
Input:   I() = [1, 5, 3, 4, 5, 3, 2, 4]
Output:  O() = [1, 7, 3, 5, 8, 4, 2, 6]

Input:   I() = [1, 5, 3, 2, 5, 3, 2, 4, 6, 6, 5]
Output:  O() = [1, 7, 4, 2, 8, 5, 3, 6, 10, 11, 9]

Rules

It should work with array of any finite length
All integers are positive(greater than 0)
This is code-golf, so the submission with the least amount of bytes wins!

I feel like this must be a duplicate.

@GregMartin I am not sure I am new to golf code so if you can find the link to the same question on golf code I'd be happy to remove this question from here.

Related. (The opposite operation in a way.) (Edit: Actually, it's the same thing...)

Can we assume some upper bound on the input values and list length like 255 or so?

@MartinEnder Yes I think 255 is okay

This is similar to Imitate an ordering where the source is always [1..n] and you have to handle repeats.

Also similar to Rank a list of scores with “skips” which handles ties differently and ranks highest to lowest.

Regardless of all the discussion whether this is a duplicate: nice first challenge and welcome to PPCG!

Unfortunately, after overcoming my general confusion with ordering-based problems, it turns out that this is an exact duplicate of the first challenge I linked.

Haskell, 41 bytes
f l|z<-zip l[0..]=[sum[1|q<-z,p>=q]|p<-z]

Try it online!
Haskell doesn't have build-in sorting, so we have to roll up our sleeves. We pair each element with its index with z<-zip l[0..], then for each pair counts the number of pairs that are smaller or equal. This first compares the values, then tiebreaks by their index.

Bash + coreutils, 28
f()(nl|sort -k2)
f|f|cut -f1

Try it online.

Dyalog APL, 2 bytes
⍋⍋
⍋ is the symbol for grade up - return a permutation that sorts the argument. Applied twice, it does what's asked for in this problem. Indices in Dyalog are 1-based by default.

JavaScript (ES6), 96 bytes
f=(a,b=a.length,c=[...Array(b)])=>(m=a.lastIndexOf(Math.max(...a)),a[m]=0,c[m]=b--,m?f(a,b,c):c)

f=(a,b=a.length,c=[...Array(b)])=>(m=a.lastIndexOf(Math.max(...a)),a[m]=0,c[m]=b--,m?f(a,b,c):c)

console.log(f([1, 5, 3, 4, 5, 3, 2, 4]));

Ruby, 35 bytes
->a{a.zip(1..999).sort.map{|x,y|y}}

Try it online!

source: Stack Exchange

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

sort: votes


text:
Draw a graph of \$y=(-n)^x\$
Challenge
Given an input of an integer, \$n\$ (where \$0<n<50\$), output the graph of \$y=\mathrm{Re}((-n)^x)\$ from \$x = -3\$ to \$x = 3\$ inclusive.
Where \$\mathrm{Re}(p)\$ is the real part of the complex number \$p\$.
Note that \$\mathrm{Re}((-n)^x) = n^x \cos{(\pi x)}\$
Output
The output may be in any form you wish (e.g. an image or a window etc.). ASCII art is disallowed.
The graph does not need to have axes (to allow languages without built-in graphing functions to compete).
If an image is output, it each side must be longer than 500 pixels. Similarly, the plot must fill the image as best it can.
The minimum interval between plots is 0.05.
Vector graphics are allowed.
Examples
For an input of 2:

For an input of 1:

You must put your corresponding outputs in your answer (n = 1 and n = 2).
Winning
The shortest code in bytes wins.

ASCII art is disallowed. (ಥ﹏ಥ)

Can the axes be on the left and bottom edges of the graph? instead of at the centre?

"The axes do not have numbers" but the examples have numbers on the axes

@Kritixi As long as the domain of the graph is from -3 to 3, yes

@Kritixi You'll just have to ignore those since I couldn't find a graphing service without numbers

"If an image is output, it each side must be longer than 500 pixels." Are vector graphics allowed?

@MartinEnder Yes, I suppose so

Should "The axes do not have numbers" read "The axes do not have to have numbers"?

@JonathanAllen Yes, sorry, it was a typo

@BetaDecay Can I suggest making the axes optional to give languages that do not have builtin plot functions a chance?

@Kritixi Axes are now optional

Why am I not surprised to see MATLAB, MATL and Mathematica as some of the first answers. :)

Where is C++? :'(

Your examples are smaller than 500 pixels in both directions.

"The output may be in any format you wish" and "ASCII art is disallowed" contradict each other.

@immibis Not really, when the question tag is [tag:graphical-output]

+1 for banning ascii art >:]

-1 for banning ascii art

MATL, 22 18 16 bytes
Thanks @LuisMendo for additional -2 bytes!
I_.01I3$:i_y^&XG

I_                       push 3 and negate
  .01                    push 0.01
     I                   push 3
      3$:                generate the list [-3,-2.99,-2.98,...,3]
         i_y^            calculate (-input)^(list)
             $XG         plot the first list against the real part of the second list

Try it on matl.io

TI-Basic, 26 21 bytes
~3→Xmin
3→Xmax
Prompt N
DrawF N^Xcos(πX

Output for N=2:

Code screenshot: https://i.stack.imgur.com/jct97.png

I count 47 characters in your code, not 26.

@KonradRudolph See: TI-Basic scoring guidelines.

"If an image is output, it each side must be longer than 500 pixels."  Doesn't seem like the built in graphing capability will work here.

@user5090812 "The output may be in any form you wish (e.g. an image or a window etc.)" - I'm outputting by the graph window, not an image, so this restriction doesn't apply.

Who would've thought that a graphing calculator could graph things!

You can save 4 bytes with DrawF, eg. DrawF N^Xcos(πX

@pizzapants184 You're absolutely right, I should have thought of that! Thanks.

Bash + Gnuplot, 56 45 bytes
(-11 bytes thanks to Noiralef!)
gnuplot -e "se t png;p[-3:3]real((-$1)**x)">A

Saves the resulting graph as a png image named A in the current working directory.
Example Outputs
For n = 1:

For n = 2:

+1 for using a langage I use everyday. (no "garbled binary nonsense" as with golf-langages ^^). This can be re-used in everyday situations.

You can save 11 bytes by using abbreviations: gnuplot -e "se t png;p[-3:3]real((-2)**x)">A

@Noiralef Thanks! :)

Python 3 with matplotlib, 103 72 bytes
-12 bytes thanks to DSM (a module is installed alongside matplotlib called pylab with the necessary functionality "making Python in a repl more like Matlab" - odd, but true!)
-18 more as a result (pylab has many numpy functions too!)
-1 byte thanks to Ajasja (replacing arange(-60,61)/20+0j with arange(121)/20-3+0j)
from pylab import*
def f(n):x=arange(121)/20-3+0j;plot(x,(-n)**x);show()

n=2,1

Can you get rid of from matplotlib.pyplot import* if you start ipython with the --pylab --matplotlib flag?

Have you got iPython; does it work? I suspect it would be acceptable if it does, but would need to ask myself. I don't have iPython and have never had the need to use it.

yup, works with --pylab (tested with python 2)

There is nothing non-standard in any config file making the display work, right? If not I'd say post it as a separate answer on this occasion since it's a clever use of a change of language IMO. EDIT: I see you have golfed it there too :)

Yes, I remembered %pylab gives you numpy as well and if you're in a notebook you don't need a show at the end:)

Wouldn't from pylab import* also give you plot and show?

@DSM, so it would, I had no idea about the existence of that as a separate module - thanks.

That's probably a good sign, it's too stateful an interface and so it's out of favour these days. :-)

Oh wow, yes that is flat; len(dir(pylab))=961 here!

I'm not completely sure if there is a difference between this and Ajasja's answer anymore...

@BetaDecay yes they have certainly merged - the presence of the pylab module here did most of that really. I don't think there is reason to delete though.

Mathematica, 41 bytes
Plot[Re[(-#)^x],{x,-3,3},PlotRange->All]&

Output looks exactly as shown in the challenge except for the font of the numbers (which I suspect was created with Wolfram Alpha).

R, 29 bytes
curve(Re((0i-scan())^x),-3,3)

n is provided through stdin.
Result for n=1:

And for n=2:

Why not use a variable n like the other answers and shave off five characters from your answer? Anyway, crazy answer. I always forget about curve.

@KonradRudolph Thanks. Actually most other answers don't predefine n. The matlab, matl, TI-Basic and mathematica answers take input as stdin (as far as I understand them), while the python and VBA answers create a function. Even if it's allowed, it's just a matter of personal taste: I just don't like predefining variables as a way of input.

Sorry correction: the matlab answers define functions as well.

Well. This is a code golf …

I didn't want to be pedantic or anything but actually as a community we consider that using a predefined variable is not considered a valid input method unless stated explicitely otherwise in the question.

Fair enough but these are merely the default rules. This question seems to explicitly permit it. At any rate most of the other answers just use a variable and make the comparison this harder. My point is, this is, hands down, the shortest solution in a non golf language (minus the weird TI Basic counting rules which are essentially cheating).

Yes you're right and this is why i didn't downvote your answer despite it using that form of input, but allow me to respect the rules i believe in. In addition, as explained in my previous comment, i think your assumption that "most of the other answers just use a variable" is wrong: apart from yours (and maybe the postscript) I don't see any. The others use anonymous functions or, like me, a prompt.

MATLAB, 35 30 bytes
x=-3:.01:3;@(n)plot(x,(-n).^x)

This defines an anyonmous function. The output is via a new window with a resizable vector graphic output. MATLAB's plot automatically ignores the imaginary part of the y-coordinates as long as your provide corresponding x-coordinates.The following output is for n=3.

Would @(n)fplot(@(x)(-n).^x,[-3,3]) work for 29 bytes?

R, 30 bytes
plot(Re((0i-n)^seq(-3,3,.05)))

n = 1

n = 2

Oooh pretty circles

@BetaDecay R’s default rendering is ugly. The rationale for the default is that unfilled circles don’t hide overplotted points as much as filled circles/dots would.

I don't think it's ugly. It looks really cool.

The x axis is labelled incorrectly. I think you need x=seq(-3,3,.05);plot(x,Re((0i-n)^x))

@user2390246 Given that the axes are completely optional, I don’t think it matters. If the axis labelling matters, other answers also have issues due to scaling (e.g. the 30-char MATLAB answer).

OK fair point (though both MATLAB answers look fine to me...)

Excel VBA, 168 160 147 138 Bytes (cells as pixels at 100x scale)
Saved 8 bytes thanks to KyleKanos
Saved 22 bytes thanks to Taylor Scott
Sub g(n)
For i=0To 1
For x=-3To 3Step.01
y=n^x*Cos([Pi()]*x)
m=IIf(y<m,y,m)
If i Then Cells(500*(1-y/m)+1,(x+3)*100+1)="#
Next x,i
End Sub

Formatted, it looks like this:
Sub g(n)
    For i = 0 To 1
    For x = -3 To 3 Step 0.01
        y = n ^ x * Cos([Pi()] * x)
        m = IIf(y < m, y, m)
        If i Then Cells(500 * (1 - y / m) + 1, (x + 3) * 100 + 1) = "#"
    Next x, i
End Sub

Fun Fact: VBA does not have a built-in pi variable so we have to evaluate it as a worksheet function where it does exist.
n=1                                                                         n=2

I started with a chart version at 193 bytes but it did get prettier results.
Sub c(n)
For x=-3To 3Step 0.05
r=r+1
Cells(r,1)=n^x*Cos(Atn(1)*4*x)
Next
With ActiveSheet.Shapes.AddChart(xlLine).Chart
.SetSourceData Range("A1:A121")
.Axes(xlCategory).Delete
End With
End Sub

n=1

n=2

Is it not shorter to use (-n)^x instead of hardcoding pi?

@BetaDecay It would be if Excel could handle negative numbers raised to negative non-integers  ¯\(ツ)/¯

Isn't it shorter to use atn(1)*4 for pi?

@KyleKanos Indeed it is, thanks. I didn't find that identity in my constants lookup table and, as an engineer, that's where I'm legally obligated to stop.

in your chart version, you can drop the cells(r+1,...) call below the r=r+1 call and change it to cells(r,...) for -2; also in your current version, do you think that it would be within the scope of the rules to just add an X into the relevant cell rather than coloring it black?

You can get this down to 138 bytes w/ Sub g(n) For i=0To 1 For x=-3To 3Step.01 y=n^x*Cos([Pi()]*x) m=IIf(y<m,y,m) If i Then Cells(500*(1-y/m)+1,(x+3)*100+1)="# Next x,i End Sub

@TaylorScott That's three new tricks, thanks. That's more valuable than the 7 bytes they saved me this time.

@EngineerToast there are always new tricks to learn about in VBA - like the [{1,2,3}] array declaration notation for Excel VBA :)

Also you can leave the string unterminated - it will autofomat to a closed string, and there is no need to check if i=1, as 1 is a truthy value and 0 is falsy

MATLAB, 35 33 bytes
Thanks fo @flawr for removing 2 bytes!
@(n)ezplot(@(x)real((-n)^x),-3:3)

This defines an anonymous function. To call it with input 2, use ans(2) (or assign the function to a variable such as f and then use f(2)).
Output is vector graphics (resizable window). The sampling interval on the x axis is determined automatically by the ezplot function, but it seems to be more than enough.
A warning is produced in STDERR because the function passed to ezplot (@(x)real((-n)^x)) is not vectorized, but the graph is generated.
Example for n = 2:

ezplot = la-z-plot :D (I keep forgetting about this one...)

Huh. Never knew that you could pass the domain to ezplot like that. Sadly, the same cannot be said for fplot, so no byte can be saved there.

@sanchises I didn't know either :-) It was flawr's idea

Jupyter notebook and Python 3; 53 bytes
%pylab
def f(n):x=arange(121)/20-3+0j;plot(x,(-n)**x)

Three bytes saved thanks to @Jonathan Allan.

Two minor bits: if I read the specs right, you need a minimum of 0.05 (not 0.1) between (effective) points, and we're supposed to be inclusive of 3.

You can use x=arange(-60,61)/20 to fix the issues highlighted by DSM at a cost of 2 bytes. If you add 0j to the arange it can be used to change over to plot(x,(-n)**x) saving 4.

@DSM Ops, fixed.

@JonathanAllan Thanks.

Ah I saved you 2 in total, you just saved me 1 by changing to arange(121)!

I'm not completely sure if there is a difference between this and Jonathan Allen's answer anymore...

@BetaDecay Well, his was first but this one is still shorter. The only remaining difference left is in the use of magic ipython commands...

J, 37 36 bytes
Thanks to my colleague Marshall for guidance. -2 thanks to FrownyFrog.
Anonymous tacit prefix function.
-(]plot@;9 o.^)i:@3j120[load@'plot'

-(]plot@;9 o.^)i:@3j120[load@'plot'
                        load@'plot'       NB. load plotting library
               i:@3j120                   NB. -3...3 in 120 steps
-                                         NB. negate argument
 (           ^)                           NB. raise the negated value to those exponents
 (       9 o. )                           NB. real part
 (]     ;     )                           NB. pair with the exponents
 ( plot@      )                           NB. plot it

I think 20%~i:@60 can be i:@3j120.

@FrownyFrog Correct. Thanks.

Julia 0.6 with Plots.jl, 46 bytes
using Plots
~n=plot(real((0im-n).^(-3:.05:3)))

This needed a Julia representation!
Not much to golf here though, except (ab)using operator overloading to save bytes on function defintion, and using 0im-n to make the input number complex where I might usually have used Complex(n). That's necessary because in Julia, for type stability reasons, the ^ operator returns Complex results only when the input is Complex itself. So here we make it a complex number by adding 0im ie. 0i.
One cool thing about the Plots.jl package is that it automatically chooses the backend to use based on what plotting packages you have installed and where you're running the plot command from. The above plot was created with the GR backend, but if I didn't have that installed (or if I explicitly ran a plotly() command like I did for this), it would have used the more interactive Plotly backend and output this (which looks a tiny bit nicer IMO):

There's even a UnicodePlots backend, to print a plot in the terminal (or save to a text file) using Unicode characters and color codes. SE keeps messing up the plot alignment if I try to directly paste it though, so here's a terminal screenshot:

PS: The alternate formula, \$ Re((−n)^x)=n^xcos(πx) \$, comes out to the same length:
using Plots
~n=plot(n.^(x=-3:.05:3).*cospi(x))

Dang, that's some clever (ab)use of the Braille characters.

45 bytes

Desmos, 12 10 9 bytes
-2 thanks to @Steffan
-1 thanks to @LeoDog896
n^xcosxπ

How has nobody used Desmos yet?

You can do n^xcosx\pi for 10 bytes

Huh, it appears you can. I didn't realize you could say just cos rather than \cos.

You can also use the pi symbol itself, which is 2 bytes but replaces the 3 bytes taken up by \pi: n^xcosxπ

Encapsulated PostScript; 232 bytes
%!PS-Adobe-3.0 EPSF-3.0
%%BoundingBox: 0 0 500 500
%%EndComments
/n 1 def .02 setlinewidth /f{dup dup n exch exp exch 180 mul cos mul 3 div}def
250 250 translate 80 80 scale newpath -3 f moveto -3 .05 3{f lineto}for stroke
%%EOF

Now since this is a vector image itself...

Ooh that is nice

TikZ + PGFPlots, 175 bytes
\documentclass{standalone}\usepackage{tikz,pgfplots}\begin{document}\typein[\n]{}\tikz{\begin{axis}\addplot[domain=-3:3,samples=120]{\n^x*cos(180*x)};\end{axis}}\end{document}

Compile with, e.g., latexmk -cd -f -pdf in.tex for a pdf output. During compilation, the user is prompted for n.
Sample outputs (converted to png) for n = 1 and n = 2:

Math.JS Grapher, 20 Bytes
r(n)=f(x)=re((-n)^x)

By sheer fluke, this graphing utility is TC (For the most part, Infinite loops just crash it.), and by nature, it's primary output is graphs.
How it works
r(n)= assigns a function r which takes the argument n to the expression f(x)=re((-n)^x). re((-n)^x) is pretty much letter for letter the challenge description. But this assigns the function f(x) to this, which the grapher implicitly outputs as a line graph.
How to test it
You can use this site, punch that function in there, then call it with r(input).
Output

Excel VBA, 133 bytes
Immediate window script that takes input from [A1] and outputs a Chart object to the Sheet1 object.
[B:B]="=ROW()/20-3.05":[C:C]="=A$1^B1*Cos(Pi()*B1)":Set c=Sheet1.Shapes.AddChart(4).Chart:c.SetSourceData[C1:C121]:c.Axes(1).Delete

Ungolfed
Full Subroutine  version. I/O is unchanged.
Sub b()
    [B:B] = "=ROW()/20-3.05"                ''  Define `x`-axis
    [C:C] = "=A$1^B1*Cos(Pi()*B1)"          ''  Define `y`-axis in terms of input from A1
    Set c = Sheet1.Shapes.AddChart(4).Chart ''  Add line plot to Sheet1 (xlLine)
    c.SetSourceData [C1:C121]               ''  Set `y` source to match `x` in [-3,3]
    c.Axes(1).Delete                        ''  Remove erroneous axes (xlCategory)
End Sub

Output
Where input, \$n=1\$

Where input, \$n=3\$

Dyalog APL, 41 bytes
⎕SE.UCMD∊'chart x(9○(-'⍞')*x←3-20÷⍨⍳121)'

How it works:
⎕SE.UCMD∊'chart x(9○(-'⍞')*x←3-20÷⍨⍳121)' ⍝ Main function
⎕SE.UCMD∊                                 ⍝ User Command (called from the session object)
         'chart                           ⍝ Plot a chart with arguments:
                 (           3-20÷⍨⍳121)' ⍝ Yields the list [-3, -2.95, -2.9,..., 2.9, 2.95, 3]
                           x←             ⍝ Assign that list to x
                          *               ⍝ and use it as exponent
                    (-'⍞')                ⍝ with (-input) as base
                  9○                      ⍝ discard the complex part; this generates Re((-n)^x)
                x                         ⍝ And x.

The user command ]chart, in this case, takes two vector arguments, x and y and plots the graphs:
For \$n=1\$:

For \$n=2\$:

Google Sheets, 65

Input N is in A1

Graphing:

=SPARKLINE(ArrayFormula(IMREAL(IMPOWER(-A1,.05*SEQUENCE(121,1,-60
or
=SPARKLINE(ArrayFormula(IMREAL(IMPOWER(-A1,SEQUENCE(121,1,-60)/20

Resize row and column of graph to 500x500.
I tried to use the COS() formula, but the best I can do is 66 characters with a named range. Problems that I came across:

X is generated by the SEQUENCE(), which is then used twice. You would naturally think to cache this, but every time you cache into a column, to use it again, you have to either name a range, or use a FILTER. Named Range is obviously better, but it does cost 1 character to make it fair.
Attempting to scalar multiply a SEQUENCE() forces us into an ArrayFormula (or MMULT() at best), and we cannot use a non-integer step for SEQUENCE(). This means that the most optimal way to use it is to give it to the SPARKLINE formula.
This also means that our scalar multiply/divide has to occur each time we use the range.

SmileBASIC, 82 bytes
INPUT N
FOR I=0TO 399X=I/66.5-3GPSET I,120-POW(N,X-3*SGN(N-1))*COS(PI()*X)*120NEXT

Graph fills the entire screen, even when N is less than 1.
When N is greater than 1, you can scale Y to be between -1 and 1 by dividing it by n^3. I'm already doing n^x, and n^x / n^3 can be simplified to n^(x-3). However, when N is less than 1, I have to divide Y by n^-3 instead. This is equivalent to n^(x+3).
I can use n^(x-3*sign(n-1)) to use -3 if n>1, and +3 if n<1
Images coming soon

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

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


text:
Verify Eigenpairs
In this challenge, you will be given a square matrix A, a vector v, and a scalar λ. You will be required to determine if (λ, v) is an eigenpair corresponding to A; that is, whether or not Av = λv.
Dot Product
The dot product of two vectors is the sum of element-wise multiplication. For example, the dot product of the following two vectors is:
(1, 2, 3) * (4, 5, 6) = 1*4 + 2*5 + 3*6 = 32

Note that the dot product is only defined between two vectors of the same length.
Matrix-Vector Multiplication
A matrix is a 2D grid of values. An m x n matrix has m rows and n columns. We can imagine an m x n matrix as m vectors of length n (if we take the rows).
Matrix-Vector multiplication is defined between an m x n matrix and a size-n vector. If we multiply an m x n matrix and a size-n vector, we obtain a size-m vector. The i-th value in the result vector is the dot product of the i-th row of the matrix and the original vector.
Example
        1 2 3 4 5
Let A = 3 4 5 6 7
        5 6 7 8 9

        1
        3
Let v = 5
        7
        9

If we multiply the matrix and the vector Av = x, we get the following:
x1 = AT1 * v /* AT1 means the first row of A; A1 would be the first column */ = (1,2,3,4,5) * (1,3,5,7,9) = 1*1 + 2*3 + 3*5 + 4*7 + 5*9 = 1+6+15+28+45 = 95
x2 = AT2 * v = (3,4,5,6,7) * (1,3,5,7,9) = 3*1 + 4*3 + 5*5 + 6*7 + 7*9 = 3+12+25+42+63 = 145
x3 = AT3 * v = (5,6,7,8,9) * (1,3,5,7,9) = 5*1 + 6*3 + 7*5 + 8*7 + 9*9 = 5+18+35+56+81 = 195
So, we get Av = x = (95, 145, 195).
Scalar Multiplication
Multiplication of a scalar (a single number) and a vector is simply element-wise multiplication. For example, 3 * (1, 2, 3) = (3, 6, 9). It's fairly straightforward.
Eigenvalues and Eigenvectors
Given the matrix A, we say that λ is an eigenvalue corresponding to v and v is an eigenvector corresponding to λ if and only if Av = λv. (Where Av is matrix-vector multiplication and λv is scalar multiplication).
(λ, v) is an eigenpair.
Challenge Specifications
Input
Input will consist of a matrix, a vector, and a scalar. These can be taken in any order in any reasonable format.
Output
Output will be a truthy/falsy value; truthy if and only if the scalar and the vector are an eigenpair with the matrix specified.
Rules

Standard loopholes apply
If a built-in for verifying an eigenpair exists in your language, you may not use it.
You may assume that all numbers are integers

Test Cases
 MATRIX  VECTOR  EIGENVALUE
 2 -3 -1    3
 1 -2 -1    1    1    ->    TRUE
 1 -3  0    0

 2 -3 -1    1
 1 -2 -1    1    -2   ->    TRUE
 1 -3  0    1

 1  6  3    1
 0 -2  0    0    4    ->    TRUE
 3  6  1    1

 1  0 -1    2
-1  1  1    1    7    ->    FALSE
 1  0  0    0

-4 3    1
 2 1    2    2    ->    TRUE

2    1    2    ->    TRUE

I will add a 4x4 later.
Unreadable Test Cases that are easier for testing

Related.

@MartinEnder Thanks. I originally had a similar challenge for arbitrary sized matrices where you were meant to calculate a basis for each unique eigenspace but that's in the sandbox still because it seems too confusing.

If inputs can have have other dimensions than 3x3, you should cover some of that in your test cases.

Also while the test case format is very readable, it's a pain to copy, because (just looking at a byte stream) the three arguments are all interleaved.

@MartinEnder Alright, I'll add a 2x2 and 4x4 test test case and link to a pastebin with more (un)readable(?) I/O.

So can we assume that the input is at least 2x2? Can it be 1x1?

I looked through this question and understood less about it afterwards :)

@ThisGuy Eigensystems are probably just on the other side of what you can reasonably learn from the specification of a PPCG challenge if you're not familiar with it beforehand. It's not a terribly difficult concept though, so if you read up on it on Wikipedia or some other online resources, the challenge should be clear quite quickly.

@ThisGuy Don't worry, it took me a few months to get up to this point. The core of the challenge is really just checking if a matrix times a vector is the same as a number times that vector.

@MartinEnder No, I'll add a 1x1.

@user00001 If you need help, eigenpair-aphrase it for you. :P

Jelly, 5 bytes
æ.⁵⁼×

This is a triadic, full program.
Try it online!
How it works
æ.⁵⁼×  Main link
       Left argument:  v (eigenvector)
       Right argument: λ (eigenvalue)
       Third argument: A (matrix)

  ⁵    Third; yield A.
æ.     Take the dot product of v and A, yielding Av.
    ×  Multiply v and λ component by component, yielding λv.
   ⁼   Test the results to the left and to the right for equality.

_> this is too short :P Nice answer

That's crazy talk! :P

You write something, and think "nothing could be shorter!". Then MATL comes along and halves your code size. Then Jelly comes along and halves that >_>

@HyperNeutrino Don't compare apples to oranges. Golfing languages have as little as one byte per operation, something normal languages rarely have. The spec has three operations (two multiplications and an equality), and allowing for an extra byte to duplicate v one could expect as little as four bytes.

I like how both Jelly and MATL use two bytes for matrix multiplication, which means that this answer really shows how good Jelly is at taking input, all else being equal.

Mathematica, 10 bytes
#2.#==#3#&

Takes input like {vector, matrix, scalar} and returns a boolean.

_> this was too easy for Mathematica. +1 :P

@HyperNeutrino And now we wait for MATL...

Well MATL has appeared >_>

One of those moments when you think nothing can be shorter and MATL pops up suddenly :)

@Mr.Xcoder And then Jelly shows up.

Suppose we're waiting for 05AB1E now @Steadybox

MATL, 7 bytes
*i2GY*=

Inputs in order: l,v,A.
Explanation:
*  % implicitly get l and v, multiply.
i  % get A
2G % get second input, i.e., v again
Y* % perform matrix multiplication
=  % test equality of both multiplications

Surprisingly long answer, if you ask me, mostly because I needed a way to get all the input correctly. I do not think that less than 5 bytes is possible, but it would be cool if someone found a 5 or 6 byte solution.
Basically, this calculates l*v==A*v.

"Surprisingly long" I was expecting at least 20 bytes >_> nice answer though :P

Well, considering that the MATLAB answer would come in at 16 bytes @(A,v,l)A*v==v*l, this seems quite verbose, and I have a feeling 6 should be plenty if I get the input somewhat smarter.

Apparently it came in at 38 bytes but I'm pretty sure it can be golfed down.

@HyperNeutrino Added my own to make the previous comment true. (or truthy...?)

CJam, 15 bytes
q~W$f.*::+@@f*=

Takes input in the form vector scalar matrix.
Try it online!
Explanation
q~               e# Read and eval the input
  W$             e# Copy the bottom most value (the vector)
    f.*::+       e# Perform element-wise multiplication with each row of the matrix, then
                 e#   sum the results of each (ie dot product with each row)
          @@     e# Move the resulting vector to the bottom of the stack
            f*   e# Element-wise multiplication of the scalar and the vector
              =  e# Check if the two vectors are equal

MATLAB, 16 bytes
@(A,v,l)A*v==v*l

Rather trivial answer. Defines an anonymous function taking the inputs, and calculates element-wise equality of the resulting vectors. A single zero in a logical array makes an array falsey in MATLAB.

Wasn't aware of the falseyness of e.g. [true,false], thanks for teaching me=)

@flawr See this answer by Suever (which is also applicable to MATLAB). Basically, an almost-but-not-quite (empty matrix [] is different) implicit all() is called on the input of if, while etc.

MATLAB, 38 bytes
function r=f(m,v,s);r=isequal(m*v,s*v)

Returns 1 or 0.
MATLAB, 30 bytes
function r=f(m,v,s);r=m*v==s*v

Returns
1
1
1

as a truthy value. A falsy value is a similar vector with any or all values 0 instead of 1.

I don't know MATLAB, but can the isequal function be shortened to ==?

@HyperNeutrino isequal would be needed if the output required true or false rather than a truthy or falsey value. As the challenge stands, == is indeed enough.

@HyperNeutrino It would return a vector containing the results of elementwise comparison of the two vectors.

Oh okay. Nice answer though!

wouldn't an annonymous function be shorter?

C++, 225 203 bytes
Thanks to @Cort Ammon and @Julian Wolf for saving 22 bytes!
#import<vector>
#define F(v,i)for(i=0;i<v.size();++i)
using V=std::vector<float>;int f(std::vector<V>m,V v,float s){V p;int i,j;F(m,i){p.push_back(0);F(v,j)p[i]+=v[j]*m[i][j];}F(v,i)v[i]*=s;return v==p;}

Try it online!

using std::vector; could golf two bytes off this.  It costs 18 bytes, but can remove 4 std::s, saving 20.

better yet, using V=std::vector<float>; or similar

Python 2.7, 33 bytes
f=lambda m,s,e:all(m.dot(s)==e*s)

input: m=matrix, s=scalar, e=eigenvalue. M and s are numpy arrays

This looks good, but I think you need to include the byte count of import np for it to be valid

You can just import it as n. Also, where are m, s, and e coming from? you need to either input them or make a lambda function

Thank you for your suggestions. This is my first code golf. This one caught my attention, but I don't really know all the rules yet. So it is better now?

Nice first answer! This is currently invalid because m, s, and e are not defined. However, if you remove the f= part and the entire last line, it's a valid anonymous function, and it's shorter.

Done. What do you mean by not defined?

Your previous print(m,s,e) statement would not have worked because the variables m, s, and e were not yet assigned/defined. Also, you can remove the space after the colon. Also, you can remove the  as n part and just use numpy later on; since you only use it once, using the full name actually saves a byte.

Ok, I understand now. Thank you for the suggestions, squeezing every bit :)

Shouldn't it be all instead of any? And I think s is the vector, not the scalar, unless I'm missing something

You could do m.dot(s). And I think it should be all as well. And I don't think the second set of parens around e*s is necessary.

It would be even shorter to compare string representations. https://tio.run/nexus/python2#jZDPCoMwDIfP@hQ9tiOV/hEHgk/ihHaoIKwqrTv49C7Wue242y/Jx0eSnlTktj2su7eWOAjQlcZl7bTQwExVme4STDq4efILGZ9uXrd@8oRGkpFhJDRNElrXCrgGLhuoJXD1SRpEg0mDxACSwT@0RBo7XJ24hAI0DsQOi@grkIio2NH8S4rDxt@S2IlWdexwPVGeR6c6RaoBxdKElTie/TAupKfx4sx6b1fqGPyWgeEDthc

@Dennis: Except that NumPy abridges repr representations by default for large arrays, and getting around that (for example, with numpy.set_printoptions) costs too many bytes.

Yes, if the multiplication of m and s is not equal to e*s but some of the numbers on same positions are same, then any() wouldnt work I guess. Hence I put back .all().

I think you can get rid of 4 bytes by removing an extra space and using all() rather than .all(): f=lambda m,s,e:all(np.dot(m,s)==e*s), you're still using np.dot() rather than numpy.dot() so it's actually only -1 byte to get it working: f=lambda m,s,e:all(numpy.dot(m,s)==e*s)

Trivial improvement: use m.dot(s) instead of numpy.dot(m,s), and get rid of the import numpy entirely. On Python 3, you can use m@s to reduce things further.

Python 3, 96 70 bytes
No builtins for matrix-vector or scalar-vector multiplication!
lambda A,L,v:all(L*y==sum(i*j for i,j in zip(x,v))for x,y in zip(A,v))

Try it online!
-26 bytes by using zip thanks to @LeakyNun!

Try to use zip: f=lambda A,L,v:all(L*y==sum(i*j for i,j in zip(x,v))for x,y in zip(A,v))

Julia, 17 bytes
(a,b,c)->a*b==b*c

Try it online!

R, 30 25 bytes
s=pryr::f(all(a%*%v==λ*v))

Anonymous function, fairly straightforward. Returns TRUE or FALSE.

05AB1E, 11 bytes
vy²*O})²³*Q

Try it online!
vy²*O})     # Vectorized product-sum.
       ²³*  # Vector * scalar.
          Q # Equivalence.

oK, 12 bytes
{y~z%+/y*+x}

This is a function, it takes in [matrix;vector;scalar].
This does not work in k for the same reasons that 3.0~3 gives 0 as a result.

The following works in k, with 14 bytes:
{(y*z)~+/y*+x}

Python, 26 bytes
lambda a,b,c:c*b==a.dot(b)

a and b are numpy arrays, c is an integer.
Try it online!

Are the parens around c*b actually necessary?

@xnor thanks, fixed.

This only works for small arrays, since NumPy abridges large array string representations.

@user2357112 example? I'm not sure what you mean.

If c*b has more than 1000 elements, NumPy will replace most of the elements with .... Demo.

@user2357112 fixed.

== doesn't work like you're thinking for NumPy arrays. Here, it will produce a vector of elementwise comparison results.

@user2357112 it returns [True, True, True], which is a truthy value. It's a valid result.

@Riker: It's not actually truthy; a list looking like that would be truthy, but the result is a NumPy array, and it will outright throw a TypeError if you try to interpret it as a boolean. Also, even if it were a list, it would then be truthy regardless of whether the input was a valid eigenpair.

@user2357112 I've gotten confirmation from OP that the method of output was acceptable, and that the list will be shorter than 1k (so my original answer also works).

Related scoring meta post

Axiom, 27 bytes
f(a,b,c)==(a*b=c*b)@Boolean

exercises
(17) -> m:=matrix[[2,-3,-1],[1,-2,-1],[1,-3,0] ]; v:=matrix[[3],[1],[0]];
(18) -> f(m,v,1)
   (18)  true

(19) -> m:=matrix[[2,-3,-1],[1,-2,-1],[1,-3,0] ]; v:=matrix[[1],[1],[1]];
(20) -> f(m,v,-2)
   (20)  true

(21) -> m:=matrix[[1,6,3],[0,-2,0],[3,6,1] ]; v:=matrix[[1],[0],[1]];
(22) -> f(m,v,4)
   (22)  true

(23) -> m:=matrix[[1,0,-1],[-1,1,1],[1,0,0] ]; v:=matrix[[2],[1],[0]];
(24) -> f(m,v,7)
   (24)  false

(25) -> m:=matrix[[-4,3],[2,1] ]; v:=matrix[[1],[2]];
(26) -> f(m,v,2)
   (26)  true

(27) -> f(2,1,2)
   (27)  true

I haven't seen this language before, nice answer! What does the @Boolean do?

(a=b)@Boolean would mean "choose among allowed =operator(type1,type2) the one its result is Boolean"; in few words "a=b" has to be Boolean

Clojure, 60 bytes
#(=(set(map(fn[a v](apply -(* v %3)(map * a %2)))% %2))#{0})

This checks that all deltas are zero, thus collapsing into the set of zero. Calling example:
(def f #(=(set(map(fn[a v](apply -(* v %3)(map * a %2)))% %2))#{0}))
(f [[1 6 3][0 -2 0][3 6 1]] [1 0 1] 4)


text:
Cheeky bus driver
The bus driver picks up the children from their homes every morning for school. All the homes are positioned around a circular street and the bus driver has to stop at every home exactly once.
One monday morning the bus driver decided to only pick up every second child he encountered along his way. However, he still had to pick up every single children, so this meant he was willing to go multiple rounds.
The houses are indexed from 1 to N (they come in order). The bus driver starts at the first (index 1) house and does not change directions during his trip. You must find the index of the house the last child is picked up from.
Input
A single positive number N read from the standard input representing the number of houses along the street.
Output
Output the index of the house the last child is picked up from to the standard output.
Example
Input: 10
Output: 4
The order of pickups are as follows: 1 3 5 7 9 2 6 10 8 4
Shortest code wins!

Why the restrictive input/output? It is common to allow anonymous functions that take an argument as input and return a value as output, as well as STDIN and STDOUT.

This is a special case of this challenge, but since this problem has a closed form solution for k = 2, it might be worth keeping this open separately.

@MartinEnder That makes it more of a dupe of this one, which is currently closed as a dupe of the other :/

I guess it's also subtly different because this one counts out the first in each pair, not the second.

That's the same as the ninja challenge though.

Next time, try posting in the sandbox first.


text:
Fold Some Towels!
I heard somewhere that one thing that technology cannot do yet is fold towels1. So it is now your job to prove that statement false!
Given a string as input, made up of rectangles (towels), like the following, fold each towel in half twice. For example:
+------+    +------+        +--+
|      |    |      |        |  |
|      |    |      |        |  |
|      | -> +------+ ->     +--+
|      |
|      |
|      |
+------+

Notice that when a towel is folded, it is first folded up, then from left to right. You program must mimic this behavior as well. Also notice that in the test cases, the towels stays in the same place, but folded.
Rules:

Standard methods of input/output.
Standard loopholes apply.
Input and output should be as a string.
Trailing whatevers are okay in output, as long as the towels are in the right place relative to each other.
You may assume that the length of each side of the towel will always be divisible by 2.
The towels passed as input will always be rectangular.
The towels will always be separated-- however, they may be separated by variable amounts.
code-golf, so shortest code wins!

Test cases:
Input:
+------+
|      |
|      |
|      |
|      |
|      |
|      |
+------+
Output:
    +--+
    |  |
    |  |
    +--+

Input:
+--+ +--+ +--+
|  | |  | |  |
|  | |  | |  |
+--+ +--+ +--+

Output:
  ++   ++   ++
  ++   ++   ++

Input:
+----+
|    |
|    |
|    |
|    | ++
+----+ ++

Output:

   +-+
   | |
   +-+

        +

Input:
+--+
+--+     ++
         ||
         ||
         ++
Output:
  ++
          +
          +

1: This has been disproved by Geobits and Laikoni. However, I did hear it somewhere.

Why the downvote? If there is something that can be fixed, please tell me.

Video of towel folding robot.

@Laikoni it seems like tech CAN do anything :-)

@LuisMendo Edited, there will always be space between the towels.

Given towels will always line horizontaly? I mean there won't be any towel under other one?

@DeadPossum They will always be next to each other, however they will not always be in line, like in the last test case.

How does ++\n++ become +? ohhh... fuuuu... it does.

Retina, 245 bytes
m1+`^((.)*(?!\+ )[+|]([- ])*[+|].*¶(?<-2>.)*)([+|][- ]*[+|])
$1$.4$*
m+`^((.)*) ( *) (.*¶(?<-2>.)*)(?(2)(?!))\|\3\|
$1|$3|$4 $3
m+`^((.)*)\|( *)\|(?=.*¶(?<-2>.)*(?(2)(?!)) )
$1+$.3$*-+
([+|])\1
 $1
(?!\+ )([+|])([- ])\2(\2*)\3\1
$.3$*   $1$3$1

Try it online!
Note: some lines end in spaces. Explanation:
m1+`                    Repeatedly search from the beginning of input
    ^((.)*              Optional indentation
      (?!\+ )           Towel does not start with a plus and a space
      [+|]([- ])*[+|]   A row of towel
      .*¶               Rest of the line
      (?<-2>.)*         Some indentation on the next line
     )
     ([+|][- ]*[+|])    Another row of towel
$1$.4$*                 Replace the second row with blanks

Delete every other line of every towel (this works because all towels have even height),
m+`             Repeatedly search
   ^((.)*)      Optional indentation
    ( *)        Find some space
    (.*¶        Rest of the line
     (?<-2>.)*) Matching indentation on the next line
    (?(2)(?!))  Ensure that the indentation exactly matches
    \|\3\|      Piece of towel
$1|$3|$4 $3     Swap the piece into the space above

shift all the detached towel pieces up,
m+`                 Repeatedly search
   ^((.)*)          Optional indentation
    \|( *)\|        Piece of towel
    (?=             Followed by
       .*¶          Rest of the line
       (?<-2>.)*    Matching indentation on the next line
       (?(2)(?!))   Ensure that the indentation exactly matches
        )           Nothing on the next line
$1+$.3$*-+          Change the piece into a towel bottom

and fix the bottom of the towels, effectively folding them up.
([+|])\1    Match a row of towel of width 2, which is just ++ or ||
 $1         Change the first column to a space, which folds it

Fold the towels of width 2 to the right.
(?!\+ )     Towel does not start with a plus and a space
([+|])      Start with a + or a |
([- ])\2    Then at least two -s or spaces
(\2*)\3     Then an even number of -s or spaces
\1          Then another + or |
$.3$*       Replace the left half with spaces
$1$3$1      Replace the first character of the right half

Fold the remaining towels to the right.

I would be interested in a more detailed explanation on how the regex works

@KritixiLithos Something like that, or was there something specific?

Yes, thank you. And am I correct in assuming that <-2> is a .NET balancing group?

@KritixiLithos It uses them: (?<-2>.)* pops the capture each time, so cannot repeat more times then the (.)* did, while (?(2)(?!)) checks that there are no captures left, so that it repeated the same number of times.

Octave with Image Package, 277 272 bytes
function x=f(x)
[i,j,v]=find(bwlabel(x-32));a=@(w)accumarray(v,w,[],@max);r=-a(-i);R=a(i);s=-a(-j);S=a(j);x(:)=32;for k =1:nnz(r)
u=(r(k)+R(k)-1)/2;v=(s(k)+S(k)+1)/2;p=v:S(k);x(r(k),p)=45;x(u,p)=45;q=r(k):u;x(q,v)=124;x(q,S(k))=124;x(u,[v S(k)])=43;x(r(k),[v S(k)])=43;end

Input and output are 2D char arrays.
Try it online! Or verify all test cases: 1, 2, 3, 4. (Note that endfunction in the test cases is only needed to separate the function from the subsequent code. It is not necessary if the function is saved in its own file.)
Readable version and explanation
function x = f(x)
[i,j,v] = find(bwlabel(x-32)); % make background equal to 0 by subtracting 32.
% Then label each connected component (i.e. towel) with a unique integer
% Then get row indices (i) and column indices (j) of nonzero values (v)
a = @(w)accumarray(v,w,[],@max); % helper function. Gives the maximum of w for
% each group given by an integer label in v
r = -a(-i); % upper coordinate of each towel (minimum row index)
R = a(i); % lower coordinate of each towel (maximum row index)
s = -a(-j); % left coordinate of each towel (minimum column index)
S = a(j); % right coordinate of each towel (maximum column index)
x(:) = 32; % remove all towels: fill x with spaces
for k = 1:nnz(r) % for each original towel: create the new, folded towel
    u = (r(k)+R(k)-1)/2; % new lower coordinate
    v = s(k)+S(k)+1)/2; % new left coordinate
    p = v:S(k); % column indices of horizontal edges
    x(r(k),p) = 45; % fill upper horizontal edge with '-'
    x(u,p) = 45; % fill lower horizontal edge with '-'
    q = r(k):u; % row indices of vertical edges
    x(q,v) = 124; % fill left vertical edge with '|'
    x(q,S(k)) = 124; % fill right vertical edge with '|'
    x(u,[v S(k)]) = 43; % fill lower corners with '+'
    x(r(k),[v S(k)]) = 43; % fill upper corners with '+'
end


text:
My source is in order, is yours?
Your challenge is to write a program, function, etc. that calculates if the passed string is "in order". That means that the characters of the string have character codes that are in order from smallest to largest.  The smallest char code must be the first. By that I mean lowest unicode codepoints to highest. It doesn't matter what code page you language uses.
You must return one value if the input is "in order" and another if it is not. The values must be distinct, but there is no other restriction on the output values. For example, you may print/return/output true for !1AQaq¡± (in order) and false for aq!QA.  The two distinct values don't need to be truthy or falsy or anything like that, just two distinct values. Repeated strings (eg. aa) are in order.
You only need to support up to unicode U+007E (~) (ascii 126)
However, the characters of your program must itself be in order. Good luck and happy code-golfing!

You don't need to have truthy/falsy values? two truthys would work?

Also, is the smallest char code always at the first char? Or can it be reversed?

There's no such thing as a "UTF-8 character". You probably just mean "the characters of the strings have character codes that are in order from smallest to largest".

@RIker the values have to be distinct. It says that.

@programmer5000 yes, but you don't need 1 falsy and 1 truthy?

@Riker no, just 2 distinct values. 2 and 3 would work.

Code-golf honestly seems like a poor win condition for this form of restricted source. Code bowling for most unique characters would be more interesting.

@fəˈnɛtɪk interesting idea, but then in a lot of langs it amounts to doing it in the lowest code points possible, then fitting in as much garbage as possible. My choice for this would be pop-con.

@Pavel Pop cons don't work well for achieving a particular task in a particular way.

is repeated string in order? for example, is "aa" in order?

By what standard do characters need to be 'in order' in the source code? By Unicode codepoints, or in their own codepages? Point in case: Jelly (Ṣ⁼ vs ⁼Ṣ).

@steenbergh see edit.

Is the empty string a valid input?

@Aaron technically no, but I won't require you to support it.

OK, who is downvoting?

Brachylog, 2 bytes
.o

Try it online!
Explanation
.o
.   Assert that {the input} equals the output of the last command in the program
 o  Sort {the input}

As a full program, an assertion failure gives false., any successful run that doesn't violate any assertions gives true.

Jelly, 2 bytes
Ṣ⁼

Try it online!
Explanation
Ṣ⁼
Ṣ    Sort {the input}
 ⁼   Compare that to {the input} for equality of the whole structure

⁼Ṣ also has the right functionality ("compare the input to the sorted input"), so it was just a case of running the two programs on themselves to figure out which was in order (I certainly don't have the Unicode codepoints of this part of Jelly's weird character set memorized).

Your submission is wrong in Jelly encoding, it needs to be ⁼Ṣ instead. You can see Jelly's codepage here.

@EriktheOutgolfer That is easily fixed; ⁼Ṣ does exactly the same as Ṣ⁼.

@steenbergh This submission, as it is right now, is invalid. Even though the fix is easy, it hasn't been applied yet, and it's discouraged for others to edit code.

@EriktheOutgolfer Discussion about this answer is mainly about which codepage to use: the challenge references Unicode (though doesn't explicitly tell us to use it) and Jelly has its own codepage. Whatever the outcome, fixing this answer is trivial. Therefor, I wouldn't go as far as calling this answer 'invalid' - I wouldn't even downvote it in its current state.

@steenbergh I haven't downvoted either, I was just notifying ais523 :)

@EriktheOutgolfer OP just edited challenge and specified Unicode as 'the order of things'. This answer seems to be valid, then.

Let us continue this discussion in chat.

MATL, 5 bytes
GGS\a

Outputs 0 if input is in order, 1 otherwise.
Try it online!
Explanation
This computes the modulus of (the code points of) each char from the input with that at the same index in the sorted input. The input is in order if and only if all results are 0.
For example, consider the input string BCD!. Sorting it gives '!BCD. The arrays of code points are respectively [66 67 68 33] and [33 66 67 68]. Computing the moduli gives [0 1 1 33], so the input is not in order. Note how some results can be 0 even if the values were not the same (here that happens at the first position), but that cannot happen in all entries unless the input is in order.
G     % Push input string
GS    % Push input string and sort it
\     % Modulus, element-wise. This gives all zeros iff the input was in order
a     % Any: gives 1 if any entry is non-zero. Implicitly display

05AB1E, 3 2 bytes
{å

Thanks to Kevin for cutting out 33% of my source code!
Try it online!
Explanation:
      There used to be a D here for 'Duplicate stack'
      but we now use the same input twice implicitly
 {    Sort the copy
  å   Check if the sorted copy is a substring of the original
      This will only return 1 if the original input is sorted, 0 otherwise.

D{Q also works...

@NeilA.It might do the same, but the characters are not in order. Requirement is that your source code passes the same test as the data does. This should yield 1.

The D can be removed for -1 by just using an implicit input twice.

Pyke, 2 bytes
Sq

Try it online!
S  - sorted(input)
 q - ^ == input

2sable, 2 bytes
{Ê

Try it online!
Explanation
{    # sorted input
 Ê   # not equals (implicit input)

Outputs 0 if it is order, else 1.

@steenbergh: Ah, missed that part of the challenge.

@steenbergh: Fixed! Fortunately we could output any distinct values :)

Pyth, 2 bytes
<S

False means sorted, True means unsorted.
Test suite
This was fairly nontrivial to come up with. The most obvious solution to this problem, without the restricted source, is SI, invariant under sorting. But that's not sorted. Then I thought of qS, which implicitly uses the input variable twice, checking if it's equal to its sorted self. But while q < s, q > S, so this didn't work either. But < comes before S, and the only way that the sorted version can not be less than the original is if the original was sorted, since the sorted version is the lexicographically minimal permutation of the elements.

CGL (CGL Golfing Language), 4 bytes
-:Sc

Explanation:
- Decrement the stack counter so the current stack is where input is put
: Split the first element of the current stack (input) into an array of single strings, make that the next stack, and increment the stack counter
S Sort the current stack
c Compare the current stack and the one before, push that to the next stack and increment the stack counter
(implicit) Output the first element of the current stack, true if in order, false if not.

Is there proof that this language was created before this challenge?

@KritixiLithos yes, and it is technically a valid language, but I will make this non-competing because the functions necessary to complete this were made after this challenge. CGL is still a work in progress, and I am using challenges to show me what new functions should be added.

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