text:
Undress a string
We already now how to strip a string from its spaces.
However, as proper gentlemen/ladies, we should rather undress it.

Undressing a string is the same as stripping it, only more delicate. Instead of removing all leading and trailing spaces at once, we remove them one by one. We also alternate between leading and trailing, so as not to burn steps.
Example, starting with "     codegolf     " (five leading and trailing spaces):
     codegolf
    codegolf
    codegolf
   codegolf
   codegolf
  codegolf
  codegolf
 codegolf
 codegolf
codegolf
codegolf

First output the string unchanged. Then, output every step. Begin by removing a leading space (if applicable - see rule #2).
The input may have a different number of leading and trailing spaces. If you run out of spaces on one side, keep undressing the other until the string is bare.
The input may have no leading nor trailing spaces. If that's the case, output it as-is.
Use PPCG's default I/O methods. PPCG Default loopholes are forbidden.
Undefined behaviour on empty input, or input that only contains spaces, is OK.
You can assume that the string will only contain characters from the ASCII printable space (0x20 to 0x7E).

Examples - spaces are replaced by dots . for better readability:
4 leading spaces, 5 trailing: "....Yes, Sir!....."
....Yes, Sir!.....
...Yes, Sir!.....
...Yes, Sir!....
..Yes, Sir!....
..Yes, Sir!...
.Yes, Sir!...
.Yes, Sir!..
Yes, Sir!..
Yes, Sir!.
Yes, Sir!

6 leading, 3 trailing: "......Let's go golfing..."
......Let's go golfing...
.....Let's go golfing...
.....Let's go golfing..
....Let's go golfing..
....Let's go golfing.
...Let's go golfing.
...Let's go golfing
..Let's go golfing
.Let's go golfing
Let's go golfing

0 leading, 2 trailing: "Hello.."
Hello..
Hello.
Hello

0 leading, 0 trailing: "World"
World

21 leading, 5 trailing: ".....................a....."
.....................a.....
....................a.....
....................a....
...................a....
...................a...
..................a...
..................a..
.................a..
.................a.
................a.
................a
...............a
..............a
.............a
............a
...........a
..........a
.........a
........a
.......a
......a
.....a
....a
...a
..a
.a
a

A gentleman/lady is concise, so the shortest answer in bytes wins.

From Sandbox: https://codegolf.meta.stackexchange.com/a/13765/71426

Can we assume that there will be at least one non-space character?

@MartinEnder Yes

Can a test string contain new-lines or tabs? (Or more precisely, will the spaces have the lowest decimal value 32 in the strings?)

@KevinCruijssen You only have to handle ASCII characters in the printable space (0x20 to 0x7E). The other ones are Undefined Behavior.

@Nathan.EilishaShiraini Ok, so a test case like "  \ntest  " or "  \t test  " isn't possible (\n being a line-feed; \t being a tab)?

@KevinCruijssen Yes, there will be no test case like this. There will be no things like "  test\r " or " \v test" either.

@Nathan.EilishaShiraini LOL! Thank you for this idea :)

do we need to output as 1 line for each step or can we return a list of strings with all the steps?

Is this a valid test case ".....................a....."? If so I suggest to add it since some answers seems to fail this kind of test. (dots are for better readability of course)

@FelipeNardiBatista I thought list of string instead of multiline string was implicitely allowed as part of the standard I/O methods. Now: it is explicitely valid.

Added @Cinaski 's suggested test case. Thanks!

After testing the answers with Cinaski's test case, I found that some of them inconsistently add a trailing empty line. Since they are already there, and upvoted, I will allow this in order to leave these answers valid.

Somehow the terminology feels backwards to me. In my mind, undressing is something that happens relatively quickly, usually done by yourself, whereas stripping is often about making it take as long as possible to turn it into a proper show.

Retina, 26 bytes
{m`^ (.+)\z
$&¶$1
 $
 ¶$%`

Try it online! (Test suite uses periods for clarity. The footer and header convert them to and from spaces for the main code.)
Explanation
It would be nice if we could just alternate between dropping a leading and a trailing space and printing the intermediate result each time. The problem is that currently Retina can't print conditionally, so it would even print this intermediate result if there are no leading or no trailing spaces left, generating duplicates. (Retina 1.0 will get an option that only prints the result if the string was changed by the operation, but we're not there yet...)
So instead, we're building up a single string containing all intermediate results and printing that at the end.
{m`^ (.+)\z
$&¶$1

The { wraps both stages of the program in a loop which repeats until the string stops changing (which means there are no leading/trailing spaces left). The stage itself matches a leading space on the final line of the string, and that final line, and then writes back the match, as well as the stuff after the space on a new line (thereby dropping the leading space in the copy).
 $
 ¶$%`

Removing the trailing space is a bit easier. If we just match the final space, we can access the stuff in front of it (on the same line) with $%` which is a line-aware variant of the prefix substitution $`.

Python 2, 122 107 103 102 98 95 93 91 90 88 87 bytes
s=input()+' '
a=0
while-a*s!=id:
 if a:id=s
 a=~a
 if'!'>s[a]:s=s[1+a:len(s)+a];print s

Try it online!

Python 3, 97 95 93 90 bytes
s=input()
a=p=print
p(s)
while s!=a:
 a=s
 if'!'>s:s=s[1:];p(s)
 if'!'>s[-1]:s=s[:-1];p(s)

Try it online!

Using s=input() instead of a function would take less bytes.

Refering to 5. Undefined behaviour on empty input, or input that only contains spaces, is OK., 98 bytes.

Python 3 saves a byte.

@JonathanFrech I hadn't seen that; thanks :)

95 bytes.

You can further golf the Python 2 code by replacing a with the built-in function id to save having to define it at the start. -2 bytes.

91 bytes.

I came up with a cute exec-free 92B variation… I’m not sure if it can be golfed down more: https://tio.run/##LYxBCgIxEATveUXvKYoKrsdIfIIfkD0Ek7gDy0zYiYivjxGtS0PRVHnXWfjUmnri8qybrSkrcYWa10xLgg6eojOg6NUgy4oAYhz3h7FbULaDvegtTE59n93oAvrpKpym8z/VmsWXu8T0kCXjh/0A

in your python3, '!'>s[0] to '!'>s

@FelipeNardiBatista Thanks :)

@Lynn Thanks :)
I got it down to 88 bytes using your slicing

While it's not required, it's common practice (and courtesy ;)) to credit the users that have helped you golf an answer. That would also let me remove all of these comments.

05AB1E, 21 15 bytes
=v¬ðQi¦=}¤ðQi¨=

Try it online!
Explanation^
=                 # print input
 v                # for each character in input
  ¬ðQi  }         # if the first char in the current string is a space
      ¦=          # remove it and print without popping
         ¤ðQi     # if the last char in the current string is a space
             ¨=   # remove it and print without popping

Dang, I tried something similar but for some reason I was sure head/tail didn't work on strings, and I was about to raise an issue about it on github. Must have read the debug logs wrong. :-)

@scottinet: I just found a way to get around the end-check :)

oh... why didn't we think about that before? since we print conditionally there is no need to loop exactly the right number of times, we only need to loop over enough times. I'm borrowing that idea to improve my answer :-)

@scottinet: Yeah. It's obvious when you think about it, but sometimes it's easy to miss those things :P

TFW the clunky redundant answer gets the lead...

Perl 6, 55 bytes
Saved 3 bytes thanks to @nwellnhof.
{($_,{$++%2??S/" "$//!!S/^" "//}...*)[^.comb*2].unique}

Try it online!
Explanation: ($_,{$++%2??S/" "$//!!S/^" "//}...*) is a recursive infinite sequence that starts with the original string ($_) and the next element is given by the block called on the previous element.
The block itself gets the string in the $_ variable. The operator S/(regex)/(string)/ will search for the first occurence of (regex) in $_, replaces it with (string), and returns the result. If there is no match, it returns the content of $_ unchanged. We use the ternary operator ?? !! with the condition $++%2, which alternates between False and True ($ is a free variable that conserves its contents across calls to the block.)
In the worst case (all spaces on one side and 1 other character), we remove 1 space every 2 steps. So we can be sure that in 2*(length of the string) steps, all spaces will have been removed. We take that many elements from the recursive sequence with [^.comb*2] and finally discard duplicates (which occur whenever a space should have been removed but it isn't there) with .unique. This returns the list of strings, progressively stripped of spaces.

[^.comb*2] saves 2 bytes. For some reason this works, but [^2*.comb] doesn't. No idea why. Using a ternary ?? !! to select the regex saves another byte.

Thanks! I tried [^2*.comb] and it didn't work, so I just used [0..2*.comb]. And thanks for the ternary, I just thought it's too expensive and it didn't occur to me that I replaced it with something even more expensive...

C (gcc), 89 84 bytes
Recursive version is shorter ;-)
j;f(char*s){puts(s);*s^32||puts(++s);s[j=strlen(s)-1]<33?s[j]=0,f(s):*s^32||f(s+1);}

Try it online!
C (gcc), 107 102 101 100 99 bytes
Saved 2 bytes thanks to @Jonathan Frech using spaces and ~
i,j,k;f(char*s){for(i=~++k,puts(s);i^k;k=s[j=strlen(s)-1]<33?s[j]=0,puts(s):0)*s^32?i=0:puts(++s);}

Try it online!

I think the question really wants you to remove spaces rather than dots. There is even an advantage to using spaces; you can replace ==46 with <33 as the space is the smallest printable character and you only have to handle those.

What does the ++k+ do?

@JonathanFrech It pre-increments k and adds one, which is equivalent to k = k + 1; i = k + 1; or i = k + 2; k = k + 1.

Technically i=k+++2 works too which I would have used because the +++ looks weird :P

@HyperNeutrino Yeah, I know what the pre-increment operator does; though I do not get how the code works without it. So really I was asking what role it plays, rather than how it is defined.

@JonathanFrech That's really odd... I'd have to take a better look at that. Good observation though.

@JonathanFrech k is true if there are leading spaces and i is true if there are trailing spaces.  I needed them to have different values so I could use ^ in the loop condition.

Ah, I think I get it. If so, I would propose ++k+1 -> ~++k.

JavaScript (ES6) 92
@Upvoters: have a look at the other JS answer down below that is 76 bytes long
(s,q,l=2,p=0)=>{for(alert(s);l--;p=!p)s[+p&&s.length-p]<'!'&&alert(s=s.slice(!p,-p||q,l=2))}

A loop looking for a space at front or at end. If found, remove space and output string. If no space found 2 times, stop.

F=
(s,q,l=2,p=0)=>{for(alert(s);l--;p=!p)s[+p&&s.length-p]<'!'&&alert(s=s.slice(!p,-p||q,l=2))}

// some trick to show dots instead of spaces, for test
alert=x=>console.log(x
  .replace(/^ +/g,z=>'.'.repeat(z.length))
  .replace(/ +$/g,z=>'.'.repeat(z.length))
)

function go() {F(I.value.replace(/\./g,' '))}

go()
<input ID=I value='....yes Sir!....'> (use dot instead of space)
<button onclick='go()'>Go</button>

You could save a byte by checking for space with <'!'. To make your snippet still work you can replace periods with spaces before passing to your function.

@JustinMariner ok now, because OP stated no char expected less than ' '. Thanks

Perl 5, 32 bytes
Saved 4 bytes due to @Abigail.
1while s/^ /!say/e+s/ $/!say/e

Requires -pl counted as 2, invoked with -E.
Sample Usage
$ echo '   test   ' | perl -plE'1while s/^ /!say/e+s/ $/!say/e'
   test
  test
  test
 test
 test
test
test

Try it online!

Doesn't work correctly for strings without trailing spaces.

print;s/^ //&&print,s/ $//&&print while/^ | $/ works with -n flag, also -l is not needed

@nwellnhof fixed.

C# (.NET Core), 192 183 182 181 179 178 bytes
-3 bytes thanks to Kevin Cruijssen
n=>{var o=n+"\n";for(var e=1;n.Trim()!=n;){if(1>(e^=1))if(n[0]<33)n=n.Remove(0,1);else continue;else if(n.TrimEnd()!=n)n=n.Remove(n.Length-1);else continue;o+=n+"\n";};return o;}

Try it online!

Some things to golf: var e=1;while(n.Trim()!=n) -> for(var e=1;n.Trim()!=n;); if(n[0]==' ') -> if(n[0]<33)

I've thought about second one, but what if the test string contains newlines?

Ok, <33 is possible due to OP's newly added rule: "You can assume that the string will only contain characters from the ASCII printable space (0x20 to 0x7E)."

Java 8, 150 146 145 137 bytes
s->{String r=s;for(int f=0;s!=s.trim();f^=1)r+="\n"+(s=f+s.charAt(0)<33|!s.endsWith(" ")?s.substring(1):s.replaceAll(" $",""));return r;}

-4 bytes thanks to @Nevay changing (f<1&s.charAt(0)<33) to f+s.charAt(0)<33.
-1 byte by using the !s.trim().equals(s) trick from @someone's C# .NET answer instead of s.matches(" .*|.* ").
-8 bytes thanks to @Nevay again by changing !s.trim().equals(s) to s!=s.trim(), because String#trim will return "A copy of this string with leading and trailing white space removed, or this string if it has no leading or trailing white space", thus the reference stays the same and != can be used to check if they are the same reference, instead of .equals to check the same value.
Explanation:
Try it here (or try a more visual version here with # instead of spaces).
s->{                               // Method with String as both parameter and return-type
  String r=s;                      //  Result-String (starting at the input)
  for(int f=0;                     //  Flag-integer (starting at 0)
      s!=s.trim();                 //  Loop as long as `s` contains leading/trailing spaces
      f^=1)                        //    And XOR(1) `f` after every iteration (0->1; 1->0)
    r+="\n"                        //   Append the result with a new-line
       +(                          //    Followed by:
         s=f+                      //     If `f` is 0,
             s.charAt(0)<33        //     and `s` starts with a space
           |!s.endsWith(" ")?      //     Or doesn't end with a space
            s.substring(1)         //      Remove the first leading space
           :                       //     Else:
            s.replaceAll(" $",""));//      Remove the last trailing space
                                   //  End of loop (implicit / single-line body)
  return r;                        //  Return the result-String
}                                  // End of method

You can use s=f+s.charAt(0)<33 instead of (f<1&s.charAt(0)<33) (-4 bytes).

You can use s!=s.trim() instead of !s.trim().equals(s); (-8 bytes).

Jelly, 16 bytes
Ḋ=⁶Ḣ$¡UµÐĿ¹Ṛƭ€QY

Try it online!
-2 bytes thanks to Erik the Outgolfer
-1 byte thanks to miles
Explanation
Ḋ=⁶Ḣ$¡UµÐĿ¹Ṛƭ€QY  Main link
       µÐĿ        While the results are unique (collecting intermediate results), apply the last link (`µ` creates a new monadic link):
Ḋ=⁶Ḣ$¡            Remove a space from the beginning if there is one
 =⁶Ḣ$             If the first character is a space, then 1, else 0
 =                Compare each character to
  ⁶               ' '
   Ḣ              Get the first comparison
Ḋ                 Then Dequeue the string (s -> s[1:])
    ¡             That many times
     U            And reverse the string (the next time this is called, it will remove spaces from the end instead)
             €    For each string
            ƭ     Alternate between two commands:
          ¹       Identity (do nothing), and
           Ṛ      Reverse
          ¹Ṛƭ€    Correct all strings that are reversed to remove the trailing space
              Q   Remove duplicates (where there was no space to remove)
               Y  Join on newlines

ḣ1Ḣ=⁶ -> =⁶Ḣ

@EriktheOutgolfer Thanks, edit coming.

Cool idea with the alternating commands of reverse/identity!

@Emigna Thanks! :D I mostly just wanted an excuse to use the new quick... heh :P

ƭ only needs a nilad if the chain is longer than two. ¹Ṛƭ works fine here.

@miles Oh cool! Thanks! :D

C, 91 90 bytes
i,l;f(char*s){for(i=puts(s);i;i=(s[l=strlen(s)-1]*=s[l]>32)?i:puts(s))i=*s<33&&puts(++s);}

Try it online!

Java (OpenJDK 8), 161 147 146 bytes
x->{for(int l=0,r=x.length(),k=-1,u,v;((u=32-x.charAt(l)>>k)*(v=32-x.charAt(r-1)>>-1))<1;x+="\n"+x.substring(l-=k&~u|v,r+=(k=~k)&~v|u));return x;}

Try it online!
-1 byte thanks to @Kevin Cruijssen!
x -> {
    /*
     * l: left index (inclusive)
     * r: right index (exclusive)
     * k: side to remove from, -1:=left, 0:=right
     * u: left character   0:=space, <0:=no space (-1 if k is left side)
     * v: right character  0:=space, -1:=no space
     */
    for (int l = 0, r = x.length(), k = -1, u, v;
            ((u = 32 - x.charAt(l) >> k)
           * (v = 32 - x.charAt(r - 1) >> -1)) < 1; // loop while left or right has space(s)
            x += "\n" + x.substring(                // append newline and substring
                    l -= k & ~u | v,                // inc. left  if k is left side
                                                    //               and left has space
                                                    //            or right has no space
                    r += (k = ~k) & ~v | u));       // dec. right if k is right side
                                                    //               and right has space
                                                    //            or left has no space
    return x;
}

Hehe, I saw your deleted answer and was wondering when you were below my 150 bytes and would undelete it. ;)

I'm not entirely sure, but I think you can golf a byte by changing (u=32-x.charAt(l)>>-1) to (u=32-x.charAt(l)>>k)

@KevinCruijssen Won't work, k is 0 every second iteration.

Yes, but the weird part is that the TIO works and gives the correct result for all test cases with this change for u. It doesn't when I also change -1 to k for v. I'm confused why it works though, since k will indeed become 0 after k=~k.. :S

@KevinCruijssen For the k=0 scenario: If left has spaces left, then u has the same value as before (0); if left has no spaces left, then (k=~k)&~v|u evaluates to -1|u (~0&-1|u), thus the undefined (negative) value of u does not matter (-1|x==-1).

05AB1E, 25 17 bytes
-8 bytes by borrowing the no-need-for-an-end-check idea from Emigna
,v2F¬ðQi¦DNiR},}R

Try it online!
I'm pretty sure a less straightforward approach can beat that solution easily. For now...
Explanations:
,v2F¬ðQi¦DNiR},}R           Full Programm
,                           Print the input string
 v                          For each char of the string
                               (we don't really care, we only need to loop
                                enough times to accomplish our task, since
                                we print conditionally we can loop more
                                times than necessary)
  2F...........}            Two times...
    ¬õQi                       Is 1st item a space?
        ¦D                        Remove 1st item + duplicate
          NiR}                    If on the second pass: reverse the list
              ,                   Pop & print with newline
               }               End If
                 R          Reverse the list

I like your approach with the loop :) I've been trying to figure out a way to do everything in one pass without multiple ifs, but I haven't figured it out yet. Also, your explanation seem to have an empty string instead of a space.

Thanks! I fixed the explanation, I forgot to edit the "is empty" part when I golfed my code, using S instead of # (-1 byte). The loop... well... it saves a whopping 1 byte compared to a straightforward approach. I'm currently looking for a shorter way to detect the end of the task (5 bytes for this is a lot), and I'm also considering a different approach altogether. I do think there is a more clever way to solve this challenge.

If you try and do everything in one pass (as I'm currently looking into), the best check I have for exiting the loop is 8 bytes...

Ruby, 63 bytes
->s{*x=s;(s=~/^ /&&x<<s=$';s=~/ $/&&x<<s=$`)while s=~/^ | $/;x}

Try it online!

R, 145 133 111 bytes
-12 bytes thanks to @Giuseppe, by storing the result of sub in a new variable and testing for whether it has changed
-22 bytes by returning a vector of strings rather than a string with newlines
function(s){L=s
while(grepl("^ | $",s)){if((x=sub("^ ","",s))!=s)L=c(L,x)
if((s=sub(" $","",x))!=x)L=c(L,s)}
L}

Try it online!
Explanation on a partially ungolfed version:
function(s){
  L=s                          # Initialise a vector with the original string
  while(grepl("^ | $",s)){     # While there are leading or trailing spaces...
    if((x=sub("^ ","",s))!=s){ # Check whether we can remove a leading space
      L=c(L,x)                 # If so, add the shortened string to the vector
    }
    if((s=sub(" $","",x))!=x){ # Check whether we can remove a trailing space
      L=c(L,x)                 # If so, add the shortened string to the vector
    }
  }
  L                            # Return the vector
}

can't you use C(s<-sub(),\n) instead of a separate print statement? Ah, no, because of sep=" "

@Giuseppe Yes, I think it works out slightly longer to include it all in a single statement because of the need to add sep="". In most challenges the extra trailing space would not matter, but here unfortunately it does!

133 bytes -- something about your using sub just suggested this, IDK why

@Giuseppe Very elegant!

Could you just set L=s and return a vector of strings?

@Giuseppe I guess so!

Husk, 23 22 bytes
u§↑L`G`I¢e₁ȯ↔₁↔
?tI<"!

Thanks to Leo for -1 byte.
Try it online!
Explanation
The function `G`I should really be a built-in...
?tI<"!  Helper function: remove initial space.
?  <"!  If less than the string "!",
 t      remove first character,
  I     else return as is.
u§↑L`G`I¢e₁ȯ↔₁↔  Main function.
         e       List containing
          ₁      the helper function
           ȯ↔₁↔  and the composition reverse-helper-reverse.
        ¢        Repeat it cyclically.
    `G`I         Cumulative reduce from left by function application
                 using input string as initial value.
 §↑L             Take first length(input) values.
u                Remove duplicates.

Nice! Indeed we would need more builtins for applying functions cyclically... btw I've found a sligthly shorter way to remove the first space: https://tio.run/##yygtzv7/v/TQ8kdtE30S3BM8Dy1KfdTUeGL9o7YpQBpIctmXeNooKf7//19JAQgiU4t1FIIzixRBHAUlAA

@Leo Thanks! Using ? seems obvious in hindsight...

C++, 196 193 189 186 183 bytes
-10 bytes thanks to Jonathan Frech
-3 bytes thanks to Zacharý
#include<iostream>
#include<string>
#define D std::cout<<s<<'\n'
#define R ~-s.size()
auto u=[](auto s){D;while(s[0]<33||s[R]<33){if(s[0]<33)s.erase(0,1),D;if(s[R]<33)s.erase(R),D;}};

Compilation with MSVC requires the un-activation of SDL checks

You may be able to replace ==32 with <33.

I am no C++ master, though is #include<string> really necessary?

if(...){...;D;} -> if(...)...,D;.

@JonathanFrech What you did there was compiler specific, not guarranted by the standard. VC++ can't find a definition of the << operators without the explicit inclusion of string.

#define R ...<33, ||R){ and if(R){ -> #define R ...<33), ||R{ and if(R{.

184 bytes.

void -> int.

@JonathanFrech 1.) C++11 requires whitespace after the macro name. ( and i compile with C++17 norm ) 2.) Sticking 2 includes each other on the same lines cause the second token to be ignored. 3.) Declaring a return value in a function that doesn't return a value is undefined behavior

Would using C++14 and auto instead of std::string, and have u be called like u(std::string("  SOMETHING ")) work?

@Zacharý No, since it's not a lambda. But i can replace it by a lambda and save a few bytes

Java (OpenJDK 8), 137 125 121 120 124 bytes
s->{int i=1;do System.out.println(s);while(s!=(s=s.substring(s.charAt(0)<33?i:(i=0),s.length()-(s.endsWith(" ")?i^=1:0))));}

Try it online!

Nice answer! Just as short as my answer of 137 bytes, but you can still golf 12 bytes like this: s->{for(int i=0;s!=s.trim();)System.out.println(s=s.substring(s.charAt(0)<33?1-i%2:0,s.length()-(s.endsWith(" ")?i++%2:0)));}

This currently does not "... output the string unchanged" and fails for input with leading spaces and no trailing spaces.

Maybe you can use s->{int i=1;do System.out.println(s);while(s!=(s=s.substring(s.charAt(0)<33?i:(i=0),s.length()-(s.endsWith(" ")?i^=1:0))));} (124 bytes) (seems to be correct but didn't test much).

MATL, 21 16 bytes
tnE:"t@o&)w46-?x

This uses dots instead of spaces for greater clarity. For spaces replace 46 by 32.
Try it online!
Explanation
tn      % Input (implicit). Duplicate and push length, say L
E       % Multiply by 2
:       % Push range [1 2 ... 2*L]
"       % For each k in that array
  t     %   Duplicate the string at the top of the stack
  @     %   Push k
  o     %   Parity: gives 1 or 0
  &)    %   Two-ouput indexing. Pushes the k-th entry of the string and then
        %   the rest of the string. The 1-st output is the first, the 0-th
        %   is the last (indexing is 1-based dand modular)
  w     %   Swap
  46-   %   Subtract 46, which ias ACII for '.'
  ?     %   If non-zero
    x   %     Delete sub-string that was obained by removing that entry
        %   End (implicit)
        % End (implicit)
        % Display stack (implicit)

x86 machine code for Linux, 60 bytes
e8 1f 00 00 00 31 c0 80 3f 20 75 09 47 4d 74 10
e8 0f 00 00 00 80 7c 2f ff 20 74 05 84 c0 75 e5
c3 4d eb dc 6a 04 58 50 31 db 43 89 f9 89 ea cd
80 58 6a 0a 89 e1 89 da cd 80 58 c3

This is a function for Linux x86. It takes as input pointer to the string in edi and string length in ebp.
Ungolfed, with some infrastructure to test (compile with FASM, run with the string as program argument; look for undress: label for actual function code):
format ELF executable
segment executable
SYS_WRITE = 4
    jmp     callUndress
; -------------------- the function itself --------------------------------
; Input:
;   edi=string
;   ebp=length
undress:
undressLoopPrint:
    call    print
undressLoop:
    xor     eax, eax    ; flag of having printed anything on this iteration
    cmp     byte [edi], ' '
    jne     startsWithoutSpace
    inc     edi
    dec     ebp
    jz      quit
    call    print
startsWithoutSpace:
    cmp     byte [edi+ebp-1], ' '
    je      endsWithSpace
    test    al, al      ; if print has been called, then we have 0x0a in eax
    jnz     undressLoop
quit:
    ret
endsWithSpace:
    dec     ebp
    jmp     undressLoopPrint
print:
    push    SYS_WRITE
    pop     eax
    push    eax
    xor     ebx, ebx
    inc     ebx ; STDOUT
    mov     ecx, edi
    mov     edx, ebp
    int     0x80
    pop     eax
    push    0x0a    ; will print newline
    mov     ecx, esp
    mov     edx, ebx ; STDOUT=1, which coincides with the length of newline
    int     0x80
    pop     eax
    ret
; --------------------- end undress ---------------------------------------
SYS_EXIT = 1
STDERR = 2
callUndress:
    pop     eax     ; argc
    cmp     eax, 2
    jne     badArgc
    pop     eax     ; argv[0]
    pop     edi
    mov     al, 0
    cld
    mov     ecx, -1
    repne   scasb
    lea     edi, [edi+ecx+1] ; argv[1]
    neg     ecx
    sub     ecx, 2
    mov     ebp, ecx     ; strlen(argv[1])
    call    undress
    xor     ebx, ebx
exit:
    mov     eax, SYS_EXIT
    int     0x80
    ud2
badArgc:
    mov     esi, eax
    mov     eax, SYS_WRITE
    mov     ebx, STDERR
    mov     ecx, badArgcMsg
    mov     edx, badArgcMsgLen
    int     0x80
    mov     ebx, esi
    neg     ebx
    jmp     exit
badArgcMsg:
    db      "Usage: undress YourString",0x0a,0
badArgcMsgLen = $-badArgcMsg
segment readable writable
string:
    db      100 dup(0)
    stringLen = $-string

sys_write() makes eax non-zero  (specifically 1, the number of characters written, assuming it's not -errno),  So will print if you don't pop eax at the end.  You could just xor eax,eax before the cmp byte [edi], ' ' and save the mov al,1, and maybe some eax save/restore.  Although you don't actually save it until after clobbering with SYS_WRITE.  Hmm, instead of 0, you could use SYS_WRITE vs. 1, since cmp al, imm8 is the same size as test al,al.

Can you put a '\n' into the array with mov byte [ecx + edx], '\n' instead of doing the 2nd write()?  (And decrement the length after printing?)  Might save you a few instructions.

Actually, print() currently leaves '\n' in eax, which is different from SYS_WRITE, so you could still check that.  I thought you were saving/restoring eax, but that was just saving bytes copying a constant around.  For long strings, sys_write() can leave the high bytes of eax non-zero, so that unfortunately rules out just using mov al, SYS_WRITE.

@PeterCordes actually yes, mov al, 1 was extraneous. -2 bytes now, thanks.

A register calling convention would save you the load instructions.  In code-golf, a custom calling convention is normally fair game for asm.  OTOH, if you'd rather golf the standard stack-args calling convention, that's interesting too.

@PeterCordes I supposed one has to use a standard convention. Will take this into account for the future.

You're writing in asm, presumably for a caller written in asm.  In asm, every function can have its own calling convention if you want.  I try not to bend the rules too far, so I still always return in eax (or dx:ax for 16-bit addler32).  Using a calling convention similar to an existing one (like MS _fastcall but with different regs), or with some dummy args to get the args in the regs you want, seems fine.  Treating more regs as call-clobbered is probably also ok.  Saving/restoring regs is kind of boilerplate and not the interesting part of a machine-code answer.

@PeterCordes agreed. Here goes the 10 bytes smaller version with custom calling convention.

If you used esi as your 2nd arg, you'd have a 32-bit version of the x86-64 System V calling convention.  Not that it really matters.

C# (.NET Core), 176 170 bytes
using System;s=>{Action o=()=>Console.WriteLine(s);o();Func<int>l=()=>s.Length-1;while(s!=s.Trim()){if(s[0]<33){s=s.Remove(0,1);o();}if(s[l()]<33){s=s.Remove(l());o();}}}

Try it online!
This is an alternative to @someone's answer, and just outputs the strings directly.

Your program doesn't output the string unmodified before removing spaces.

@Nathan.EilishaShiraini I corrected that mistake and golfed a few bytes to reduce the byte count anyway.

JavaScript (ES6), 76 bytes
f=(s,r,n,l=s.length)=>s[r?--l:0]<"!"?s+`
`+f(s.slice(!r,l),!r):n?s:f(s,!r,1)

Outputs as a multiline string.
Test Cases
Using dots instead of spaces, as most answers are doing.

f=(s,r,n,l=s.length)=>s[r?--l:0]<"!"?s+`
`+f(s.slice(!r,l),!r):n?s:f(s,!r,1)

// converting to and from dots and spaces
let dots=s=>s.replace(/^\.+|\.+$/gm,x=>" ".repeat(x.length));
let spaces=s=>s.replace(/^ +| +$/gm,x=>".".repeat(x.length));

["....Yes, Sir!.....", "......Let's go golfing...", "Hello..", "World", ".....................a....."]
.forEach(test=>O.innerHTML+=spaces( f(dots(test)) ) + "\n\n");
<pre id=O></pre>

Sed, 24 bytes
p;:s s/ //p;s/ $//p;ts;D

Try It Online !

Octave, 88 83 bytes
5 bytes off thanks to Stewie Griffin!
x=[input('') 0];for p=mod(1:sum(x),2)if x(~p+end*p)<33,disp(x=x(2-p:end-p)),end,end

Try it online!

Very nice. "Anyway, see if you can remove a couple of bytes" :-P

@StewieGriffin I meant in your answer... :-D Good idea, thanks!

I might delete mine... It's so uninspired compared to this...

@StewieGriffin Here's an idea to remove two bytes. Pity that min is needed because of s being dynamically shrunk

PHP, 117 bytes
I add an extra space at the start so it will take the space out and show the original without any extra code.
Kinda new to this... would the <?php and the space at the start of the PHP file add 6 extra bytes or do I get that for free?
$s=" $argn";while($r!=$s){$r=$s;if($s[0]==" ")echo($s=substr($s,1))."
";if($s[-1]==" ")echo($s=substr($s,0,-1))."
";}

Try it online!

Using your method 6 bytes can be reduced: Try it online!

You can omit the PHP's opening tag since you can run it with a command like this: php -r "echo 1;" But if you want to use something like <?=1; you have to include the tag in bytes count.

Haskell, 109 bytes
(b%e)
t=last
b(' ':s)=s
b l=l
e l|t l>' '=l|1>0=init l
(g%h)l=l:t((h%g$g l):[t$(h%g$h l):[[]|h l==l]|g l==l])

Try it online!
b removes leading space if there is a leading space
e removes trailing space if there is a trailing space
% switches between b and e

Haskell, 86 bytes
(f#g)
r=reverse
f(' ':s)=s
f s=g s
g=r.f.r
(a#b)s=s:[x|last s<'!'||s<"!",x<-(b#a)$a s]

Try it online! Usage: (f#g) "    test     " yields a list of strings.
Explanation

Function f removes a leading space from a given string. If there is no leading space, it calls function g.
Function g reverses the string, calls f and reverses back. This removes a trailing space if there is one, and an leading space otherwise.
If a string has neither leading nor trailing spaces, then f and g diverge, so this needs to be checked before.
The main function # is initialized with f as first and g as second argument. The third argument s is the input string, which is appended to the recursively computed list of results:

If s has no leading or trailing spaces, then last s<'!'||s<"!" is false and the list of results empty.
Otherwise the function given as first argument is applied to s and # is applied recursively with f and g exchanged.

Octave, 89 bytes
s=input('');while any(s([1,end])<33)if s(1)<33,s(1)=[],end,if s(end)<33,s(end)=[],end,end

Try it online!
I'll add an explanation later, when I have the time. I might be able to golf off some bytes if I change the approach completely, but I can't see how unfortunately.
The last letters here spell out: "sendsendendend". I wish there was a way to store end as a variable and use that, but guess what ...

Is it valid to output with s = ...? (The usual question, I know)

Anyway, see if you can remove a couple of bytes :-P

Python 2, 79 bytes
-1 byte thanks to @JonathanFrech
f=lambda s,i=1:[s]+(s>i*'!'and'!'>s[-1]and f(s[:-1])or'!'>s and f(s[1:],0)or[])

Try it online!
The test suit replaces "." with " " before calling the function and replaces " " back to "." before printing the results for clarity.

'!'*i and -> i*'!'and.

Pyth, 28 bytes
QW<lrKQ6lQ=hZ?&%Z2qdhQ=tQ=PQ

Try it here! or Verify all test cases!
Explanation
QW<lrKQ6lQ=hZ?&%Z2qdhQ=tQ=PQ   ~ Full program. Q is autoinitialized to input.

Q                              ~ Output the input.
 W<lrKQ6lQ                     ~ Loop while the condition is met.
  <                            ~ Is smaller?
   lrKQ6                       ~ The length of the original input, stripped on both sides.
        lQ                     ~ The length of the current Q.
          =hZ                  ~ Increment a variable Z, initially 0
             ?&%Z2qdhQ         ~ If Z % 2 == 1 and Q[0] == " ", then:
                      =tQ      ~ Make Q equal to Q[1:] and output, else:
                         =PQ   ~ Make Q equal to Q[:-1] and output.

Bash, 98 94 bytes
Saved 4 bytes using subshell instead of sequences (poor performances)
r()(s=$1;[[ $s = $b ]]||([[ $s = $a ]]||echo "$s"
b=$a a=$s;((i=!i))&&r "${s# }"||r "${s% }"))

First answer
r(){ s=$1;[[ $s = $b ]]||{ [[ $s = $a ]]||echo "$s"
b=$a a=$s;((i=!i))&&r "${s# }"||r "${s% }";};}

Note the ! must be escaped in interactive mode

C# - yet again, 125 bytes
while(s.Trim()!=s){if(s[0]==' '){yield return s=s.Substring(1);}if(s.Last()==' '){yield return s=s.Substring(0,s.Length-1);}}

Cheers!
Try it online!

Welcome to PPCG!

D, 142 140 bytes
import std.stdio;void u(T)(s){s.writeln;while(s[0]<33||s[$-1]<33){if(s[0]<33){s=s[1..$];s.writeln;}if(s[$-1]<33){s=s[0..$-1];s.writeln;}}}

Try it online!
This is a port of HatsuPointerKun's C++ answer.

Julia, 138 bytes
a(s)=' ' in s?s[1]==' '?(println(s);z(s[2:end])):z(s[1:end]):print(s)
z(s)=' ' in s?s[end]==' '?(println(s);a(s[1:end-1])):a(s[1:end]):print(s)

Not sure if there is a way to substitute another character for end, but if there was that would probably save some bytes.

Welcome to the site!

Kotlin, 151 150 bytes
{var v=it
var c={println(v)}
while(0<((if(v[0]<'!'){c()
v=v.substring(1)
1}else 0)+if(v.endsWith(' ')){c()
v=v.slice(0..v.length-2)
1}else 0
)){}
c()}

Beautified
{
    var v = it
    var c={println(v)}
    while ( 0 <(
            (if (v[0] < '!') {
                c()
                v = v.substring(1)
                1
            } else 0)
                    +
                    if (v.endsWith(' ')) {
                        c()
                        v = v.slice(0..v.length-2)
                        1
                    } else 0
            )){}
    c()
}

Test
/** Shows spaces, just helps viewing answer. */
fun println(i: String) {
    for (c in i) {
        if (c == ' ') {
            print('~')
        } else {
            print(c)
        }
    }
    print('\n')
}
var u: (String) -> Unit =
{var v=it
var c={println(v)}
while(0<((if(v[0]<'!'){c()
v=v.substring(1)
1}else 0)+if(v.endsWith(' ')){c()
v=v.slice(0..v.length-2)
1}else 0
)){}
c()}

fun main(args: Array<String>) {
    u("      Let's go golfing   ")
}

Edits
-1 -> x == ' ' => x < '!' Jonathan French

150 bytes.

Jq 1.5, 149 116 bytes
def G(p):if p==[]then. else sub(p[0];"")as$n|if.!=$n then.,($n|G(p|reverse))else($n|G(p[1:]))end end;G(["^ "," $"])

Expanded
def G(p):
  if p==[] then .                  # stop when no patterns remain
  else
     sub(p[0];"") as $n            # use first pattern
   | if .!=$n                      # if we removed something
     then ., ($n|G(p|reverse))     #   return result and switch patterns
     else ($n|G(p[1:]))            # otherwise remove failed pattern
     end
  end
;
G(["^ "," $"])

Sample Run
$ jq -MRr 'def G(p):if p==[]then. else sub(p[0];"")as$n|if.!=$n then.,($n|G(p|reverse))else($n|G(p[1:]))end end;G(["^ "," $"])' <<<'     codegolf     '
     codegolf
    codegolf
    codegolf
   codegolf
   codegolf
  codegolf
  codegolf
 codegolf
 codegolf
codegolf
codegolf

$ wc -c <<<'def G(p):if p==[]then. else sub(p[0];"")as$n|if.!=$n then.,($n|G(p|reverse))else($n|G(p[1:]))end end;G(["^ "," $"])'
 116

This is not a successful contender, because it works only for len(left whitespace) between [len(right whitespace), len(right whitespace)+1]. Anyway, just for the fun of it:
Python 3, 56 bytes:
def f(a,e=0):print(a);a[e]<'!'and f(a[e+1:e or None],~e)

GolfScript - 46 bytes
'
'+{.(32={.1}{;.0}if\);)32={'
'+\1}{;0}if|}do

Explanation
'\n'+    Adds endline to the argument
{.       Starts do loop and duplicates the top of the stack
(32=     Is the first character a ' '?
{.1}     It is, duplicate result and push 1
{;.0}if  It isn't, remove cut string, duplicate and push 0
\        The number (0 or 1) we pushed before sinks one position
);)      Obtains the last character of the string
32=      Is it a space?
{'\n'+\1} Add a new line, make the number we pushed before rise
          one position, and push another 1
{;0}if   Same as before
|        'Or' between the two numbers we pushed before
}do      If at least one of them was 1, repeat!

Test
It works with dots by replacing 32 with 46.
Input: ...test..

Output:

...test..
..test..
..test.
.test.
.test
test

Japt -R, 18 bytes
ÈrYg"^  $"ò}hUÊN â

Try it

Stax, 16 bytes
ùG⌐♦ò⌡╩d♪º"╪8·`;

Run and debug it
Procedure:

Alternate replacing regexes "^ " and " $" with "".  Do this n times where n is the length of the input.
Remove duplicate values.

Perl 5 -n, 33 bytes
(s/^ //&&say)|(s/ $//&&say)&&redo

Try it online!


text:
Little Boxes on the Hillside
There's a satirical song called Little Boxes, originally by Malvina Reynolds, about suburban sprawl that has lyrics as follows:

Little boxes on the hillside,
  Little boxes made of ticky-tacky,
  Little boxes on the hillside,
  Little boxes all the same.
  There's a green one and a pink one
  And a blue one and a yellow one,
  And they're all made out of ticky-tacky
  And they all look just the same.

Your job here is, given an integer input n>1 that represents the size of the house, output the four "little boxes" using the following colors (in 0xRRGGBB notation):
Green -- 0x00FF00
Pink --- 0xFF00FF (technically magenta)
Blue --- 0x0000FF
Yellow - 0xFFFF00

If your particular console doesn't have these exact colors, you may use the closest available (e.g., ANSI escape codes).
The houses are constructed with n _ representing the floor and roofline. They are surrounded by n/2 (round-up) | characters representing the walls. The roofs are always 2 high and are two / on the left edge, two \ on the right edge, and n-2 - representing the roof peak. As the houses get larger, the comparative size of the roof gets smaller; this is intended.
Here's a house of size 2:
 /\
/__\
|__|

Here's size 3:
 /-\
/___\
|   |
|___|

Here's size 7:
 /-----\
/_______\
|       |
|       |
|       |
|_______|

Thus given an input of 7, output four houses of size 7 as described above, with the first one in green, the second in pink (magenta), the third in blue, and the fourth in yellow. Output of the colors in that order is important.
Example picture of size 3:

Rules

The houses can be horizontal or vertical so long as there is a clear separation between them.
Leading/trailing newlines or other whitespace are optional, provided that the houses line up appropriately.
Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
Output can be to the console, saved as an image, etc.
Standard loopholes are forbidden.
This is code-golf so all usual golfing rules apply, and the shortest code (in bytes) wins.

Python 2, 123 121 119 111 109 108 bytes

Saved two bytes thanks to caird coinheringaahing; using the actual unprintable ASCII character instead of escaping it (\33)
Could (and did) save a byte by writing an entire program using input() instead of defining a function
Saved seven bytes thanks to ElPedro; using the fact that str(90+n) with 0<=n<=9 is "9%s"%n
Saved two three bytes by using string formatting rather than string concatenation

N=input()
for(n)in"2543":Z="_"*N;print"[9%sm /"%n+~-~-N*"-"+"\ \n/%s\\\n"%Z+~-N/2*("|%s|\n"%" "*N)+"|%s|"%Z

Try it online!
Uses ANSI escape codes for coloring the houses.

119 bytes

112 by looping "2543" and using string formatting - Try it online!

@ElPedro Thanks. Did not occur to me that 90 and 2,5,4,3 summed up is effectively concatenation.

JavaScript (ES6), Chrome / Firefox, 156 148 151 150 bytes
Saved 8 bytes thanks to @Shaggy
Saved 1 byte thanks to @Neil
n=>['0f0','f0f','00f','ff0'].map(c=>console.log(`%c /${'-'[r='repeat'](n-2)}\\
/${s='_'[r](n)}\\
${(`|${' '[r](n)}|
`)[r](~-n/2)}|${s}|`,'color:#'+c))

Demo
Make sure to open the console of your browser to get the colored output.

let f =

n=>['0f0','f0f','00f','ff0'].map(c=>console.log(`%c /${'-'[r='repeat'](n-2)}\\
/${s='_'[r](n)}\\
${(`|${' '[r](n)}|
`)[r](~-n/2)}|${s}|`,'color:#'+c))

f(3)

Works fine for me as a Snippet, with my browser's console open. Save 8 bytes by using the 3 digit hex codes: https://tio.run/##NYvRCsIgGEbv9xSDFr/SXNJl4F5kGymmUZgOHd1se3b7E7o5fJzD91IflXR8zgvz4W5y9qIfgFsOLVhukbzQopm6t5qJFr0OPgVnOhceRB51fW5WYDBEAdHMRi0wEc8udB/HClMScMOIrphmJXLDQ/13WyVpmb8LlrRvsgUdXIjXA5w0pTl/AQ

@Shaggy Thanks for the suggestions!

Are the leading 0s necessary?

@JonathanFrech Yes. Without the leading zeros, that would not be valid #RGB CSS color codes.

I think the height is wrong on the wider houses.

@Neil I should have read the spec more carefully. Fixed.

~-n/2 instead of n/2-.5?

Excel VBA, 243 Bytes
Anonymous VBE immediate window function that takes input from A1 and outputs to the range A2:A5
[C1]=vbLf:For i=1To 4:Cells(i+1,1)=[" /"&Rept("-",A1-2)&"\"&C1&"/"&Rept("_",A1)&"\"&C1&Rept("|"&Rept(" ",A1)&"|"&C1,A1/2)&"|"&Rept("_",A1)&"|"]:Cells(i+1,1).Font.Color=Array(32768,&HFF00FF,rgbBlue,65535)(i-1):Next:Cells.Font.Name="Courier New"

Output

Japt, 79 76 74 73 72 bytes
3#²¤r1'f ò3 w £Ol"%c /{ç- ¤}\\
/{ç'_}\\
{/2-½ ç"|{ç}|
"}|{ç'_}|"Xi`¬l:#

Try it (Open your browser's console before hitting "Run").
Thanks to ETH for helping me to test this last night while I was working it up on my phone.

Explanation
Implicit input of integer U
3#²¤r1'f ò3 w

First we build an array of 3-digit hex colours to map over. The charcode of ² is 178 so 3#² gives us 3178. We convert that to a base-2 string with ¤ and then replace all occurrences of 1 with f. ò3 splits the string into an array of strings of length 3 and w reverses that array.(I need to figure out a way to shorten that, somehow.)
£Ol

We map over the array using £ - with X being the current element - and Ol logs to console. We'll be passing 2 strings to that, one containing the house and one containing the CSS.
Xi`¬l:#

The second string is constructed using i to prepend X with the compressed string color:#.
"%c /{ç- ¤}\\

The %c tells the console to use the second string as CSS. The top line of the house is built by repeating (ç) the - character U times and then slicing that from the second element (0-indexed) with ¤. The braces act as a shortcut, of sorts, for string concatenation.
/{ç'_}\\

The second line is built in a similar way, this time repeating the _ character U times.
{/2-½ çRi|²iUç 1}

The body of the house is built by first repeating the | character twice with ² and then inserting a space repeated U times into that string at index 1. The resulting string is then prepended to a newline (R) and that string is repeated U/2-0.5 times.
|{ç'_}|"

Finally, the last line is built in the same way as the second.

Coolest Japt answer.

You only say that 'cause Japt shouldn't be able to do this, @Razetime! :D

Well, that's the point, isn't it?

Python 2, 120 bytes
n=input()
for i in'2543':s='_'*n;print'[1;3'+i+('m /'+'-'*(n-2)+'\ \n/%s\\\n'%s+(-~n/2-1)*('|'+' '*n+'|\n')+'|%s|\n'%s)

Try it online! (shows escape chars instead of actual colors, tested on local terminal)

I think your houses are too high for inputs like n=2.

@JonathanFrech yep I'll fix...wrong ceiling approach apparently EDIT: fixed

The question says to use the closest available, though you seem to use the normal colors instead of the bright colors. The bright colors -- I think -- would, however, be closer to the desired colors.

@JonathanFrech Hmm, yours seems to be using the normal colors too, but yeah the bright ones are closer.

Looks like you already used the idea that I suggested to @JonathanFrech. Sorry, I didn't steal your idea. I had not seen your answer. +1 for thinking like me.

@ElPedro Anyways his has turned out better than mine :p

Yabasic, 220 bytes
An anonymous function that takes input as an integer, n and outputs 4 colored homes to the terminal.
The lack of a dedicated string repeating or replacement function in yabsic really hurts this response.
Clear Screen
Input""n
b$="__"
c$="|  "
For i=1To n-2
a$=a$+"-"
b$=b$+"_"
c$=c$+" "
Next
c$=c$+"|\n"
For i=1To n-4
d$=d$+c$
Next
For i=0To 3
?Color(Mid$("gremagbluyel",1+3*i,3))" /"+a$+"\\\n/"+b$+"\\\n"+d$+"|"+b$+"|"
Next

This version requires graphics mode and thus does not work on TIO.
Output
The input value for the below is n=7.

SmileBASIC, 115 bytes
INPUT N
H.H 6H 4H 2DEF H C
COLOR C+5?" /";"-"*(N-2);"\
?"/";"_"*N;"\
FOR I=3TO N?"|";" "*N;"|
NEXT?"|";"_"*N;"|
END

Another one which is also 115 bytes:
INPUT N
FOR J=0TO 3COLOR!!J*8-J*2+5?" /";"-"*(N-2);"\
?"/";"_"*N;"\
FOR I=3TO N?"|";" "*N;"|
NEXT?"|";"_"*N;"|
END

The colors codes I need (in 4-bit RGBI) are 5, 11, 9, 7. This is generated using !!J*8-J*2+5 If J is not 0, this is 13-J*2 (giving 11,9,7), and if it is, the result is just 5.

source: Stack Exchange

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

sort: votes


text:
How do I ask a teller for money at the bank?
I need to go to the bank and withdraw some money.  I need to withdraw $30, $22 to pay my roommate for the internet and $8 for laundry.  Since neither of these can make change, I need my $30 to be split into two partitions of the two sizes.  That means when the teller asks me how I want my $30 I am going to have to make a request.  I could tell them I want it in a twenty, a fiver, and five ones.  But I want to make my request as simple as possible as to avoid having to repeat myself.  To make my request simpler I could ask that my cash contain a twenty and at least 2 ones because the 8 is implied by the total, but better yet I could simply request that one of the bills I receive be a one dollar bill (If you are not convinced of this just try to make 29 dollars without making 8).
So that's all fine and dandy but I need to do this calculation every time I go to the bank so I thought I would write a program to do this (have you write a program to do this for me).
Your program or function should take a list of integers representing all the payments I need to make and a set of integers representing the denominations of bills available at the bank, and you must output the smallest list of denominations such that every way to make the total that includes that list of denominations can be cleanly divided into the list of payments.
Extra rules

You may assume that the denomination list will always contain a 1 or you may add it to each list yourself.
Some inputs will have multiple minimal solutions. In these cases you may output either one.

This is code-golf so answers will be scored in bytes with less bytes being better.
Test Cases
Payments, denominations    -> requests
{22,8}    {1,2,5,10,20,50} -> {1} or {2}
{2,1,2}   {1,5}            -> {1}
{20,10}   {1,2,5,10,20,50} -> {}
{1,1,1,1} {1,2}            -> {1,1,1}
{20,6}    {1,4,5}          -> {1}
{2,6}     {1,2,7}          -> {2}
{22, 11}  {1, 3, 30, 50}   -> {1, 3}
{44, 22}  {1, 3, 30, 50}   -> {1, 3, 3, 30}

At first I thought this was spam or off-topic or something...

@EriktheOutgolfer paragraphs hurt challenges so much >_<

I don't understand why {1} isn't the output for all the examples? My understanding is that when you go up to the teller, and say (e.g.) "I'd like $8, one partition of $2 and another of $6. Also, there must be at least one $1 bill", why that wouldn't produce a partition e.g. of ($1,$1) and ($2,$2,$2)? Why doesn't $1 work, and why do you have to specify $2?

@ChartZBelatedly
I had to read the task several times but I think now I understand it. You try to give the teller as little information as necessary. To stay with the example with the 2$ and 6$ partition. If you give the teller the information you need 8$ and want one of them to be a 1$ bill there are different outcomes: (1,7), (1,1,2,2,2), (1,1,1,1,1,1,1,1) etc. The last two would do the job, but (1,7) would not fit our partition. Although it did meet the criteria. It has at least one 1$ bill and added up we get 8$.

JavaScript (ES6), 485 476 bytes
Alright ... this is a monster. :-(
But it's a rather fast monster that solves all test cases almost instantly.
I may attempt some more advanced golfing later, but I've already spent far too much time on it.
f=(b,a,L=[...a])=>L.reduce((a,x)=>[...a,...a.map(y=>[x,...y])],[[]]).sort((a,b)=>a[b.length]||-1).find(L=>(Y=G(U(b)-U(L),L.sort((a,b)=>a-b)),Y[0]&&!Y.some(a=>P(b.map(a=>G(a,[]))).every(b=>b+''!=a))),U=a=>~~eval(a.join`+`),P=(e,C=[],R=[])=>e[0].map(v=>R=(c=v.map((x,i)=>x+(C[i]|0)),e[1])?[...P(e.slice(1),c),...R]:[c,...R])&&R,G=(n,l)=>(S=[],g=(n,l)=>n?a.map(x=>x<l[0]|x>n||g(n-x,[x,...l])):S=[l.map(v=>s[a.indexOf(v)]++,s=[...a].fill(0))&&s,...S])(n,l)&&S)||f(b,a,[...a,...L])

Test cases

f=(b,a,L=[...a])=>L.reduce((a,x)=>[...a,...a.map(y=>[x,...y])],[[]]).sort((a,b)=>a[b.length]||-1).find(L=>(Y=G(U(b)-U(L),L.sort((a,b)=>a-b)),Y[0]&&!Y.some(a=>P(b.map(a=>G(a,[]))).every(b=>b+''!=a))),U=a=>~~eval(a.join`+`),P=(e,C=[],R=[])=>e[0].map(v=>R=(c=v.map((x,i)=>x+(C[i]|0)),e[1])?[...P(e.slice(1),c),...R]:[c,...R])&&R,G=(n,l)=>(S=[],g=(n,l)=>n?a.map(x=>x<l[0]|x>n||g(n-x,[x,...l])):S=[l.map(v=>s[a.indexOf(v)]++,s=[...a].fill(0))&&s,...S])(n,l)&&S)||f(b,a,[...a,...L])

console.log(JSON.stringify(f([22,8], [1,2,5,10,20,50])))
console.log(JSON.stringify(f([2,1,2], [1,5])))
console.log(JSON.stringify(f([20,10], [1,2,5,10,20,50])))
console.log(JSON.stringify(f([1,1,1,1], [1,2])))
console.log(JSON.stringify(f([20,6], [1,4,5])))
console.log(JSON.stringify(f([2,6], [1,2,7])))
console.log(JSON.stringify(f([22,11], [1,3,30,50])))
console.log(JSON.stringify(f([44,22], [1,3,30,50])))

How?
NB: This is not matching the current version anymore, but is much easier to read that way.
// b = list of payments, a = list of bills,
// L = list from which the requested bills are chosen
f = (b, a, L = [...a]) => (
  // U = helper function that computes the sum of an array
  U = a => ~~eval(a.join`+`),

  // P = function that computes the summed Cartesian products of arrays of integers
  // e.g. P([[[1,2],[3,4]], [[10,20],[30,40]]]) --> [[33,44], [13,24], [31,42], [11,22]]
  P = (e, C = [], R = []) => e[0].map(v => R =
    (c = v.map((x, i) => x + (C[i] | 0)), e[1]) ? [...P(e.slice(1), c), ...R] : [c, ...R]
  ) && R,

  // G = function that takes a target amount and a list of requested bills and returns
  // all combinations that contain the requested bills and add up to this amount;
  // each combination is translated into a list of number of bills such as [2,0,0,1,0]
  G = (n, l) => (
    S = [],
    g = (n, l) => n ?
      a.map(x => x < l[0] | x > n || g(n - x, [x, ...l])) :
      S = [l.map(v => s[a.indexOf(v)]++, s = [...a].fill(0)) && s, ...S]
  )(n, l) && S,

  // compute X = list of possible bill combinations to process all payments
  X = P(b.map(a => G(a, []))),

  // compute the powerset of L and sort it from shortest to longest list
  L.reduce((a, x) => [...a, ...a.map(y => [x, ...y])], [[]])
  .sort((a, b) => a[b.length] || -1)

  .find(L => (
    // compute Y = list of possible combinations to reach the total amount,
    // using the requested bills
    Y = G(U(b) - U(L), L.sort((a, b) => a - b)),

    // exit if Y is not empty and all combinations in Y allow to generate all payments
    Y[0] && !Y.some(a => X.every(b => b + '' != a)))
  )

  // if no solution was found, enlarge the set of requested bills and try again
  || f(b, a, [...a, ...L])
)

I'm not too familiar with javascript, but can you reduce the && to & and the || to |?

@TaylorScott This is only possible under certain conditions. For instance, a || b will evaluate b only if a is falsy, while a | b will unconditionally perform a bitwise OR between a and b.

Python 2, 456 455 bytes
Extremely, extremely, extremely slow!!!!
Should work correctly on all the input examples given enough time
Edit: Saved 1 byte thanks to @Jonathan Frech
def F(p,d):v=sum(p);E=enumerate;l=lambda x,y:y[1:]and(x>=y[-1]and[k+[y[-1]]for k in l(x-y[-1],y)]+l(x,y[:-1])or l(x,y[:-1]))or[[1]*x];Q=l(v,d);m=lambda x,y=[0]*len(p):x and max(m(x[1:],[a+x[0]*(i==j)for i,a in E(y)])for j,_ in E(y))or y==p;f=lambda x,h=[]:x and min([S for i,s in E(x)for S in h+[s],f(x[:i]+x[i+1:],h+[s])if all(map(m,filter(lambda k:all(k.count(j)>=S.count(j)for j in S),Q)))],key=len)or[1]*v;print-(all(map(m,Q))-1)*min(map(f,Q),key=len)

Try it online!
Explanation
p,d=input() # Read input
v=sum(p) # Save a byte by keeping track of the total money withdrawn
E=enumerate # We use enumerate a lot
# Generates the possible combinations of denominators that add up to the withdrawn amount
l=lambda x,y:y[1:]and(x>=y[-1]and[k+[y[-1]]for k in l(x-y[-1],y)]+l(x,y[:-1])or l(x,y[:-1]))or[[1]*x]
# We use the list generated by l quite a few times
Q=l(v,d)
# Checks if we can divide a list of denominators x in such a way that we get the wished division of the money
m=lambda x,y=[0]*len(p):x and max(m(x[1:],[a+x[0]*(i==j)for i,a in E(y)])for j,_ in E(y))or y==p
# For a list of denominators, it tries all possible combinations of the denominators as input to the teller, selecting the one with minimum length
f=lambda x,h=[]:x and min([S for i,s in E(x)for S in h+[s],f(x[:i]+x[i+1:],h+[s])if all(map(m,filter(lambda k:all(k.count(j)>=S.count(j)for j in S),Q)))],key=len)or[1]*v
# Call f with all possible lists of denominators, and check if saying nothing to the teller will work
print-(all(map(m,Q))-1)*min(map(f,Q),key=len)

Using a function rather than input() is one byte shorter.

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


text:
Make a zigzag pattern
Your task is to take in one integer input and print a zigzag pattern using slashes and backslashes.

The integer input determines the length of each zig and zag, as well as the number of zigs and zags
The pattern always starts from right to left

Test Cases
4->
   /
  /
 /
/
\
 \
  \
   \
   /
  /
 /
/
\
 \
  \
   \
2->
 /
/
\
 \
0->
1->
/
8->
       /
      /
     /
    /
   /
  /
 /
/
\
 \
  \
   \
    \
     \
      \
       \
       /
      /
     /
    /
   /
  /
 /
/
\
 \
  \
   \
    \
     \
      \
       \
       /
      /
     /
    /
   /
  /
 /
/
\
 \
  \
   \
    \
     \
      \
       \
       /
      /
     /
    /
   /
  /
 /
/
\
 \
  \
   \
    \
     \
      \
       \

Can we output an array/list of strings for each line? Are training or leading newlines or spaces allowed?

Is leading whitespace okay as long as the pattern is unaffected?

Charcoal, 16 10 9 bytes
ＦＮ«↖Ｉθ→‖Ｔ

Try it online! Link is to verbose version of code.

this works (Was InputNumber broken in golfy mode too?)

@ASCII-only No, thus the separate links to the given succinct version and the approximate verbose version.

Oh >_> didn't look to see which link I was opening

@ASCII-only Well there's only one link now ;-)

C (gcc), 108 102 101 98 80 76 72 bytes

Saved six bytes thanks to Kevin Cruijssen; removing parentheses and golfing N-n-1 to N+~n
Saved a byte by moving Z's incrementation into the loop condition
Saved three bytes by using printf("%c\n",...) instead of putchar(...) and ,puts("")
Saved eighteen (!) bytes thanks to HatsuPointerKun; using printf("%*s",n,""); to print n spaces instead of using a loop j;for(j=n;j--;)putchar(32); and combining both printf(...); calls
Saved four bytes by using printf("%*c",-~n,...); instead of printf("%*s%c",n,"",...);
Saved four bytes thanks to nwellnhof; moving everything inside one loop instead of two

j;f(k){for(j=0;j<k*k;j++)printf("%*c\n",j/k%2?j%k+1:k-j%k,j/k%2?92:47);}

Try it online!

Z,n,j;f(N){for(Z=0;Z<N;Z++)for(n=N;n--;putchar(Z%2?92:47),puts(""))for(j=Z%2?N+~n:n;j--;)putchar(32);} 102 bytes. Removed the curly brackets by putting everything inside the loops; and changed N-n-1 to N+~n.

@KevinCruijssen Thanks. Saved another byte by swapping both Z%2?...:... and replacing Z<N;Z++ with Z++<N;.

You can save several bytes by using the printf magic like i did in my answer. That way you will get rid of the for loop used to print spaces. For more details, see this stack overflow answer about left padding spaces with printf

@HatsuPointerKun Thanks; that is a really short way to repeat spaces in C.

4 bytes shorter: i;f(N){for(i=0;i<N*N;i++)printf("%*c\n",i/N%2?i%N+1:N-i%N,i/N%2?92:47);}. Try it online!

@nwellnhof Thanks. I was wondering if it would be shorter in a single loop; great that it is!

MATL, 17 bytes
:"GXy@o?P47}92]*c

Try it online!
Explanation
:         % Implicit input, n. Push range [1 2 ... n]
"         % For each k in that range
  G       %   Push n again
  Xy      %   Identity matrix of that size
  @       %   Push k
  o?      %   If it's odd
    P     %     Flip the matrix upside down
    47    %     Push 47 (ASCII for '/')
  }       %   Else
    92    %     Push 92 (ASCII for '\')
  ]       %   End
  *       %   Multiply each entry of the matrix by that number
  c       %   Convert to char. Char 0 is shown as space
          % Implicit end. Implicit display

C# (.NET Core),  117 103 101 bytes
a=>{for(int z=a+1,e=0;e<a*a;)System.Console.WriteLine(e++/a%2<1?"/".PadLeft(--z):@"\".PadLeft(z++));}

Try it online!

You can save 14 bytes like this: a=>{var o="";for(int z=a+1,e=0;e<a*a;)o+=(e++/a%2<1?"/".PadLeft(--z):@"\".PadLeft(z++))+"\n";return o;} 103 bytes You don't need all those parenthesis; you can combine the int; and only add +"\n" once.

Hmm, you can save 2 more bytes by printing directly, instead of returning a string: a=>{for(int z=a+1,e=0;e<a*a;)System.Console.WriteLine(e++/a%2<1?"/".PadLeft(--z):@"\".PadLeft(z++));} 101 bytes

Javascript ES8, 83 79 78 76 75 74 71 bytes
*reduced 1 byte with ES8 thanks to Shaggy
A=(m,i=0)=>i<m*m?`/\\`[x=i/m&1].padStart(x?i%m+1:m-i%m)+`
`+A(m,++i):""

Test here

whoever downvoted my solution, could you explain why? Am i missing something?

I'm not the one who downvoted, but I assume that it is because functions need to be repeatable to be valid. Yours could be fixed pretty easily by making i a default parameter. The byte count seem off as well.

Adding a TIO link is always appreciated as well, so that people can easily test your solution.

@Emigna fixed it (char wise and Link wise) :)

74 bytes with some ES8. Also, for JS you can just use a Stack Snippet rather than TIO.

@Shaggy im new to StackExchange, how can i insert Stack Snippet?

SOGL V0.12, 13 12 9 bytes
╝F{±↔}P}ø

Try it Here!
could be 8 bytes ╝F{±↔}P} if the 0 test-case wasn't required
Explanation:
       }   implicitly started loop repeated input times
╝            create a down-right diagonal of the input
 F           get the current looping index, 1-indexed
  {  }       that many times
   ±↔          reverse the diagonal horizontally
      P      print that
        ø  push an empty string - something to implicitly print if the loop wasn't executed

Python 2, 69 68 62 bytes
-1 byte thanks to Jonathan Frech

lambda n:[[~i,i][i/n%2]%n*' '+'/\\'[i/n%2]for i in range(n*n)]

Try it online!

68 bytes.

Mathematica, 84 90 bytes
(n=#;Grid@Array[If[Abs[n-(s=Mod[#-1,2n])-.5]==#2-.5,If[s<n,"/","\\"],""]&,{n^2,n}])&

Thank Jenny_mathy for -6 bytes.

I have no idea why \ is obviously darker than /.

84 bytes (n=#;Grid@Array[If[Abs[n-(s=Mod[#-1,2n])-.5]==#2-.5,If[s<n,"/","\\"],""]&,{n^2,n}])&

Jq 1.5, 94 89 bytes
["/","\\"][range($n)%2]as$s|range($n)|[(range(if$s=="/"then$n-.-1 else. end)|" "),$s]|add

Explanation
  ["/","\\"][range($n)%2] as $s                         # for $s= / \ / \ $n times
| range($n)                                             # for .=0 to $n-1
| [(range(if $s=="/" then $n-.-1 else . end)|" "), $s]  # form list of spaces ending with $s
| add                                                   # concatenate

Sample Run
$ jq -Mnr --argjson n 5 '["/","\\"][range($n)%2]as$s|range($n)|[(range(if$s=="/"then$n-.-1 else. end)|" "),$s]|add'
    /
   /
  /
 /
/
\
 \
  \
   \
    \
    /
   /
  /
 /
/
\
 \
  \
   \
    \
    /
   /
  /
 /
/

Try it online!

Java 8, 140 134 116 bytes
n->{String r="";for(int a=0,b,c;a++<n;)for(b=n;b-->0;r+=a%2>0?"/\n":"\\\n")for(c=b-n+b|-a%2;++c<b;r+=" ");return r;}

-24 bytes thanks to @Nevay.
Explanation:
Try it here.
n->{                // Method with integer parameter and String return-type
  String r="";      //  Result-String
  for(int a=0,b,c;  //  Index integers
      a++<n;)       //  Loop (1) from 0 to the input (exclusive)
    for(b=n;        //   Reset `b` to the input
        b-->0;      //   Inner loop (2) from the input to 0 (exclusive)
                    //     After every iteration:
        r+=a%2>0?"/\n":"\\\n")
                    //      Append either of the slashes + a new-line
      for(c=b-n+b|-a%2;++c<b;r+=" ");
                    //    Append the correct amount of spaces
                    //   End of inner loop (2) (implicit / single-line body)
                    //  End of loop (1) (implicit / single-line body)
  return r;         //  Return the result-String
}                   // End of method

The condition of the innermost loop can be written as c-->f*(b-n-~b) (-6 bytes).

116 bytes: n->{String r="";for(int a=0,b,c;a++<n;)for(b=n;b-->0;r+=a%2>0?"/\n":"\\\n")for(c=b-n+b|-a%2;++c<b;r+=" ");return r;}

C++, 92 91 bytes
-1 bytes thanks to Kevin Cruijssen
void m(int n){for(int i=0,j;i<n;++i)for(j=0;j<n;++j)printf("%*c\n",i%2?j+1:n-j,i%2?92:47);}

Thanks to the power of the magic printf

You can put the int i=0,j in the for-loop for(int i=0,j;i<n;++i) to save a byte.

88 bytes

Java (OpenJDK 8), 131 106 98 96 94 91 bytes
i->{for(int j=0;j<i*i;System.out.printf("%"+(j/i%2<1?i-j%i:j%i+1)+"c\n",47+45*(j++/i%2)));}

Try it online!

You can remove quite a few parentheses: i->{for(int j=0;j<i*i;System.out.printf("%"+(j/i%2<1?i-j%i+1:j%i+2)+"s",j++/i%2<1?"/\n":"\\\n"));} (98 bytes).

Pyth, 20 bytes
Lm+*;dbQjs<*,_y\/y\\

Try it online!

PowerShell, 81 bytes
param($a)if($a){1..$a|%{((1..$a|%{" "*--$_+'\'}),($a..1|%{" "*--$_+'/'}))[$_%2]}}

Try it online!
Ugh, this is ugly. So much repeated code, plus 7 bytes required to account for 0 special case. Golfing suggestions welcome.

Pyth, 17 bytes
js<*_+RV"\/"_B*L;

Try it online: Demonstration
Explanation:
js<*_+RV"\/"_B*L;QQQ   implicit Qs at the end
              *L;Q     list with ["", " ", "  ", ..., " "*(input-1)]
            _B         bifurcate with reverse: [["" to "   "], ["   " to ""]]
     +RV"\/"           append to each one either "\" or "/":
                       [["\", to "   \"], ["   /" to "/"]]
    _                  reverse
   *              Q    repeat input times
  <                Q   but only take the first input many
 s                     flatten the list of lists
j                      print on each line

05AB1E, 17 16 bytes
F<„/\Nèú.sNƒR}»,

Try it online!
Explanation
F                  # for N in [0 ... input-1] do
  „/\              # push the string "/\"
     Nè            # cyclically index into this string with N
 <     ú           # prepend input-1 spaces to this string
        .s         # get suffixes
          NƒR}     # reverse the list of suffixes input+1 times
              »,   # join on newline and print

Current best attempt using canvas:
F„/\Nè©53NèΛ2®ð«4Λ

Python 3: 90 Bytes 82 Bytes
lambda n:"\n".join(" "*(abs(i%(n*2)-n+i//n%2)-1)+"/\\"[i//n%2]for i in range(n*n))

Thanks to @Jonathan Frech for pointing out that print wasn't needed and that the first zig was the wrong way

] for -> ]for.

You do not need the print(...), a function returning a string would be valid. Also, I think your initial zig is oriented the wrong way (\ rather than /).

@JonathanFrech Thanks! I changed it

(abs(...)-1) -> ~-abs(...).

Dyalog APL, 39 36 35 34 bytes
{↑((,⍵ ⍵⍴(⌽,⊢)⍳⍵)/¨' '),¨⍵/⍵⍴'/\'}

Try it online!
1 byte saved thanks to Zacharý

Dang it, beat me by one byte. You can make ⎕IO be 0, and then remove ¯1+.

@Zacharý I was just about to do that :p

Oh, one more thing: (⌽,⊢)⍳⍵ instead of (⌽⍳⍵),⍳⍵

@Zacharý Yeah, I'm yet to understand the tacks, tacitness and stuff that comes with that :/

Don't worry, I don't fully understand how trains/forks/whatever-they're-called work either.

Perl 5, 70 + 1 (-n) = 71 bytes
$n=$_**2;$_=$"x--$_.'/';say&&s% /%/ %||s%\\ % \\%||y%\\/%/\\%while$n--

Try it online!

Excel VBA, 84 83 Bytes
Anonymous VBE immediate window function that takes input from range [A1] and outputs to the VBE immediate window
For i=1To[A1]:For j=1To[A1]:?IIf(i mod 2,Space([A1]-j)&"/",Space(j-1)&"\"):Next j,i

Kotlin, 102 bytes
(0..q-1).map{r->if(r%2<1)q-1 downTo 0 else{0..q-1}.map{(1..it).map{print(' ')};println('/'+45*(r%2))}}

Try it online!

Jelly, 15 bytes
ḶṚ⁶ẋm0ż⁾/\x$ṁ²Y

Try it online!
Full program.

Haskell, 86 85 bytes
f n=take(n*n)$cycle$[(' '<$[x..n-1])++"/"|x<-[1..n]]++[(' '<$[2..x])++"\\"|x<-[1..n]]

Try it online!
Saved one byte thanks to Laikoni
Repeat a zig ++ a zag, and take the first n*n lines.

cycle$ ... instead of cycle( ... ) saves a byte.

J, 39 35 33 32 25 bytes
' /\'{~[,/@$(|.,:+:)@=@i.

Try it online!

Dyalog APL, 41 40 bytes
⎕IO must be 0.
{⍪/((⌽⍵ ⍵⍴S↑'/')(⍵ ⍵⍴'\'↑⍨S←⍵+1))[2|⍳⍵]}

Try it online!

D, 105 bytes
import std.stdio;void m(T)(T n){for(T i,j;i<n;++i)for(j=0;j<n;++j)printf("%*c\n",i%2?j+1:n-j,i%2?92:47);}

Try it online!
Lifted from HatsuPointerKun's C++ answer.

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


text:
Is the matrix rank-one?
Given a matrix of integers, test if it's rank-one, meaning that every row is a multiple of the same vector. For example, in
 2   0  -20  10
-3   0   30 -15
 0   0   0   0

every row is a multiple of 1 0 -10 5.
The same definition also works with columns in place of rows. Alternatively, a matrix is rank-one if it's like a multiplication table:
 *    1   0  -10  5
    ----------------
 2 |  2   0  -20  10
-3 | -3   0   30 -15
 0 |  0   0   0   0

We've assigned row labels r[i]and column labels c[j] so that each matrix entry M[i][j] is the product of the corresponding labels as M[i][j] = r[i] * c[j].
Input:
An integer matrix as a 2D container of your choice. For example, a list of lists, a 2D array, or similar. You shouldn't take the width or height as additional inputs unless the array format requires it.
The matrix may be non-square.  It will have at least one nonzero entry -- you don't have to deal with empty or zero matrices.
You can assume the integers won't cause overflow issues.
Output:
A consistent value for rank-one matrices, and a different consistent value for other matrices.
Built-ins:
You may not use any built-in to computes rank or directly check rank one. You may use other built-ins like eigenvalues, decompositions, etc, but I encourage upvoting answers that don't have built-ins do most of the work.
Test cases:
Rank-one:
[[2, 0, -20, 10], [-3, 0, 30, -15], [0, 0, 0, 0]]
[[0, 0, 0], [0, 3, 0], [0, 0, 0]]
[[-10]]
[[0, 0, 0], [0, 4, 11], [0, -4, -11]]

Not rank-one:
[[-2, 1], [2, 4]]
[[0, 0, 3], [-22, 0, 0]]
[[1, 2, 3], [2, 4, 6], [3, 6, 10]]
[[0, -2, 0, 0], [0, 0, 0, 1], [0, 0, -2, 0]]

Leaderboard:

var QUESTION_ID=143528,OVERRIDE_USER=20260;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/143528/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="
"+e.body.replace(OVERRIDE_REG,"")+"
")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
 <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

{{PLACE}}	{{NAME}}	{{LANGUAGE}}	{{SIZE}}	Link

{{LANGUAGE}}	{{NAME}}	{{SIZE}}	Link

For the curious, a Mathematica response using builtins would look like this (16 bytes): MatrixRank@#==1&

Related

A beautiful theorem is that column rank is equal to row rank for finite dimensional matrices.

Do we have to worry about float precision issues? They may make a rank-1 matrix seem rank 2 for instance

@LuisMendo You do have to handle precision issues like an eigenvalues of 1.0000000001, but can assume the matrix is not large and not specifically chosen to be misclassified.

Jelly, 6 bytes
ẸÐfÆrE

Try it online!
How it works
ẸÐfÆrE  Main link. Argument: M (2D array)

ẸÐf     Filter by any, removing rows of zeroes.
   Ær   Interpret each row as coefficients of a polynomial and solve it over the
        complex numbers.
     E  Test if all results are equal.

Precision
Ær uses numerical methods, so its results are usually inexact. For example, the input [6, -5, 1],  which represents the polynomial 6 - 5x + x², results in the roots 3.0000000000000004 and 1.9999999999999998. However, multiplying all coefficients of a polynomial by the same non-zero constant results in equally inexact roots. For example, Ær obtains the same roots for [6, -5, 1] and [6 × 10100, -5 × 10100, 10100].
It should be noted that the limited precision of the float and complex types can lead to errors. For example, Ær would obtain the same roots for [1, 1] and [10100, 10100 + 1]. Since we can assume the matrix is not large and not specifically chosen to be misclassified, that should be fine.

multiplying all coefficients of a polynomial by the same non-zero constant results in equally inexact roots That's a brilliant approach

Haskell, 50 bytes
r takes a list of lists of Integers and returns False if the matrix has rank one, True otherwise.
r l=or[map(x*)b<map(y*)a|a<-l,b<-l,(x,y)<-zip a b]

Try it online!
How it works

Generates all pairs of rows a and b (including equal rows), and for each pair, lets x and y run through corresponding elements.
Multiplies the row b by x and the row a by y. The matrix will have rank one if and only if the results are always equal.
Since pairs are generated in both orders, < can be used to check if there's ever an inequality. The list of test results are combined with or, giving True if there are any non-proportional rows.

Mathematica, 51 33 bytes
RowReduce@#~Count~Except@{0..}<2&

Input

[{{2,0,-20,10},{-3,0,30,-15},{0,0,0,0}}]

-14 bytes from user202729
3 more bytes saved from junghwanmin

I suggest that, instead of construct a table with length equal to that of First@#, you can calculate 0First@# since 0 multiplies with everything is 0, and multiplication is listable. Also you may consider using Tr[1^<list>] to calculate the length of a list.

very nice.I'll edit!

Instead of 0#&@@#, {0..} would work too. And then Infix works, so the final code could be RowReduce@#~Count~{0..}==Tr[1^#]-1&, saving 2 bytes.

Actually, Except can be used to get rid of Tr stuff. -3 bytes: RowReduce@#~Count~Except@{0..}==1&

I think the row-reduced matrix is guaranteed to be nonzero (because the original matrix is nonzero), thus the count result will be an positive integer, thus <2 can be used instead of ==1.

JavaScript (ES6), 68 67 65 bytes
This one is based on Neil's 05AB1E answer and is significantly more efficient than my original approach.
Returns false for rank-one and true otherwise.
f=(a,R,V,X)=>a.some(r=>r.some((v,x)=>R?v*V-r[X]*R[x]:f(a,r,v,x)))

Test cases

f=(a,R,V,X)=>a.some(r=>r.some((v,x)=>R?v*V-r[X]*R[x]:f(a,r,v,x)))

console.log(f([[2, 0, -20, 10], [-3, 0, 30, -15], [0, 0, 0, 0]]))
console.log(f([[0, 0, 0], [0, 3, 0], [0, 0, 0]]))
console.log(f([[-10]]))
console.log(f([[0, 0, 0], [0, 4, 11], [0, -4, -11]]))

console.log(f([[-2, 1], [2, 4]]))
console.log(f([[0, 0, 3], [-22, 0, 0]]))
console.log(f([[1, 2, 3], [2, 4, 6], [3, 6, 10]]))
console.log(f([[0, -2, 0, 0], [0, 0, 0, 1], [0, 0, -2, 0]]))

Original answer, 84 bytes
Returns false for rank-one and true otherwise.
a=>a.some(r=>r.some((x,i)=>(isNaN(x/=a.find(r=>r.some(x=>x))[i])?r:1/r[0]?r=x:x)-r))

Test cases

let f =

a=>a.some(r=>r.some((x,i)=>(isNaN(x/=a.find(r=>r.some(x=>x))[i])?r:1/r[0]?r=x:x)-r))

console.log(f([[2, 0, -20, 10], [-3, 0, 30, -15], [0, 0, 0, 0]]))
console.log(f([[0, 0, 0], [0, 3, 0], [0, 0, 0]]))
console.log(f([[-10]]))
console.log(f([[0, 0, 0], [0, 4, 11], [0, -4, -11]]))

console.log(f([[-2, 1], [2, 4]]))
console.log(f([[0, 0, 3], [-22, 0, 0]]))
console.log(f([[1, 2, 3], [2, 4, 6], [3, 6, 10]]))
console.log(f([[0, -2, 0, 0], [0, 0, 0, 1], [0, 0, -2, 0]]))

How?
a => a.some(r =>          // given a matrix a, for each row r of a:
  r.some((x, i) =>        //   for each value x of r at position i:
    (                     //
      isNaN(x /=          //     divide x by a[ref][i]
        a.find(r =>       //       where ref is the index of the first row that
          r.some(x => x)  //       contains at least one non-zero value
        )[i]              //       (guaranteed to exist by challenge rules)
      ) ?                 //     we get NaN for 0/0, in which case:
        r                 //       use r, so that this column is ignored
      :                   //     else:
        1 / r[0] ?        //       if r is still holding the current row:
          r = x           //         set it to x (either a float, +Inf or -Inf)
        :                 //       else:
          x               //         use x
    ) - r                 //     subtract r from the value set above (see table)
  )                       //   end of some()
)                         // end of every()

The subtraction which is performed at the end of the code can lead to many different situations, which are summarized below:
A                   | B              | A - B       | False / True
--------------------+----------------+-------------+-------------
array of 1 number   | same array     | 0           | False
array of 2+ numbers | same array     | NaN         | False
a number            | same number    | 0           | False
+Infinity           | +Infinity      | NaN         | False
-Infinity           | -Infinity      | NaN         | False
a number            | another number | <> 0        | True
+Infinity           | -Infinity      | +Infinity   | True
-Infinity           | +Infinity      | -Infinity   | True
a number            | +/-Infinity    | +/-Infinity | True
+/-Infinity         | a number       | +/-Infinity | True

The test fails as soon as we get a truthy value: this happens when we encounter two distinct ratios (other than 0 / 0) between a(i,y) and a(i,r) in any row y of the matrix, where r is the index of a non-zero row.

Huh, I was just wondering that myself...

@Neil Would you like to post it as a new answer? Just let me know.

05AB1E, 16 13 bytes
2ãεø2ãε`R*E]W

Try it online! Uses the multiplication table property that the opposite corners of any rectangle have the same product. Edit: Saved 3 bytes thanks to @KevinCruijssen. Explanation:
2ãε             Loop over each pair of rows
   ø            Transpose the pair into a row of pairs
    2ãε         Loop over each pair of columns
       `R*E     Cross-multiply and check for equality
           ]W   All results must be true

I know it's been a while, but this can be 11 bytes without changing the actual approach (even in the legacy version). I don't know if this was already the case when you posted your answer, but: ã implicitly uses 2 if no integer is given, so the two 2 can be removed for -2; the W can take the flattened minimum, so }W}W can be ]W for another -2; and *`Q to check if both inner lists are the same can be *Ë for another 1.

@KevinCruijssen ã didn't do that at the time, but the other two look sensible.

Python 2 + numpy, 58 bytes
lambda m:sum(linalg.svd(m)[1]>1e-10)==1
from numpy import*

Try it online!
Credit to this.

Could one use 1e-9 instead of 1e-10?

Jelly, 12 bytes
ẸÐfµ÷"Ð€ZE€Ẹ

Try it online!
Explanation
ẸÐfµ÷"Ð€ZE€Ẹ  Main link
 Ðf           Filter; keep all elements where
Ẹ             At least one element is truthy (remove zero-rows)
      Ð€      For each row on the right side
    ÷"        Divide it by each row in the original
        Z     Zip the array
          €   For each submatrix
         E    Are all rows equal?
           Ẹ  Is at least one of the elements from above truthy?

Explanation may be slightly incorrect as this is my interpretation of miles's golf of my original algorithm
-5 bytes thanks to miles

...Your code is addicted to money. (I'm getting deja vu...)

@icrieverytim Hey at least the number of dollar signs is less than half of the length of the code this time! :P

@icrieverytim fixed a bug and now even fewer dollar signs :P

I believe this should work too for 12 bytes ẸÐfµ÷"Ð€ZE€Ẹ TIO

@miles Oh nice! The approach for yours is a bit different (I think?) so you can post that as your own answer of you'd like :)

Oh no, its the same as yours pretty much.

@miles oh wait I misinterpreted how your code worked whoops. a thanks! :D

Luckily we don't have to deal with all-zero matrices (I commented to ask for it but noticed they are explicitly excluded, even though by the definition they would pretty clearly be rank one).

TI-Basic (TI-83 series), 28 27 28 bytes (62 characters)
:Prompt [A]
:{0→X
:Matr►list(ref([A])ᵀ,L₁,X
:not(max(abs(ᶫX

Computes the row-echelon form of the matrix [A], stores its first row (to be discarded) in L₁ and its second row in ᶫX. Then max(abs(ᶫX will be zero if ᶫX consists only of zeroes, and a positive value otherwise, which not( changes to 1 if the matrix is rank one, 0 otherwise.
For a 1-row matrix, ᶫX is set to {0} and then doesn't get changed when we try to look at the nonexistent second row of the matrix.

-1 byte thanks to Scott Milner
+1 byte to fix dimension error for 1-row matrices. Turns out the Matr►list( command complains if you try to extract the second row from a matrix with only one row; however, if you try to extract the first and second row both from the matrix, it will fail silently.

You can save a byte with Prompt [A] instead of Ans→[A].

@ScottMilner Thanks! There's probably a way to avoid either if we use something like ClrList to initialize ᶫX, but I haven't quite gotten that to work in less space.

Get rid of the second line, since Matr►list( will overwrite the list, even if it doesn't exist, and you'll save 5 bytes.

@kamoroso94 The point of the second line is not to create a list when it doesn't exist: the point of the second line is to create a default value for the second row when the matrix only has one row. If you get rid of the second line, the code crashes for 1xN matrices.

@MishaLavrov well replace L1 with Y to save a byte since you're not using L1 anyway.  You'll save a byte.

@kamoroso94 We'd have to replace L1 with ᶫY, not Y; otherwise, the calculator will think "extract the Y-th row of the matrix to ᶫX", not "extract the first row to ᶫY, and the second row to ᶫX".

Brachylog, 27 bytes
{⊇Ċ}ᶠzᵐ{↰₁ᶠ{⟨hz{t↔}⟩×ᵐ=}ᵐ}ᵐ

Try it online!
Uses Neil's approach of "products of opposite corners of each rectangle should be equal". Cross product is costly and takes 10 whole bytes, but this is still shorter than any division based approach I tried, mainly because of the stipulation of two consistent outputs for truthy and falsey in the question - making falsey be only a false., and not sometimes a divide-by-zero error, uses too many bytes.
{⊇Ċ}ᶠzᵐ{↰₁ᶠ{⟨hz{t↔}⟩×ᵐ=}ᵐ}ᵐ
{⊇Ċ}ᶠ                        Get each pair of rows from the matrix
                             eg.: [ [[a, b, c], [k, l, m]], ... ]
     zᵐ                      Zip each pair's elements
                                  [ [[a, k], [b, l], [c, m]], ... ]
       {                 }ᵐ  Map this over each pair of rows:
                                  [[a, k], [b, l], [c, m]]
        ↰₁ᶠ                  Get each pair of paired elements from the rows
                                  [[[a, k], [b, l]], [[b, l], [c, m]], [[a, k], [c, m]]]
           {           }ᵐ    Map this over each pair of pairs
                                  [[a, k], [b, l]]
            ⟨hz{t↔}⟩         Zip the first pair with the reverse of the second
                                  [[a, l], [k, b]]
                    ×ᵐ       Multiply within each sublist
                                  [al, kb]
                      =      The results should be equal
                             (If the results are unequal for any pair, the whole predicate fails,
                              and outputs false.)

Alternate approach based on element-wise division (30 bytes):
{≡ᵉ¬0&}ˢ\↰₁ˢ{c×¬0&⟨hz∋⟩ᶠ/ᵐ²=ᵐ}

Try it online!

Jelly, 9 bytes
ẸÐf÷g/$€E

Try it online!
ẸÐf         Discard zero rows
   ÷  $€    Divide each row by
    g/        its greatest common divisor
        E   Does this list have only one unique element?

SageMath, 40 bytes
lambda M:any(M.rref()[1:])*(M.nrows()>1)

Try it online
This anonymous function returns False if the matrix is rank-one, and True otherwise.
The function takes a matrix M as input, converts it to reduced row-echelon form (M.rref()), and tests for any of the rows past the first being non-zero. Then, that value is multiplied by M.nrows()>1 (does the matrix have more than one row?).

Python 3, 93  91 bytes
lambda m,e=enumerate:any(h*g-r[j]*s[i]for r in m for i,h in e(r)for s in m for j,g in e(s))

Try it online!
How it works
Checks if any 2-minor has nonzero determinant. If this is the case the rank must be at least 2:
"A non-vanishing p-minor (p × p submatrix with non-zero determinant) shows that the rows and columns of that submatrix are linearly independent, and thus those rows and columns of the full matrix are linearly independent (in the full matrix), so the row and column rank are at least as large as the determinantal rank" (from Wikipedia)
Note: shaved two bytes thanks to user71546's comment.

91 - shorter if putting enumerate into the function arguments and thus eliminating the need of f=: lambda m,e=enumerate:any(h*g-r[j]*s[i]for r in m for i,h in e(r)for s in m for j,g in e(s))

@user71546 Thanks! Done it!

Pari/GP, 18 bytes
a->#matimage(a)==1

matimage gives a basis of the image of the linear transformation defined by the matrix.
Try it online!

Scala, 86 bytes
Golfed version. Try it online!
l=>l.exists(a=>l.exists(b=>a.zip(b).exists{case(x,y)=>b.map(_*x).sum<a.map(_*y).sum}))

Ungolfed version. Try it online!
object Main extends App {
  val lists = List(
    List(List(2, 0, -20, 10), List(-3, 0, 30, -15), List(0, 0, 0, 0)),
    List(List(0, 0, 0), List(0, 3, 0), List(0, 0, 0)),
    List(List(-10)),
    List(List(0, 0, 0), List(0, 4, 11), List(0, -4, -11)),
    List(List(-2, 1), List(2, 4)),
    List(List(0, 0, 3), List(-22, 0, 0)),
    List(List(1, 2, 3), List(2, 4, 6), List(3, 6, 10)),
    List(List(0, -2, 0, 0), List(0, 0, 0, 1), List(0, 0, -2, 0))
  )

  lists.foreach { list =>
    println(s"$list: ${r(list)}")
  }

  def r(list: List[List[Int]]): Boolean = {
    list.exists { a =>
      list.exists { b =>
        a.zip(b).exists { case (x, y) =>
          b.map(_ * x).sum < a.map(_ * y).sum
        }
      }
    }
  }
}


text:
Generate a special period image
Construct a program or function that takes input in form of
<width>, <height>, <color1>, <color2>

and generates an output such that first row alternates between pixels of color  <color1> and <color2> with a period of <height>. For each row that follows, the period shall be <height> - <row number>. Note that <color1> always begins the row.
Sample Output
Input 120, 6, #000000, #FFFF00:

Input 80, 50, #000000, #FFFF00:

(Sample output has been scaled for clarity)
This is code-golf, so the shortest valid entry in bytes wins.

Is that a fractal? Does it have a fractal dimension?

JavaScript (ES6), 177 bytes

g=
(w,h,f,b)=>`<svg${s=` width=${w} height=`+h}><rect${s} fill=${b} />`+[...Array(h)].map((_,i)=>`<line stroke=${f} stroke-dasharray=${h-i} x1=0 y1=${i} x2=${w} y2=${i} />`).join``
Width: <input id=w value=80 type=number min=1>
Height: <input id=h value=50 type=number min=1>
Foreground: <input id=f value=#000000>
Background: <input id=b value=#FFFF00>
<input type=button value=Go! onclick=o.innerHTML=g(+w.value,+h.value,f.value,b.value)>

Outputs an HTML5-compatibile SVG image.

Tcl/Tk, 143
147 150 151
proc P {w h b c} {set p [image c photo -w $w -h $h]
time {incr y
set x 0
time {$p p -t $x $y [expr {[incr x]/($h-$y+1)%2?$c:$b}]} $w} $h
set p}

Returns the image which can be tested, by putting it on a canvas widget, writing on a file, may be on the clipboard, etc.
Code for testing
set w 960
set h 540
pack [canvas .c -w $w -he $h -highlightt 0]
.c cr image 0 0 -image [P $w $h #00ffff #ffbf32] -anchor nw

Excel VBA, 129 122 Bytes
Anonymous VBE immediate window function that takes input from range [A1:D1] and outputs to the range [A2].Resize([B1],[A1])
Cells.RowHeight=48:For Each r in[Offset(A2,,,B1,A1)]:r.Interior.Color=IIf((r.Column-1)\([B1]-R.Row+2)Mod 2,[D1],[C1]):Next

Far More Interesting Version, 160 bytes
Presented w/ newlines in place of : characters for readability
In this version the snippet [Let(r,Offset(A1,,,B1,A1),If(IsOdd((Column(r)-1)/(B1-Row(r)+2)),C1,D1))]
alone is able to calculate the array of values, and all other code is used to output this array as colors to the range [Offset(A1,,,B1,A1)].
Cells.RowHeight=48
[Offset(A2,,,B1,A1)]=[Let(r,Offset(A2,,,B1,A1),If(IsOdd((Column(r)-1)/(B1-Row(r)+2)),C1,D1))]
For Each r In Cells
r.Interior.Color=r
r="
Next

Perhaps this approach my prove fruitful for further improvement?
Output
Output for input 160, 90, 0xBDD7EE, 0xDDEBF7:

Mathematica, 52 bytes
Image@Table[If[Mod[j,2i]>i,#4,#3],{i,-#2,-1},{j,#}]&

Sample input:
Image@Table[If[Mod[j,2i]>i,#4,#3],{i,-#2,-1},{j,#}]&[120,6,Black,Yellow]

C (gcc), 155 143 bytes
Prints a Portable PixMap (.ppm) to stdout.
x,y,z;f(w,h,r,g,b,R,G,B){for(y=~0,printf("P3 %d %d 255",w,h);y++<~-h;)for(x=~0;x++<~-w;)z=(x/(h-y)%2),printf("\n%d %d %d ",z?R:r,z?G:g,z?B:b);}

Try it online!
Output

Input: 80, 50, #ad00df, #f17e18

(Image converted and resized.)

What is the advantage of writing ~0 instead of  -1 ?

@sergiol It looks cooler. And -- theoretically -- if you need a variable containing only 1s, ~0 would be more portable than -1.

this image killed my eyes when I was scrolling past it. +1

MATL, 34 32 29 bytes
-3 bytes thanks to Luis Mendo
XJx:P"1Hh@Y"1Jyn/XkX"J:)]viYG

Try it at MATL Online

Java 8, 321 + 42 = 363 bytes
import java.awt.*;import java.awt.image.*;
(w,h,a,b)->{BufferedImage i=new BufferedImage(w,h,1);Graphics2D g=(Graphics2D)i.getGraphics();g.setColor(new Color(a));g.fillRect(0,0,w,h);g.setColor(new Color(b));for(int j=h;j>0;g.drawLine(0,h-j,w,h-j--))g.setStroke(new BasicStroke(1,0,0,1,new float[]{j},j));javax.imageio.ImageIO.write(i,"png",new java.io.File("a"));}

Outputs to a PNG file named a (no extension).
Surrounding code used to run the lambda: Try it online!
Ungolfed
(w,h,a,b)->{
    BufferedImage i=new BufferedImage(w,h,1);
    Graphics2D g=(Graphics2D)i.getGraphics();
    g.setColor(new Color(a));
    g.fillRect(0,0,w,h);
    g.setColor(new Color(b));
    for(int j=h;j>0;g.drawLine(0,h-j,w,h-j--))
        g.setStroke(new BasicStroke(1,0,0,1,new float[]{j},j));
    javax.imageio.ImageIO.write(i,"png",new java.io.File("a"));
}

Result
Inputs: 80, 50, 0xFF00FF, 0xFFFF00.

SOGL V0.12, 83 bytes
..¹Cbe¹"εģνļ▲I-℮eīÆoHι⅛ļJd⁾)⁶f°┌²‘→e∫Ab∫Ƨ01a∙H∑bmWrcwιFHea-¹"S⁸▒Μ¬NrηA¤Y_⅓ļpPboā⁵‘→

Try it Here!
SOGL was made in Processing.. So I took advantage of that using → - execute as JavaScript. Could easily be many bytes less (at least 30) if SOGL had anything made for graphics.
Uncompressed strings:
..¹Cbe¹"__processing0.hidden=0;cp.size(ŗ,ŗ)”→e∫Ab∫Ƨ01a∙H∑bmWrcwιFHea-¹"cp.stroke(ŗ);cp.point(ŗ,ŗ)”→

Explanation:
..¹C       save the first 2 inputs as an array on variable C
be¹        save next input - width - on B, next input - height - on E, and wrap both in an array
"__processing0.hidden=0;cp.size(ŗ,ŗ)”→
           execute "__processing0.hidden=0;cp.size(ŗ,ŗ)" as JavaScript - show the canvas and set the size to the corresponding items in the array

e∫A        repeat height times, saving 1-indexed counter on A
  b∫       repeat width times, pushing 1-indexed counter
    Ƨ01    push "01"
    a∙     multiply vertically A times             - ["01", "01", "01",...]
    H      rotate anticlockwise                    - ["000...","111..."]
    ∑      join together                           - "000..111.."
    bm     mold to the length of width             - "00011100011100"
    W      get the counterth letter of that string - "1"
    r      convert to number                       - 1
    cw     get that item from the variable C
    ι      remove the array from the stack
    FH     push current loops counter minus 1
    ea-    push e-a - height-outerLoopsCounter
    ¹      wrap the 3 items in an array - [itemInC (color), counter-1 (x position), height-outerLoopsCounter (y position)]

    "cp.stroke(ŗ);cp.point(ŗ,ŗ)”→
           execute "cp.stroke(ŗ);cp.point(ŗ,ŗ)" as JavaScript, replacing ŗ with the corresponding item from the array

SmileBASIC, 84 bytes
DEF C W,H,C,D
FOR J=1TO H
FOR I=0TO W-1N=1AND I/J
GPSET I,H-J,C*!N+D*N
NEXT
NEXT
END

The color of a pixel at (x,height-y) is [color1,color2][x/y & 1]

hm, the specification asks you to input a color.

Python 2, 123 101 bytes
w,h,c,C=input()
print'P3',w,h,255
for i in range(h):
 for j in range(w):print`[c,C][j/(h-i)%2]`[1:-1]

Try it online!
Prints a .ppm to output as in Jonathan's answer.

Looks similar to my C answer... 105 bytes if you change your color input format (as the question does not rigorously define the color format).

@JonathanFrech Thanks :)
Yeah, I got inspired by your answer when looking for a way to output the image.

Just out of curiosity; which program do you use to open your .ppm file?

'%d '*3% is shorter than '%d %d %d'%.

@JonathanFrech This works, or I've used GIMP

Why then did you move from 101 bytes to 104 bytes?

I got confused by the docs. I'll change it back to 101

JavaScript (ES6) + HTML5, 138 bytes
(w,h,a,b)=>{with(c.width=w,c.getContext`2d`)for(c.height=y=h;~--y;)for(x=w;~--x;)fillStyle=x/(h-y)%2<1?a:b,fillRect(x,y,1,1)}

<canvas id=c>

f=
(w,h,a,b)=>{with(c.width=w,c.getContext`2d`)for(c.height=y=h;~--y;)for(x=w;~--x;)fillStyle=x/(h-y)%2<1?a:b,fillRect(x,y,1,1)}
#c{display:block
<input id=w value=80>
<input id=h value=50>
<input id=a value=#000>
<input id=b value=#FF0>
<input value=go type=button onclick=f(w.value,h.value,a.value,b.value)>
<canvas id=c>

The function outputs by operating on the <canvas id=c>.
Starting from the bottom right of the canvas, the nested for loop iterates to the left and up, and checks the condition x/(h-y)%2<1 for the pixel at x,y. If the condition is true, it colors that pixel with color1, else color2.