text:
Factorials and never ending cycles!
As you may know it, the factorial of a positive integer n is the product of all the positive integers which are equal or smaller to n.
For instance :
6! = 6*5*4*3*2*1 = 720
0! = 1

We will now define a special operation with an irrelevant name like sumFac:
Given a positive integer n, sumFac(n) is the sum of the factorials of the digits.
For instance :
sumFac(132) = 1! + 3! + 2! = 9
Task
Your mission, whether or not you choose to accept it, is to return the sequence (potentially infinite) of the applications of sumFac to an integer given in input.
Example : 132 -> 132, 9, 362880, 81369, 403927, ...
But that's not all! Indeed, the applications of sumFac will eventually create a cycle. You must also return this cycle!
If your language has a built in factorial you can use it.
I'm not picky about the return type, you just have to return the sequence of sumFac applications and the cycle in a format understandable by a human.
EDIT : To help you visualize better what should the output look like I copied Leaky Nun's just below:
[132, 9, 362880, 81369, 403927, 367953, 368772, 51128, 40444, 97, 367920, 368649, 404670, 5810, 40442, 75, 5160, 842, 40346, 775, 10200, 6, 720, 5043, 151, 122, 5, 120, 4, 24, 26, 722, 5044, 169, 363601, 1454]

You just need to stop the sequence when the cycle is about to start for the second time!
But this is code-golf so the shortest answer in bytes wins!

Related

Welcome to PPCG! This looks like a nice challenge, BTW.

@Qwerp-Derp Thank you very much! I tried to be creative ^^

@Zgarb Well it's exactly like the output of Leaky Nun. The sequence of the applications and then it shall end just before the beginning of the second cycle. I'll copy his output in the question so everyone can have a clear understanding. Thanks for pointing that out :)

@Antoine 1454 actually maps to 169. Should I just print the cycle or should I print everything from the start?

@LeakyNun You need to print everything that comes before the cycle and end the sequence with the cycle. Which is what you did because the next number would indeed be 169

Related OEIS

How important is the output formatting? Can we have the trailing comma, can the values be separated by a space or a newline instead?

Hardcoding the value 169 is cheating?

@2501 Hardcoding the value is cheating, but concerning the output formatting you can use any separator you want

@Antoine Ok. The constant 169 doesn't help anyway, since some cycles don't contain it.

Jelly, 6 bytes
D!SµÐĿ
    ÐĿ  Repeat until the results are no longer unique. Collects all intermediate results.
D           Convert from integer to decimal (list of digits)
 !          Factorial (each digit)
  S         Sum

Try it online!
I don't see any other way to make it shorter other than to do as told.
Specs

Input: 132 (as command-line argument)
Output: [132, 9, 362880, 81369, 403927, 367953, 368772, 51128, 40444, 97, 367920, 368649, 404670, 5810, 40442, 75, 5160, 842, 40346, 775, 10200, 6, 720, 5043, 151, 122, 5, 120, 4, 24, 26, 722, 5044, 169, 363601, 1454]

I didn't expect to have an answer that short. Nice :)

@Antoine It's Jelly :D It's always shorter than I think it'll be ;)

@HyperNeutrino Somehow Dennis will come with an even shorter answer

Somehow, yes. Because Dennis. :P

So... Which character encoding do you use to come up with 6 bytes for those 6 characters? Isn't Jelly supposed to be UTF-8 encoded, meaning that this program is actually 9 bytes?

@LordOfThePigs Jelly code page

I see, thanks for educating me. I'm a noob at Code Golfing :-)

-1 byte

Python 2, 88 bytes
import math
f=lambda x,l=[]:l*(x in l)or f(sum(math.factorial(int(i))for i in`x`),l+[x])

Try it online!

As a python fan I'm glad someone answered with it, nice :)

05AB1E, 12 bytes
[DˆS!O©¯så#®

Try it online!
Explanation
[               # infinite loop
 Dˆ             # add a copy of current value to the global list (initialized as input)
   S            # split current number to digits
    !O          # calculate factorial of each and sum
      ©         # save a copy in register
       ¯så#     # if the current number is in the global list, exit loop
           ®    # retrieve the value from the register for the next iteration
                # implicitly output the global list

Short and correct, well played !

Thought I could get rid of the s, was wrong, nice answer.

Brachylog, 17 bytes
g:I{tẹḟᵐ+}ᵃ⁾L¬≠Lk

Try it online!
Explanation
g:I{     }ᵃ⁾         Accumulate I (a variable) times, with [Input] as initial input:
    t                  Take the last integer
     ẹḟᵐ+              Compute the sum of the factorial of its digits
            L        The result of the accumulation is L
            L¬≠      Not all elements of L are different
               Lk    Output is L minus the last one (which is the start of the loop)

What does I mean?

@LeakyNun It's a parameter to ᵃ⁾. ᵃ³ means "accumulate 3 times". ᵃ⁾ means "accumulate as many times as the last element of the input", which in that case is I. Since I is a completely free variable, it will try values for it from 0 to +inf.

Wolfram Language, 62 60 56 bytes
Most@NestWhileList[Tr[IntegerDigits@#!]&,#,UnsameQ,All]&

It is really too bad that Wolfram Language has such abominably long function names. *Sigh*
Explanation:
Most[NestWhileList[Tr[IntegerDigits[#]!]&,#,UnsameQ,All]]&
                      IntegerDigits[#]                     (*Split input into list of digits*)
                                      !                    (*Factorial each element in the list*)
                   Tr[                 ]&                  (*Sum the list together*)
     NestWhileList[                      ,#,UnsameQ,All]   (*Iterate the function over itself, pushing each to a list, until a repeat is detected*)
Most[                                                   ]& (*Remove the last element in the list*)

Nice answer. I don't think this can be improved upon.

@KellyLowder Thanks! I was actually able to save two more bytes by mapping the factorial to the list, then summing it with Tr.

Nice use of NestWhileList[...,All]!

JavaScript (ES6), 91 89 bytes
Saved 2 bytes thanks to fəˈnɛtɪk
It turns out to be quite similar to the other JS answer.
f=(n,x=!(a=[n]))=>n?f(n/10|0,x+(F=n=>n?n--*F(n):1)(n%10)):~a.indexOf(x)?a:f(x,!a.push(x))

f=(n,x=!(a=[n]))=>n?f(n/10|0,x+(F=n=>n?n--*F(n):1)(n%10)):~a.indexOf(x)?a:f(x,!a.push(x))

console.log(f(132))

In your factorial function shouldn't you be able to use n instead of n>1 because 0!=1?

@fəˈnɛtɪk I don't know what I was thinking here. Thank you!

ClojureScript, 146 109 bytes
#(loop[n[%]](let[f(apply +(for[a(str(last n))](apply *(range 1(int a))))](if(some #{f}n)n(recur(conj n f)))))

Yikes, that is a monstrosity. Someone please help me golf this...
Thanks @cliffroot for shaving off a whopping 37 bytes!
This is an anonymous function, to run the function, you have to do this:
(#(...) {arguments})

TIO doesn't have ClojureScript, so here's a link to a ClojureScript REPL.
Here's a link to a Clojure program which prints the last element in the list from 0 to 1000.
Here's the output for 9999:
[9999 1451520 269 363602 1455 265 842 40346 775 10200 6 720 5043 151 122 5 120 4 24 26 722 5044 169 363601 1454]

I have a strong suspicion that all numbers must eventually settle at 1 or the loop [169 363601 1454].
Ungolfed code:
(defn fact-cycle [n]
  (loop [nums [n]]
    (let [fact-num
          (let [str-n (str (last nums))]
            (apply +
              (for [a (range (count str-n))]
                (apply *
                  (range 1
                    (inc (int (nth str-n a))))))))]
      (if (some #{fact-num} nums) nums
        (recur
          (conj nums fact-num))))))

Explanation coming soon!

Quite long but correct ;) I cannot really help you to golf this sorry ^^

the inner for can be
(for[a s](apply *(range 1(-(int a)47)))), can't it?

and this will allow to get rid of the other let
#(loop[n[%]](let[f(apply +(for[a(str(last n))](apply *(range 1(-(int a)47)))))](if(some #{f}n)n(recur(conj n f)))))

oh, seems you don't even need (- ... 47) in ClojureScript, just int will suffice

well,  (inc(int a)) should do for ClojureScript and (-(int a)47) for Clojure.

(1), (2), (169, 363601, 1454), (363601, 1454, 169), (1454, 169, 363601), (871, 45361), (145), (45361, 871), (45362, 872), (872, 45362), (40585) are all cycles for n <= 10000000, so there are more than just [1] and [169 363601 1454]

Perl 6, 64 bytes
{my@a;$_,{[+] .comb.map:{[*] 2..$_}}...^{$_∈@a||!@a.push: $_}}

Try it
Expanded:
{

  my @a;             # array of values already seen

  $_,                # seed sequence with the input

  {
    [+]              # reduce using &infix:<+>
      .comb          # the digits of $_ (implicit method call)
      .map:          # do the following for each
      {
        [*] 2..$_    # get the factorial of
      }
  }

  ...^               # keep generating values until
                     # (｢^｣ means throw away the last value when done)

  {
      $_ ∈ @a        # is it an elem of @a? (｢∈｣ is shorter than ｢(cont)｣)

    ||               # if it's not

      !              # boolean invert so this returns False
        @a.push: $_  # add the tested value to @a
  }
}

Every line above that has { starts a new bare block lambda with an implicit parameter of $_.
I used [*] 2..$_ instead of [*] 1..$_ purely as a micro optimization.

JavaScript, 92 bytes
Thanks @Shaggy for golfing off one byte with includes
Thanks @Neil for golfing off two bytes
Code separated into individual functions 92 bytes
f=(x,a=[])=>a.includes(x)?a:f(k(x),a,a.push(x))
p=y=>y?y*p(y-1):1
k=n=>n?p(n%10)+k(n/10|0):0

Code on one line 92 bytes
f=(x,a=[])=>a.includes(x)?a:f((k=n=>n?(p=y=>y?y*p(y-1):1)(n%10)+k(n/10|0):0)(x),a,a.push(x))

Explanation
Initially call the function with just a single argument, therefore a=[].
If x exists in the array a return a a.includes(x)?a:...
Otherwise, append x to a and pass the factorial digit sum and a to the function (a.push(x),f(k(x),a))
p=y=>y?y*p(y-1):1
k=n=>n?p(n%10)+k(n/10|0):0

Factorial Digit sum performed so that it will not exceed the maximum recursion limit.
List of all possible endpoints: 1, 2, 145, 169, 871, 872, 1454, 40585, 45361, 45362, 363601
Try it online!

Gah, I was so close! Save a byte with f=(x,a=[])=>a.includes(x)?a:(a.push(x),f(k(x),a))

Can you not write f(k(x),a,a.push(x))? Also, I think you can write k=n=>n&& to save another byte.

Haskell, 80 67 bytes
g#n|elem n g=g|h<-g++[n]=h#sum[product[1..read[d]]|d<-show n]
([]#)

Try it online! Usage: ([]#) 132
Edit: Saved 13 bytes with typs from Ørjan Johansen!

(1) Test and append n instead of s(same as in ovs's Python answer), then f=([]#). (2) Switch the branches, inline s, and use elem.

Switch out your ++ for : also.

@Canyon It's the wrong order around for that, it would give the final result reversed. You can almost fix it up afterwards, by prepending an extra n: and changing =g to =[], but it seems to be only a tie.

Pyth, 9 bytes
.us.!MjNT
.us.!MjNTQ  implicit Q

.u          explained below
       N      current value
      j T     convert to decimal (list of digits)
   .!M        factorial of each digit
  s           sum

Try it online!
This answer uses .u ("Cumulative fixed-point. Apply until a result that has occurred before is found. Return all intermediate results.")

Pyth, 30 bytes
W!hxYQQ=+YQKQ=Q0WK=+Q.!%KT=/KT

Try It Here

Pyth has more useful functions than one imagines. See my answer as reference.

R, 120 Bytes
o=scan()
repeat {
q=sum(factorial(as.double(el(strsplit(as.character(o[length(o)]), "")))))
if(q%in%o)break
o=c(o,q)
}
o

you can do o=scan(), use el() instead of [[1]], and gamma(n+1)=factorial(n) which I believe saves a byte, and I think as.numeric is the same as as.double for integers, which also saves a byte, and you can use toString instead of as.character.

@Giuseppe Thanks for the input, updated.

Java 9 JSHell, 213 bytes
n->{Set<Integer>s=new HashSet<>();
return IntStream.iterate(n,i->(""+i).chars()
.map(x->x<50?1:IntStream.rangeClosed(2,x-48)
.reduce(1,(a,b)->a*b)).sum()).boxed()
.takeWhile(x->s.add(x)).collect(Collectors.toList());}

Try it online!
Note: This solution relies on the string representation of a number having code points in the range 48-57. Works for ASCII, UTF-8, Latin-1, all ISO-8859-* character sets, most code pages. Does not work for EBCDIC. I don't think anyone will deduct points for that. :)
Ungolfed:
Function<Integer, List<Integer>> f =        // function from Integer to List of Integer
n -> {
    Set<Integer> s = new HashSet<>();       // memo of values we've seen
    return IntStream.iterate(n,             // iterate over n, f(n), f(f(n)), etc.
    i -> (""+i).chars()                     // the sumFac function; for all chars
        .map(x -> x < 50? 1 :               // give 1 for 0! or 1!
        IntStream.rangeClosed(2, x-48)      // else produce range 2..d
        .reduce(1,(a,b)->a*b))              // reduction to get the factorial
        .sum())                             // and sum up the factorii!

                                            // now we have a stream of ints
                                            // from applying sumFac repeatedly
        .boxed()                            // box them into Integers (thanks, Java)
        .takeWhile(x->s.add(x))             // and take them while not in the memo
        .collect(Collectors.toList());      // collect them into a list
}

Notes:

The return value of Set::add is very helpful here; returns true iff the item was not in the set
I was being sarcastic when I said "Thanks, Java"
factorii isn't really a word; I just made that up

I admit this is original ! Nice job :)

@Antoine I admit, Java isn't the best language to golf in, but it's hardly the craziest thing I've done lately. :) https://codegolf.stackexchange.com/a/117644/794

Pyth, 22 11 bytes
.usm.!sd+Nk

Try it online!
Lots of credit to Leaky Nun's answer, which introduced me to .u, and helped save a massive 11 bytes of this program.
Explanation:
.usm.!sd+NkQ | ending Q is implicitly added
             | Implicit: Q = eval(input())
.u         Q | Repeat the function with initial value Q until a previous value is found. Return all intermediate values
  s          | Summation
   m.!sd     | For each character 'd' in the string, convert to integer and take the factorial
        +Nk  | Convert function argument to string

Pyth has more useful functions than one imagines. See my answer as reference.

@LeakyNun I've rewritten my answer to use .u. I guess I'll need to take a look through the character reference again to see if there are any other useful functions there.

You can use \Nto convert to string instead of+Nk`.

@LeakyNun Where the N would be obsolete then, and there comes a 9-byte solution...

Python 3, 110 bytes
g=lambda x:x<1or x*g(x-1)
def f(n):
 a=[];b=n
 while b not in a:a+=[b];yield b;b=sum(g(int(x))for x in str(b))

Try it online!

Husk, 6 bytes
U¡oṁΠd

Try it online!

Axiom, 231 bytes
l(a:NNI):List NNI==(r:List NNI:=[];repeat(r:=cons(a rem 10,r);a:=a quo 10;a=0=>break);r)
g(a:NNI):NNI==reduce(+,[factorial(x) for x in l(a)])
h(a:NNI):List NNI==(r:=[a];repeat(a:=g(a);member?(a,r)=>break;r:=cons(a,r));reverse(r))

not golfed functions and some test
-- convert one NNI in its list of digits
listify(a:NNI):List NNI==
    r:List NNI:=[]
    repeat
        r:=cons(a rem 10,r)
        a:=     a quo 10
        a=0=>break
    r

-- g(1234)=1!+2!+3!+4!
SumfactorialDigits(a:NNI):NNI==reduce(+,[factorial(x) for x in listify(a)])

ListGenerateFromSumFactorialDigits(a:NNI):List NNI==
    r:=[a]
    repeat
       a:=SumfactorialDigits(a)
       member?(a,r)=>break
       r:=cons(a,r)
    reverse(r)

(9) -> h 132
   (9)
   [132, 9, 362880, 81369, 403927, 367953, 368772, 51128, 40444, 97, 367920,
    368649, 404670, 5810, 40442, 75, 5160, 842, 40346, 775, 10200, 6, 720,
    5043, 151, 122, 5, 120, 4, 24, 26, 722, 5044, 169, 363601, 1454]

C, 161 bytes
f(a){return a?a*f(a-1):1;}
a(l){return l?f(l%10)+a(l/10):0;}
c,t,o;r(i){for(t=o=i;t=a(t),o=a(a(o)),c=t^o;);for(t=i;t^c;printf("%d ",t),c=c|t^o?c:o,t=a(t),o=a(o));}

See it work online.

TI-BASIC, 85 79 64 60 bytes
:Prompt L₁                             //Get input as 1 length list, 4 bytes
:Lbl C                                //create marker for looping, see below, 3 bytes
:int(10fPart(Xseq(10^(~A-1),A,0,log(X //split input into list of digits, 20 bytes
:sum(Ans!→X                           //factorial and sum the list, write to new input, 6 bytes
:If prod(L₁-X                         //Test to see if new element is repeated, see below, 7 bytes
:Then                                 //Part of If statement, 2 bytes
:augment(L₁,{X→L₁                     //Push new input to List 1, 10 bytes
:Goto C                               //Loop back to beginning, 3 bytes
:Else                                 //Part of If statement, 2 bytes
:L₁                                   //Print Answer, 2 bytes

Since this is running on a graphing calculator, there is limited RAM. Try testing it with numbers that loop quickly, like 169.
More Explanation:
:int(10fPart(Xseq(10^(~A-1),A,0,log(X
              seq(10^(~A-1),A,0,log(X //Get a list of powers of 10 for each digit (i.e. 1, 0.1, 0.01, etc.)
             X                        //Multiply by input
       fPart(                         //Remove everything but the decimal
     10                               //Multiply by 10 (move one digit in front of the decimal
:int(                                 //Truncate to an integer

If prod(L₁-X works by subtracting the new element from the old list, then multiplying all the elements of the list together. If the element was already in the list, the product will be 0, a falsey value. Otherwise, the product will be a positive integer, a truthy value.

Java 7, 220 bytes
String c(int n){String r=n+",",c;for(;!r.matches("^"+(c=(n=d(n))+",")+".*|.*,"+c+".*");r+=c);return r;}int d(int n){int s=0;for(String i:(n+"").split(""))s+=f(new Long(i));return s;}long f(long x){return x<2?1:x*f(x-1);}

Explanation:
String c(int n){                            // Method with integer parameter and String return-type
  String r=n+",",                           //  Result-String (which starts with the input integer + a comma
         c;                                 //  Temp String
  for(;!r.matches(                          //  Loop as long as the result-String doesn't match the following regex:
    "^"+(c=(n=d(n))+",")+".*|.*,"+c+".*");  //    "^i,.*|.*,i,.*" where `i` is the current integer
                                            //   `n=d(n)` calculates the next integer in line
                                            //   `c=(n=d(n))+","` sets the temp String to this integer + a comma
    r+=c                                    //   And append the result-String with this temp String
  );                                        //  End of loop
  return r;                                 //  Return the result-String
}                                           // End of method

int d(int n){                               // Separate method (1) with integer parameter and integer return-type
  int s=0;                                  //  Sum
  for(String i:(n+"").split(""))            //  Loop over the digits of `n`
    s+=f(new Long(i));                      //   And add the factorial of these digits to the sum
                                            //  End of loop (implicit / single-line body)
  return s;                                 //  Return the sum
}                                           // End of separate method (1)

long f(long x){                             // Separate method (2) with long parameter and long return-type (calculates the factorial)
                                            // (NOTE: 2x `long` and the `new Long(i)` is shorter than 2x `int` and `new Integer(i)`, hence long instead of int)
  return x<2?                               //  If `x` is 1:
      1                                     //   return 1
    :                                       //  Else:
      x*f(x-1);                             //   return `x` multiplied by the recursive-call of `x-1`
}                                           // End of method (2)

Test code:
Try it here.
class M{
  String c(int n){String r=n+",",c;for(;!r.matches("^"+(c=(n=d(n))+",")+".*|.*,"+c+".*");r+=c);return r;}int d(int n){int s=0;for(String i:(n+"").split(""))s+=f(new Long(i));return s;}long f(long x){return x<2?1:x*f(x-1);}

  public static void main(String[] a){
    System.out.println(new M().c(132));
  }
}

Output:
132,9,362880,81369,403927,367953,368772,51128,40444,97,367920,368649,404670,5810,40442,75,5160,842,40346,775,10200,6,720,5043,151,122,5,120,4,24,26,722,5044,169,363601,1454,

GolfScript, 44 bytes
~]{..)\;10base{,1\{)*}/}%{+}*.@\+@@?)!}do);`

~                                             eval input
 ]                                            initialization
  {                                   }do     do...
   ..)\;                                          initialization
        10base                                    get digits
              {,1\{)*}/}%                         factorial each
                         {+}*                     sum
                             .@\+@@?)!        while result not found
                                         );   drop last element
                                           `  tostring

Try it online!
The factorial part is from here.

J, 40 31 bytes
Edit: 9 bytes saved using the improvements by FrownyFrog. Thanks!
f=.$:@,~`]@.e.~[:+/@:!10#.inv{:

Original code:

f=.[`($:@,)@.([:-.e.~)[:+/!@("."0&":@{:)

In this case I decided to count the bytes for the verb definition, since otherwise it doesn't work in the interpreter.
Explanation:

                         (        {:) - Takes the last element of the array
                               ":@    - converts it to string
                          "."0&       - converts each character back to integer
                       !@             - finds the factorials
                     +/               - sums them
                   [:                 - cap (there are 2 derived verbs above, we need 3 for a fork)
          (    e.~)                   - check if the result is present in the list
             -.                       - negates the above check
           [:                         - cap
        @.                            - Agenda conjunction, needed for the recursion
  ($:@,)                              - if the result is not in the list, add it to the list and recur
[`                                    - if the result is in the list, display it and stop

Try it online!

([:-.e.~) -> (1-e.~)

31 bytes

@FrownyFrog Thanks, your code is much better!
I tried 10#.inv early while experimenting, but then I wrote it 10&#.inv and it was longer, so I rejected it. Thanks for all your suggestions! I have much to learn :)

@FrownyFrog  Reversing the cases for the agenda is so good, I regret I didn't see it :)

[:+/!@"."0@":@{: is the same length, so there's no improvement with 10#.inv. Just had to drop the ().

Yes, I just saw it - its not ambiguous to require ()

Tcl, 143 bytes
proc P {n L\ ""} {proc F n {expr $n?($n)*\[F $n-1]:1}
while {[set n [expr [join [lmap d [split $n ""] {F $d}] +]]] ni $L} {lappend L $n}
set L}

Try it online!

APL (Dyalog Extended), 17 16 15 bytes
Saved 1 byte thanks to @Adám and another later
f←(#+.(!⍎)⍕)⌂traj

Try it online!
traj is a function in the dfns workspace that runs a function until a cycle is detected. Here, that function is #+.(!⍎)⍕. ⍕ turns the argument into a string. Each character/digit (¨) is executed/turned into a number (⍎). ! finds the factorial of each of these digits. Then + adds up all these factorials. # is used because #⍎foo just executes foo, so it's #f.⍎ is practically the same as {f/⍎¨⍵} here.
APL (Dyalog Unicode), 25 20 bytes
Saved 5 bytes thanks to @Adám!
1↓{⍵,⍨+/!⍎¨⍕⊃⍵}⍣(⊃∊)

Try it online!
Output is reversed.
This is very similar to the code above, but uses the power operator (⍣) to run the dfn until a cycle is reached, then drops the first element (1↓) because it runs 1 extra time. {⍵,⍨+/!⍎¨⍕⊃⍵} applies the function in the question to the first element of the argument (⊃⍵), then prepends it to the argument (⍵,⍨). Each time it is called, the list grows by one. The train ⊃∊ is applied with the next result on the left side and the previous result on the right side and tells ⍣ when to stop. ∊ is membership and tells which of the next result's elements are in the previous results (if one of them is repeated, there is a cycle). Then it picks the first of these booleans (⊃) because we need a single value and the rest have been checked already in previous iterations.

#.{+/!⍎¨⍕⍵}⌂traj saves a byte.

1↓{⍵,⍨+/!⍎¨⍕⊃⍵}⍣(⊃∊)

@Adám Sweet, thanks!

PowerShell Core, 87 bytes
param($r)for(;$r-notin$l){$l+=,$r
$r=("$r"|% t*y|%{1.."$_"-ne0-join'*'})-join'+'|iex}$l

Try it online!
Thanks to mazzy for saving a lot of bytes!
Explained (old implementation, but close enough)
param($r)for(;$r-notin$l                       # Checks that the last computed value isn't an existing one
                        ){$l+=,$r              # Adds it to the list

$r=("$r"|                                      # Converts r as a string
      % t*y|                                   # Converts it to a char array
      %{1.."$_"-ne0-join'*'}                   # Builds the factorial calculation strings and handles 0!. e.g. 1*2*3*4
   )-join'+'|iex}                              # Joins them with "+" and computes it. e.g. 1*2*3*4+1*2*3

$l                                             # Returns all the values in the list

Thanks. I think you can save some bytes if you use an array instead of hashtable

I tried but arrays have fixed size and I couldn't find any short way of instantiating one.
i.e. [System.Collections.ArrayList]::New()

Another 117 bytes option that raises a lot of error but returns a correct result

Try it online! 【ツ】

Perl 5 -MList::Util=product,sum -n, 49 bytes
say&&($_=sum map{product 1..$_}/./g)until$k{$_}++

Try it online!

You can save 2 bytes by changing && to ,, ) to a space, and by removing (. Try it online!

Wolfram Language (Mathematica), 72 bytes
Most@NestWhileList[Total[IntegerDigits@#!]&,#,DuplicateFreeQ@*List,All]&

Try it online!
Keeps applying sumFac to it's own output until it sees a duplicate value, then returns a list of all values excluding that final duplicate.

Stax, 10 bytes
│¼µ\Ä▬Éε╩X

Run and debug it

Perl 5 -n, 65 bytes
say,(map{$f=1;map{$f*=$_}2..$_;$.+=$f}/./g),$_=$.until$.=$r{$_}++

Try it online!
Uses map as regular loops (ignoring return value), and $. as a temporary variable (to save space before until).

Note that, under current rules, command line flags count as separate languages, rather than extra bytes, so the correct header for this answer is "Perl 5 -n, 65 bytes"

@pppery, ok changed


text:
Find the number of subgroups of a finite group
Definitions
You can skip this part if you already know the definitions of groups, finite groups, and subgroups.
Groups
In abstract algebra, a group is a tuple (G, ∗), where G is a set and ∗ is a function G × G → G such that the following holds:

Closure: for all x, y in G, x ∗ y is also in G (implied by the fact that ∗ is a function G × G → G).
Associativity: for all x, y, z in G, (x ∗ y) ∗ z = x ∗ (y ∗ z).
Identity: there exists an element e in G such that for all x in G, x ∗ e = x = e ∗ x.
Inverse: for each x in G, there exists an element y in G such that x ∗ y = e = y ∗ x, where e is the identity element mentioned in the previous bullet point.

Finite groups
A finite group is a group (G, ∗) where G is finite, i.e. has finitely many elements.
Subgroups
A subgroup (H, ∗) of a group (G, ∗) is such that H is a subset of G (not necessarily proper subset) and (H, ∗) is also a group (i.e. satisfies the 4 criteria above).
Examples
Consider the dihedral group D3 (G, ∗) where G = {1, A, B, C, D, E} and ∗ is defined below (a table like this is called a Cayley table):

∗ | 1   A   B   C   D   E
--+----------------------
1 | 1   A   B   C   D   E
A | A   B   1   D   E   C
B | B   1   A   E   C   D
C | C   E   D   1   B   A
D | D   C   E   A   1   B
E | E   D   C   B   A   1

In this group, the identity is 1. Also, A and B are inverses of each other, while 1, C, D, and E are the inverses of themselves respectively (the inverse of 1 is 1, the inverse of C is C, the inverse of D is D, and the inverse of E is E).
Now, we can verify that (H, ∗) where H = {1, A, B} is a subgroup of (G, ∗). For the closure, refer to the table below:

∗ | 1   A   B
--+----------
1 | 1   A   B
A | A   B   1
B | B   1   A

where all possible pairs of elements in H under ∗ give a member in H.
The associativity does not require checking, since elements of H are elements of G.
The identity is 1. This must be the same with the group identity. Also, the identity in a group must be unique. (Can you prove this?)
For the inverse, check that the inverse of A is B, which is a member of H. The inverse of B is A, which is also a member of H. The inverse of 1 is still itself, which does not require checking.

Task
Description
Given a finite group (G, ∗), find the number of its subgroups.
Input
For a group (G, ∗), you will receive a 2D array of size n × n, where n is the number of elements in G. Assume that index 0 is the identity element. The 2D array will represent the multiplication table. For example, for the group above, you will receive the following 2D array:
[[0, 1, 2, 3, 4, 5],
[1, 2, 0, 4, 5, 3],
[2, 0, 1, 5, 3, 4],
[3, 5, 4, 0, 2, 1],
[4, 3, 5, 1, 0, 2],
[5, 4, 3, 2, 1, 0]]

For example, you can see that 3 ∗ 1 = 5 because a[3][1] = 5, where a is the 2D array above.
Notes:

You can used 1-indexed 2D array.
The row and the column for the identity can be omitted.
You may use other formats as you see fit, but it must be consistent. (i.e. you may want the last index to be identity instead, etc.)

Output
A positive number representing the number of subgroups in the group.
For example, for the group above, (H, ∗) is a subgroup of (G, ∗) whenever H =

{1}
{1, A, B}
{1, C}
{1, D}
{1, E}
{1, A, B, C, D, E}

Therefore, there are 6 subgroups, and your output for this example should be 6.

Hints
You can read the articles that I linked to. Those articles contain theorems about groups and subgroups that might be useful to you.

Scoring
This is code-golf. Answer with lowest byte-count wins.

Oh it wasn't clear to me the e specifically refers to the identity element, not just any intermediate result.

@orlp clarified.

If you're going to call 0 the identity element, then it's confusing to have the operator described as multiplication...

@Neil eh... when conventions clash.

@Downvoter: how can I improve my question?

Can we take the identity as 1?

@Dennis I was assuming that the identity element could be any element. Maybe we need more test cases.

@mbomb007 Hm, yes, the worked example uses 1.

But it also shows it as 0 when it shows the 2D list input. I'd also like to know if the identity element will always be the first item in the first row of the Cayley table.

I assumed the elements in the 2D list were identical to the indices of their rows/columns, otherwise how would you even identify which row/column goes with which?

@Dennis I just assumed it is 0 out of convenience. Doesn't make much sense if the second element is the identity. You can still use it though. I've edited the question.

@mbomb007 I've edited the question.

Mathematica, 62 48 bytes
Count[Subsets@First@#,x_/;Union@@#[[x,x]]==x]-1&

Pure function expecting a 1-indexed 2D array. Counts the number of Subsets of the First row of the input array that are  closed under the group operation. Since this will include the empty set, we subtract 1. Note that a nonempty subset of a finite group that is closed under the group operation is in fact a subgroup, (and vice versa, by definition).
Strictly speaking I don't check that the subset x is closed under the group operation, I restrict the multiplication table to the subset x and check that it contains precisely the elements of x. Clearly this implies that x is closed with respect to the group operation. Conversely, any subgroup x will contain 1 and thus x will be a subset of the elements appearing in the restricted multiplication table, and since x is closed under the group operation, it must equal x.

Haskell, 79 bytes
Basically a port of ngenisis's Mathematica method. (Except I'm using 0-indexed arrays.)
c takes a list of lists of Ints and returns an integer.
c g=sum[1|l<-foldr(\r->([id,(r!!0:)]<*>))[[]]g,and[g!!x!!y`elem`l|x<-l,y<-l]]-1

Try it online!
It is assumed that the Ints are numbered the same as the rows (outer lists) and columns showing their multiplication. Thus, since 0 is the identity, the first column is the same as the indices of the rows. This allows using the entries of the first column to construct the subsets.
How it works

c is the main function.
g is the group array as a list of lists.
l is a subset of the elements. The list of subsets is constructed as follows:

foldr(\r->([id,(r!!0:)]<*>))[[]]g folds a function over the rows of g.
r is a row of g, whose first (0th) element is extracted as an element that may be included ((r!!0:)) or not (id).
<*> combines the choices for this row with the following ones.

and[g!!x!!y`elem`l|x<-l,y<-l] tests for each pair of elements in l whether their multiple is in l.
sum[1|...]-1 counts the subsets that pass the test, except for one, the empty subset.

Python 2, 297 215 bytes
from itertools import*
T=input()
G=T[0]
print sum(all(T[y][x]in g for x,y in product(g,g))*all(any(T[y][x]==G[0]==T[x][y]for y in g)for x in g)*(G[0]in g)for g in chain(*[combinations(G,n)for n in range(len(G)+1)]))

Try it online
This program works for the example group without ==T[x][y], but I'm still pretty sure it's necessary.
Edit: Now assumes that the identity element of G is always the first.

Ungolfed:
from itertools import*
T=input()
G=T[0]
def f(x,y):return T[y][x]                                           # function
def C(g):return all(f(x,y)in g for x,y in product(g,g))             # closure
def E(g):return[all(f(x,y)==y for y in g)for x in g]                # identity

a=E(G)
e=any(a)
e=G[a.index(1)]if e else-1                                          # e in G

def I(G):return all(any(f(x,y)==e==f(y,x)for y in G)for x in G)     # inverse

#print e
#print C(G),any(E(G)),I(G)

#for g in chain(*[combinations(G,n)for n in range(len(G)+1)]):      # print all subgroups
#   if C(g)and I(g)and e in g:print g

print sum(C(g)*I(g)*(e in g)for g in chain(*[combinations(G,n)for n in range(len(G)+1)]))

Ungolfed TIO
Negative group elements can be supported at no cost by changing -1 to ''.

Why do you check for identity? The identity is guaranteed to be the first element. Just make all combinations without the first element and add the first element to each combination.

"Assume that 0 is the identity element."

Yeah, but that doesn't mean it's first in the list. I thought it was talking about the number 0 for the example, not the index.

@mbomb007 it's clearly the index

Jelly, 17 16 bytes
1 byte thanks to ETHproductions (LR → J)
ị³Z⁸ịFḟ
JŒPÇÐḟL’

JŒPÇÐḟL’  main link. one argument (2D array)
J         [1,2,3,...,length of argument]
 ŒP       power set of ^
    Ðḟ    throw away elements that pass the test...
   Ç      in the helper link
      L   length (number of elements that do not pass)
       ’  decrement (the empty set is still closed under
          multiplication, but it is not a subgroup, as
          the identity element does not exist.)

ị³Z⁸ịFḟ   helper link. one argument (1D indexing array)
ị³        elements at required indices of program input (2D array)
  Z       transpose
   ⁸ị     elements at required indices of ^
     F    flatten
      ḟ   remove elements of ^ that are in the argument given
          if the set is closed under multiplication, this will
          result in an empty set, which is considered falsey.

Try it online! (1-indexed)

You can do J instead of LR to save a byte :-)

@ETHproductions wow, thanks for spotting that.

source: Stack Exchange

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

sort: votes


text:
Golf this AP CS Java FRQ - Duplicate Sums of Arrays in 2D Array
In preparation for the AP Computer Science AP Test (Java), our teacher has been giving us FRQs from previous years for practice.
My friend and I were golfing this during class today and got it as short as we could, but I'd like to see if there are any shorter solutions any of you can come up with.
Rules:

You must use the predefined method headers, method names, and parameter names.
You do not have to specify imports.
All code is to be written in Java.
No external libraries

Information:
Part A
Given an array of type int, write a method that returns the sum of the elements of the array.
public int arraySum(int[] arr)
{
    /*Implementation to be written in part A*/
}

Now, write the implementation for the method arraySum.
Part B
Given a 2D array of type int, write a method that returns a 1-dimensional int array containing the sums of each row of the given 2-dimensional array. You must use arraySum but may assume it works properly regardless of what you put for part A.
public int[] array2dSum(int[] arr2d)
{
    /*Implementation to be written in part B*/
}

Now, write the impmenetation for the method array2dSum.
Part C
Given a 2D array of type int, write a method that returns whether or not the sums of the rows of the array are diverse, meaning the array contains no duplicate sums. You must use array2dSum but may assume it works properly regardless of what you put for part A.
public boolean isDiverse(int[] arr2d)
{
    /*Implementation to be written in part C*/
}

Now, Write the implementation for the method isDiverse.

Here's what I have:
A - 31 chars
return IntStream.of(arr).sum();

B - 59 chars
return Stream.of(arr2d).mapToInt(x->arraySum(x)).toArray();

C - 86 chars
int[]h=array2dSum(arr2d);return IntStream.of(h).distinct().toArray().length==h.length;

Test Inputs:
arraySum(new int[] {1, 2, 3}) returns 6
array2dSum(new int[][] {{1,2},{3,4}}) returns {3,7}
isDiverse(new int[][] {{1,2,3},{4,5,6},{7,8,9}}) returns true
isDiverse(new int[][] {{1,2,3},{4,5,6},{1,2,3},{7,8,9}}) returns false

Welcome to the site but in my humble opinion this is too specific. Asking for answers in one language particularly Java which is not particularly golfable (again in my humble opinion) will not get a great response. Maybe try to make the question a bit more open?

Shouldn't your test case for array2dSum() return {3,7} ?

@ElPedro Questions like this are on-topic. The goal is essentially tips, not a challenge.

@mbomb007 - thanks for the clarification but that is not how I understood it. "Tips for golfing in XXXX language" I understand are on topic but not specific questions that specify a language. Apologies if I have misunderstood.

He already listed his shortest solutions, so it's essentially a tips question. Asking for tips for a specific golf is acceptable, though chat may be a better place to ask. He does not yet have enough rep to post a chat message, though.

Point taken. Not my kind of question and it wasn't me that downvoted so I guess I'll leave it at that. Thanks again for the clarification.

This question is also a golf-course.  Which are disallowed in most cases.  This particular question seems like a golf course with little interaction and should probably be closed.

I'm voting to close this question as off-topic because this question is a golf-course with little interaction

@WheatWizard - I wasn't aware of golf-course but it pretty well sums up what I was thinking.

@WheatWizard I understand about golf courses but I didn't want to post a separate question for each part since I thought that would be spam and obnoxious. I also included my shortest solutions so people wouldn't think I was simply asking for someone to do a homework problem or something.

@WheatWizard also if it wasn't clear I'm not doing it like a golf course where you have to do all 3 parts for an answer, I just wanted to see if anybody could get this any shorter in any of the parts at all

@Targz - myself I wasn't meaning to be in any way insulting. It's just that questions here usually leave things open to Python/JavaScript/AnyOtherLanguages programmers to also submit an answer unless they are questions asking for tips in a specific language but not usually with a specific question/challenge. Perhaps if you posted this in the sandbox we could help improve the question. Maybe then you would get your Java answer and maybe some interesting answers in Ruby or Perl or other languages.

"Given a 2D array of type int" I would expect to see int[][] in the signature.

@PeterTaylor I just copied the wording of the original problem

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


text:
Seventy Seven Sevens
Given a number n and an upper limit l list the numbers that can be created by multiplying two or more numbers consisting of only sevens of length n or less that are less than l. A161145 is close to this challenge, however, you will NOT be including the 7, 77, 777, 7777, 77777, etc..
Examples
n=anything, l<49 would result in:
[]

n=1, l=49 would result in:
7*7=49

f(1,49)=[49]

n=1, l=343 would result in:
7*7   =49
7*7*7 =343

f(1,343)=[49,343]

n=2,l=6000 would result in:
7*7    =49
7*7*7  =343
7*7*7*7=2401
7*77   =539
7*7*77 =3773
77*77  =5929

f(2,6000)=[49,343,539,2401,3773,5929]

n=3, l=604000 would result in:
[49, 343, 539, 2401, 3773, 5439, 5929, 16807, 26411, 38073, 41503, 59829, 117649, 184877, 266511, 290521, 418803, 456533, 603729]

Etc...
Rules

You do not have to output intermediate steps, this was done for clarity.
Output can be as an array or separated by any character (even newlines).
Output must be in numerical order, lowest to highest.
To make the title relevant, highest n that must be handled is n=77 (if you can't handle that high, note why - language restrictions are acceptable, laziness is not). This limitation is to hinder those looking to build the entire superset in memory.
If TIO cannot run n=77 for your code, explain what specs were required to achieve n=77.
For a product to be valid it must consist of at least 2 numbers.
This is code-golf lowest byte-count will be deemed victorious.
You may choose the list to contain items less than l or less than/equal to l.
BONUS: If your code is exactly 77 bytes, kudos from me; worthless, I know.

I'm having trouble parsing "list the numbers that can be created by multiplying two or more numbers consisting of only sevens of length n or less that are less than l"

Is it acceptable to have some numbers output more than once?

Rule 5 is pretty pointless, will any code run given n=77 and l=7**7**7, for example?

Can we assume that the result will not be empty?

@JonathanAllan true.

05AB1E, 19 bytes
L7×1¸ì©IF®âPD²‹Ïê®K

Try it online!
Explanation
Very inefficient. TIO link performs ceil(l^(1/7)) iterations instead of the l iterations used in the golfed version to easier test large testcases.
L7×                   # create the list ['7', '77', '777' ...]
                      # with the final item having n 7's
   1¸ì©               # prepend a 1 and store a copy in register
       IF             # l times do:
         ®â           # cartesian product between current list and the list in register
           P          # product of each sublist
            D²‹Ï      # keep only numbers smaller than l
                ê     # remove duplicates and sort
                 ®K   # remove 1, 7, 77, 777 ... from the list

$L7×‚˜ - tried to get 5 bytes, couldn't.

@carusocomputing: Yeah, I feel like 6 bytes is too much, but I really can't see a shorter way. I was hoping you'd school me with a shorter way ;)

I was thinking .p or .s too, but even those seem longer. I accidentally hit 'refresh' on the TIO page with my example implementation instead of run, deleted it from existence. I think it was 26 though.

@carusocomputing: That's why you should always press the link button regularly. Don't loose anything by refreshing or rebooting the computer. A bit annoying to loose history though :)

Jelly, 21 20 19 18 bytes
R7ẋḌµ;ŒċP€⁹f€FµÐLḟ

Note that the output doesn't match the OP's. I've left a comment.
Try it online!
How it works
R7ẋḌµ;ŒċP€⁹f€FµÐLḟ  Main link. Left argument: n. Right argument: l

R                   Range; yield [1, ..., n].
 7ẋ                 Times; yield [[7], ..., [7] * n].
   Ḍ                Undecimal; yield s := [7, 77, ...].
    µ         µÐL   Begin a new chain with argument s and call the chain between
                    until the results no longer chain.
                    Return the last unique result.
      Œċ            Combinations; return all unordered pairs in integers in the
                    return value.
     ;              Concatenate the return value and its pairs.
        P€          Take the product of each individual integer and each pair in
                    the result.
          ⁹f€       Filter each; for each j in [1, ..., l], intersect [j] with the
                    array of products. The result is sorted and contains no
                    duplicates.
                 ḟ  Filterfalse; remove the elements of s from the result.

Python 2, 116 113 109 bytes
n,l=input()
r=t={1}
exec't|={10**n/9*7};n-=n>1;r=r|{x*y for x in r for y in t if l/x/y};'*l
print sorted(r-t)

Note that TIO doesn't have enough memory for the last test case.
Try it online!

JavaScript (ES6), 103 101 bytes
Takes input in currying syntax (n)(l).
n=>l=>(a=[],g=(n,m,p,i)=>(p>l||g(n,m,(a[i>1?p:a]=p)*m,-~i),--n?g(n,m+7,p,i):a.filter(n=>n)))(n,'7',1)

Test cases
The last test case may take a few seconds to complete.

let f =

n=>l=>(a=[],g=(n,m,p,i)=>(p>l||g(n,m,(a[i>1?p:a]=p)*m,-~i),--n?g(n,m+7,p,i):a.filter(n=>n)))(n,'7',1)

console.log(f(1)(49))
console.log(f(1)(343))
console.log(f(2)(6000))
console.log(f(3)(604000))

Ruby, 89 86 bytes
A recursive solution.
-3 bytes by remembering that anything times 0 is 0.
f=->n,l,b=1{n*l>0?(f[n,l/k=eval(?7*n),b*k]+f[n-1,l,b]+(b>1&&l>=k ?[k*b]:[])).sort: []}

Try it online!

PHP, 142 Bytes
$r=[];for([,$n,$l]=$argv;$n--;)f($v[]=$z.=7);function f($t){global$v,$l,$r;while($c=$t*$v[+$i++])$l<$c?:f($c)&$r[$c]=$c;}sort($r);print_r($r);

-5 Bytes removing $r=[]; and replace sort($r); with @sort($r);
Online Version
Expanded
A recursive function make all permutations including the limit
$r=[];
for([,$n,$l]=$argv;$n--;)
  f($v[]=$z.=7);
function f($t){
    global$v,$l,$r;
    while($c=$t*$v[+$i++])
      $l<$c?:f($c)&$r[$c]=$c;
}
sort($r);
print_r($r);

PHP, 145 Bytes
for([,$n,$l]=$argv;$n;)$t[]=str_pad(7,$n--,7);for(;$l>=$i+=49;$v>1?:$u[]=$r)for($v=$i,$r=!$c=0;$d=$t[$c];)$v%$d?$c++:($v/=$d)&$r*=$d;print_r($u);

Expanded
a loop till including the limit
check every value that is divisible by 49
for([,$n,$l]=$argv;$n;)
  $t[]=str_pad(7,$n--,7);
for(;$l>=$v=$i+=49;$v>1?:$u[]=$r)
  for($r=!$c=0;$d=$t[$c];)
    $v%$d?$c++:($v/=$d)&$r*=$d;
print_r($u);

Online Version
a few bytes more and an associative array can be created
key the number and as value an array of the used sevens
for([,$n,$l]=$argv;$n;)
  $t[]=str_pad(7,$n--,7);
for(;$l>=$v=$i+=49;$v>1?:$u[array_product($r)]=$r)
  for($r=[],$c=0;$d=$t[$c];)
    $v%$d?$c++:($v/=$d)&$r[]=$d;
print_r($u);

Online Version

while($c=$t*$v[+$i++])$l<$c?f($c)&$r[$c]=$c; saves 3 bytes; but it should be $l<=$c. $r?sort($r)&print_r($r):0; instead of $r=[]; saves one.

$z.=7; is 5 bytes shorter than $z=$z*10+7;.

and @ is another 4 bytes shorter than $r?...:0;. (Thanks @Christoph)

@Titus Why should it be $l<=$c ? It seems yesterday was not my day for the $z.=7 and the additional 2 Bytes that  I have found. I am thinking first over your other two suggestions.  You miss the : in the while loop

I´ve asked the OP to clarify. In the description he talks about results that are less than l, in his examples they are less than or equal. Depending on the clarification, $c>$l||.../$c>$l?:... or $c<$l&&... are shortest.

@Titus you may choose either, as people have already done so both ways. This is valid.

Jörg this would be 137 if You actually removed the $r=[];. ;-) f($v[]=...) is a great find! And it´d be nice to put the function definition in front.

@Titus I know that is can be 137 if I remove the $r=[] but I will not work with @ And your version is shorter and I could not reach your byte count. I am happy that I found a solution without using a function. Why is f($v[]=...) a great find? And If it is you should add it to the tips for PHP

Yours is a lot faster. Mine takes 1.7 seconds to complete the last example while yours does it in 1/8 ms. I know, that´s not the objective in codegolf; but it´s well worth to mention.

@Titus Now I see what you mean and I have also tested my second approach. Normally I prefer Performance and avoid all Error reports but it is codegolf

PHP, 128 125 130 129 127 123 bytes
will work up to 22 7s but will round larger values (7**23 is floating point on a 64 bit machine).
3 bytes saved by Jörg, 3 by me, 5 4 1 added to avoid warning for empty results.
for([,$c,$z]=$argv,$n=$c+1;$c<$z;$p<$z&&$r[$p]=$p)for($b=$c+=$p=1;$b|0;$b/=$n)$p*=str_pad(7,$b%$n,7);@sort($r);print_r($r);

takes input from command line arguments; run with -nr or try it online.
breakdown
for([,$c,$z]=$argv,$n=$c+1;         # $z=L, $n=N+1
    $c<$z;                          # loop $c from N to L-1:
    $p<$z&&$r[$p]=$p                    # 2. if product is < L, add to array
)                                       #    (key=val to avoid duplicates)
    for($b=$c+=$p=1;$b|0;$b/=$n)        # 1. loop $b through ++$c as base-N+1 number
        $p*=str_pad(7,$b%$n,7);             # take each base-N+1 digit as length
                                            # for a streak of 7s as factor
        // (str_pad is 1 byte shorter than str_repeat and saves 3 by ensuring positive $p)
@sort($r);                          # sort array (muted to avoid warning for empty result)
print_r($r);                        # print array

for([,$c,$z]=$argv,$n=1+$c;$c<$z; instead of for($n=1+$c=$argv[1];$c<$z=$argv[2];

Use @ instead of $r&& to suppress the warning? $p<$z&&$r[$p]=$p

I just noticed it should be $p>$z?:$r[$p]=$p from example n=1, l=343 it is clear that l should be included. Therefore no savings there when using $p>$z||$r[$p]=$p or $p>$z?:$r[$p]=$p.

@Christoph I asked the OP to clarify. Thanks for reminding me of @; will edit when the OP replies.

@Christoph both seem to be ok; and it doesn´t really matter wether $p>$z|| or $p<$z&&. I´ll stick with the description.

Pyth, 22 bytes
JsM._*\7Eu@s*LR+JGJSQJ

JsM._*\7E
        E               second input
     *\7                repeat "7" as many times as the above
   ._                   all prefixes of above
 sM                     convert each to integer
J                       store list as J

         u@s*LR+JGJSQJ
         u              repeat the following until results not unique
                     J  starting from G = J
                        at each iteration, G is the current value
               +JG      append G to J
                  J     J
            *LR         multiply the elements of the above two, vectorizing each
           s            flatten list
          @        SQ   intersect with [1,2,3,...,first input]
                        this takes elements from [1,2,3,...,first input] and
                        check if each element is in the previous list
                        which ensures the result is sorted and unique

Try it online!
Specs

Input: l[newline]n
Output: array containing the sorted result

Brachylog, 28 bytes
h>.ḋ{p~c×ᵐ{=h7&l}ᵐobt≤~t?∧!}

There's a lot of scope for improvement in the language itself, here; quite a few things I wrote look like they'd be obviously improvable with some changes to the language's design. This is the shortest way I've found with the current version. I may well make some suggestions for Brachylog which would make this program more efficient, shorter, and more readable.
Very, very slow; TIO times out even on the simplest possible nontrivial answer, so there's not much point in providing a TIO link. I've verified this program by running it locally.
This is a function (not a full program), whose output is a generator (as opposed to a list). Add .w⊥ to the end of the function if you want to see all outputs, rather than just the first. (Note that this doesn't really matter in practice, because as the program is too slow for TIO anyway, you have to run it locally, and the local Brachylog interpreter runs in a REPL which can describe a generator just fine.)
Explanation
h>.ḋ{p~c×ᵐ{=h7&l}ᵐobt≤~t?∧!}
  .                           The desired output is
h>                            a number less than the first input
   ḋ p                        such that taking its prime factors in some order,
      ~c                      partitioning them,
        ×ᵐ                    and taking the product of each partition
          {     }ᵐ            produces a number for which each digit
           =h7                is composed only of 7s
              &l              and for which the lengths of those numbers
                  o           are in sorted order
                    t         and the last element
                   b          (which is not also the first element)
                     ≤        is less than or equal to
                      ~t?     the last input.
                         ∧    (Delete an unwanted implicit constraint.)
   ḋ{                     !}  Output each number only once.

Bash + GNU utilities, 108
seq -f3o%gp $2|dc|sed -r "/0|1{$1}/d;s/./&7/g;s/1//g;s/2/*/g;/[*]/!d;s/^/a=7/;s/$/;if(a<=$2)a;/"|bc|sort -un

Try it online.  TIO takes about a minute for the last testcase.  My results match @Dennis's.

Pyth --  57 51 49 42 bytes
FY}2eQKYJv*\7hQWJIqYJBW!%KJ=/KJ)=/JT)Iq1KY

Try it

Welcome to PPCG! There are many shortcuts available, which can cut down your code by a lot of bytes. You can come to our chatroom and ping me if you want to know more.

Unfortunately, your current program does not generate the correct results, namely that it includes 7 and 77 for your current input.

Ways to cut down bytes include: using m instead of F or V etc. (functional programming vs. execution control); using hQ instead of @Q0; using eQ instead of @Q1; using i*hQ]7T instead of the long for-loop to generate 777...7.

@LeakyNun Thanks much for the suggestions and the chatroom link.  Also, I fixed it.

JavaScript (Node.js), 94 91 88 bytes
n=>l=>(X=[]).filter(g=(i,j=1,k)=>j>l|i[n]||(X[g(i+7,j,k)|g(i,j*i,-~k),k>1&&j]=j),l=g`7`)

Try it online!
n=>l=>         // input
(X=[]).filter( // X stores index=results
g=(i,j=1,k)=>  // recurse             Reuse of g for filter:
j>l|i[n]||     // out of range        49>1|49[n] (true)
(X[g(i+7,j,k)|g(i,j*i,-~k),k>1&&j]=j)
               // k<=1: X[false]=j, ignored
               // k>1: X[j]=j
,l=g`7`)       // First call [0/1]|[0/1]||1 ==1

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


text:
Find a set of maximal matching edges
Consider a connected undirected graph. A matching set of edges on this graph is defined as a set of edges such that no two edges in the set share a common vertex. For example, the left figure denotes a matching set in green, while the right figure denotes a non-matching set in red.

A matching set is said to be maximally matching, or a maximal matching if it is impossible to add another edge of the graph to the matching set. So both examples above are not maximal matching sets, but both of the sets below in blue are maximal matchings. Note that maximal matchings are not necessarily unique. Furthermore, there's not requirement that the size of each possible maximal matching for a graph is equal to another matching.
The goal of this challenge is to write a program/function to find a maximal matching of a graph.
Input
Assume all vertices of the input graph have some consecutive integer numbering starting at any beginning integer value of your choice. An edge is described by an unordered pair of integers denoting the vertices the edge connects. For example, the graph shown above could be described with the following unordered set of edges (assuming the numbering of vertices starts at 0):
[(0,1), (0,2), (1,3), (1,4), (2,3), (3,4), (3,5), (5,6)]

An alternative way to describe a graph is via an adjacency list. Here is an example adjacency list for the above graph:
[0:(1,2), 1:(0,3,4), 2:(0,3), 3:(1,2,4,5), 4:(1,3), 5:(3,6), 6:(5)]

Your program/function must take as input a graph from any source (stdio, function parameter, etc.). You may use any notation desired so long as the no additional non-trivial information is communicated to your program. For example, having an extra parameter denoting the number of input edges is perfectly acceptable. Similarly, passing in an unordered multiset of edges, adjacency list, or adjacency matrix is fine.
You may assume:

The graph is connected (e.g. it is possible to reach any vertex given any starting vertex).
There is at least one edge.
An edge never connects a vertex directly to itself (ex. the edge (1,1) will not be given as input). Note that cycles are still possible (ex.: the above graphs).
You may require that the input vertices start at any index (e.g. the first vertex can be 0, 1, -1, etc.).
Vertex numbering is sequentially increasing from your chosen starting index (ex.: 1,2,3,4,..., or 0,1,2,3,...).

Output
Your program/function should output a list of edges denoting a maximal matching set. An edge is defined by the two vertices which that edge connects. Ex. output for the left blue set (using the example input vertex ordering):
[(1,4), (2,3), (5,6)]

Note that the order of the vertices are not important; So the following output describes the same matching set:
[(4,1), (2,3), (6,5)]

Output may be to stdout, a file, function return value, etc.
Examples
Here are a few example inputs (using the adjacency list format). These examples happen to start counting vertices at 0.
Note that no example outputs are given, instead I've included a Python 3 validation code.
[0:(1), 1:(0)]

[0:(1,2), 1:(0,3,4), 2:(0,3), 3:(1,2,4,5), 4:(1,3), 5:(3,6), 6:(5)]

[0:(1,2), 1:(0,2,3,4,5), 2:(0,1), 3:(1), 4:(1), 5:(1)]

[0:(1,2), 1:(0,2,3), 2:(0,1,4), 3:(1,4,5), 4:(2,3), 5:(3)]

Validation Python 3 code
Here's a Python 3 validation code which takes in a graph and set of edges and prints out whether that set is maximally matching or not. This code works with any vertex start index.
def is_maximal_matching(graph, edges):
    '''
    Determines if the given set of edges is a maximal matching of graph
    @param graph a graph specified in adjacency list format
    @param edges a list of edges specified as vertex pairs

    @return True if edges describes a maximal matching, False otherwise.
    Prints out some diagnostic text for why edges is not a maximal matching
    '''

    graph_vtxs = {k for k,v in graph.items()}
    vtxs = {k for k,v in graph.items()}

    # check that all vertices are valid and not used multiple times
    for e in edges:
        if(e[0] in graph_vtxs):
            if(e[0] in vtxs):
                vtxs.remove(e[0])
            else:
                print('edge (%d,%d): vertex %d is used by another edge'%(e[0],e[1],e[0]))
                return False
        else:
            print('edge (%d,%d): vertex %d is not in the graph'%(e[0],e[1],e[0]))
            return False
        if(e[1] in graph_vtxs):
            if(e[1] in vtxs):
                vtxs.remove(e[1])
            else:
                print('edge (%d,%d): vertex %d is used by another edge'%(e[0],e[1],e[1]))
                return False
        else:
            print('edge (%d,%d): vertex %d is not in the graph'%(e[0],e[1],e[0]))
            return False
        if(e[1] not in graph[e[0]]):
            print('edge (%d,%d): edge not in graph'%(e[0],e[1]))
            return False

    # check that any edges can't be added
    for v in vtxs:
        ovtxs = graph[v]
        for ov in ovtxs:
            if(ov in vtxs):
                print('could add edge (%d,%d) to maximal set'%(v,ov))
                return False

    return True

Example usage:
graph = {0:[1,2], 1:[0,3,4], 2:[0,3], 3:[1,2,4,5], 4:[1,3], 5:[3,6], 6:[5]}
candidate = [(0,1),(2,3)]
is_maximal_matching(graph, candidate) // False
candidate = [(0,1),(2,3),(5,6),(0,1)]
is_maximal_matching(graph, candidate) // False
candidate = [(0,1),(2,3),(5,6)]
is_maximal_matching(graph, candidate) // True

Scoring
This is code golf; shortest code wins. Standard loopholes apply. You may use any built-ins desired.

CJam (16 chars)
{M\{_2$&!*+}/2/}

Online demo
This is a greedy approach which accumulates edges which don't have any vertex in common with the previously accumulated edges.

I'm pretty sure this fails on the third example, giving [[0 1] [3 4]] instead of the maximal set [[0 2] [1 4] [3 5]]. (I'm ignoring the (1, 1) edge that seem to be in there by mistake)

@ETHproductions, you're confusing maximal with maximum.

Dangit, sorry about that... I'll just leave my comment to help any others who are confused, if you don't mind, since this seems to be a recurring issue :-P

Pyth, 8 bytes
ef{IsTty
       y  power set (gerenate all set of edges)
      t   remove the first one (the first one is
          empty and will cause problems)
 f        filter for sets T satisfying:
     T        T
    s         flatten
  {I          is invariant under deduplicate, i.e. contains no
              duplicating vertices, as the elements represent vertices
e         pick the last one (the power set is ordered from
          smallest to largest)

Try it online!
Specs

Input: [(0,1), (0,2), (1,3), (1,4), (2,3), (3,4), (3,5), (5,6)]
Output: [(1, 4), (2, 3), (5, 6)]

Wolfram Language, 25 22 bytes
Saved 3 bytes thanks to @MartinEnder
FindIndependentEdgeSet

This takes input as a Graph object (defined as Graph[{1<->2,2<->3,1<-3>}] etc.)

You don't need the @#&.

@MartinEnder Thanks.

Pfft. import solve_problem; run(). Now someone just needs to write a plugin for Wolfram that takes in a codegolf challenge URL and outputs the desired output. Call it Golf.

Brachylog, 5 bytes
 ⊇.c≠∧

?⊇.cL≠   implicit ? at the beginning;
         ∧ breaks implicit . at the end;
         temporary variable inserted.
?⊇.      input is a superset of output
  .cL    output concatenated is L
    L≠   L contains distinct elements

Try it online!
This is guaranteed to be maximal, since Brachylog searches from the largest subset.

I think that your explanation has different code than your actual code.

@EriktheOutgolfer That is because I inserted characters that are implicit in my explanation. The original code is in the first line. Brachylog is quite terse in this aspect.

I don't mean that, but the first code ends in ≠∧, while the second code ends in L≠.

Without ∧, there would be an implicit . at the end. All ∧ means here is that the . is not to be inserted at the end.

The L is a temporary variable that is used nowhere, hence its ability to be omitted.

Husk, 10 bytes
►LOfoS=uΣṖ

Try it online!

JavaScript (ES6), 67 bytes

let f =
a=>a.map(b=>r.some(c=>c.some(d=>~b.indexOf(d)))||r.push(b),r=[])&&r

let g = a => console.log("[%s]", f(a).map(x => "[" + x + "]").join(", "))
g([[0,1]])
g([[0,1], [0,2], [1,3], [1,4], [2,3], [3,4], [3,5], [5,6]])
g([[0,1], [0,2], [1,2], [1,3], [1,4], [1,5]])
g([[0,1], [0,2], [1,2], [1,3], [2,4], [3,4], [3,5]])

Uses the greedy approach for maximal golfiness.

JavaScript (ES6), 68 66 bytes
f=a=>a[0]?[a[0],...f(a.filter(b=>!a[0].some(c=>~b.indexOf(c))))]:a
f=([b,...a])=>b?[b,...f(a.filter(c=>!c.some(c=>~b.indexOf(c))))]:a

I thought I'd give the recursive approach a go, and by stealing @ETHproduction's set intersection trick I managed to undercut his answer!
I was not the first to misread the original question, and I was about to submit the following recursive function which finds a maximal set of matching edges, rather than a set of maximal matching edges. Subtle difference, I know!
f=a=>a.map(([b,c])=>[[b,c],...f(a.filter(([d,e])=>b-d&&b-e&&c-d&&c-e))]).sort((d,e)=>e.length-d.length)[0]||[]

Simple recursive approach. For each input element, deletes all conflicting edges from the set and finds the maximal set of matching edges of the remaining subset, then finds the maximal result over each input element. Somewhat inefficient for large sets (9-byte speed-up possible).

Jelly, 12 11 bytes
FQ⁼F
ŒPÇÐfṪ

Try it online!
Sample input: [0,1],[0,2],[1,3],[1,4],[2,3],[3,4],[3,5],[5,6]
Sample output: [[1, 4], [2, 3], [5, 6]]
How it works
FQ⁼F    - Helper function, returns 1 if a set of edges is non-matching
F       - Flatten input
 Q      - Remove repeated elements
  ⁼     - Return boolean value. Is this equal to
   F    - The flattened input list

ŒPÇÐfṪ - Main link.
ŒP     - Power set of input list of edges
   Ðf  - Remove all elements which return 1 if
  Ç    - (Helper function) it is a non-matching set
     Ṫ - Get the last element in the resultant list (the longest).
           Always maximal because it is the longest, so any
           edge added would not be in this list (not matching)

Python 3, 68 bytes
f=lambda g:len({*sum(g,())})<2*len(g)and max(f(g-{k})for k in g)or g

Try it online!
Takes input as set. Recursively removes one item until there are no duplicate vertices. It then returns the set with the most items.


text:
Get rid of whitespace on otherwise empty lines
Ah, yet another of my selfish uses of this Stack.
Being a Chromebook owner, I'm a frequent user of the Ace IDE, the editor used by Cloud9. It has lots of tools for dealing with excess whitespace, but it notably lacks one: clearing empty lines.
Your mission today is, given an input from a place I can copy-paste to [;)], output something identical, save all spaces and tabulators on otherwise empty lines.
I'll give some examples, with #s representing whitespace characters to be removed.

INPUT 1:
if (this.Color !== 'blue') {
##
  this.Color = 'blue';
}

OUTPUT:
if (this.Color !== 'blue') {
[empty line]
  this.Color = 'blue';
}

INPUT 2:
function outputSomething(times) {
  for (var iter = 0; iter < times; iter++) {
    console.log('"# # " represents a tabulator');
    // This is a comment
# #
}}

OUTPUT:
function outputSomething(times) {
  for (var iter = 0; iter < times; iter++) {
    console.log('"# # " represents a tabulator');
    // This is a comment
[empty line]
}}

INPUT 3:
var x = 'Do you prefer spaces or tabs?';
var y = 'I\'m using both here. Sue me.';
# # ####
console.log(x + ' ' + y);

OUTPUT:
var x = 'Do you prefer spaces or tabs?';
var y = 'I\'m using both here. Sue me.';
[empty line]
console.log(x + ' ' + y);

You may process the input however you like. Output wherever, so long as I can copy-paste from it [;)].
Standard loopholes apply, shortest answer in bytes wins!

Do we have to leave an empty line where it says [empty line], or no line at all?

Oh, and, before anyone does it, no getting into the 'spaces vs tabulators' holy war. Doing that gets your answers nuked with a 10,000 byte penalty :P

@LeakyNun an empty line, save for a newline character.

What does # in your examples mean?

@LeakyNun # is visible shorthand for a space, while # with a space in front of it is for a tabulator.

So the line in INPUT 3 is [space][tab][tab][space][space][space]?

@LeakyNun [tab][tab][space][space][space][space].

And are all these clarifications necessary? Just nuke spaces and tabulators on lines that have no other characters.

Is a trailing newline in the output ok?

@BusinessCat Yes.

Is it okay to nuke other whitespace charcters as well?

@HyperNeutrino Absolutely! I was mainly restricting it to ASCII to account for languages that can only process such.

Can we assume that the input will not contain trailing whitespace on any lines (except the all-whitespace ones, obviously)? None of the examples do.

If a line containing non-whitespace has trailing whitespace, is it ok to strip that whitespace?

@DigitalTrauma I suppose, why not.

perhaps, this answer may interest you? https://meta.stackexchange.com/a/294870/300395 @Papayaman1000 this will let you put tabs in

@mathjunkie The challenge could be called "make empty lines empty."

Japt, 10 8 6 5 4 bytes
mx1R

Try it online!
Explanation
(from the Japt docs)
.m(f,s=""):
Splits this with s, maps each item by f, then rejoins with s.

So mx1R splits the string by R which is a newline, trims the right hand side of each line using x1 and joins the strings again with a newline.
Saved 2 bytes thanks to ETHproductions.

Congratulations! You out-golfed Retina!

Very nice! You can save another byte with ®x1}R.

Scratch that, you can just do mx1R to solve the whole problem in 4 bytes of ASCII :-) (The x1 is automatically interpreted by m as _x1}

@ETHproductions Oh wow, thanks for the tips. Can't see why mx1R would work, but it's cool that it does!

It's a sort of hidden feature of Japt: whenever there's a method call that accepts a function as its first argument, and you only do one operator/method call in that function, e.g. m@Xx}, you can just use the letter/operator, e.g. mx. This also works with arguments, hence why m@Xx1} can be shortened to mx1.

But this trims all whitespaces at the right end of a line.

@LeakyNun You're right; none of the examples had trailing whitespaces so I assumed there wouldn't be any.

Retina, 5 bytes
%G`\S

Try it online!
A not so obvious approach rewards us with a better score :)
Explanation
G indicates this as a Grep stage, keeping only those lines where a match to the regex given (\S, matches non-space characters) can be found. If it wasn't for the starting % this would completely remove lines instead of just "emptying" them.
The % is a modifier which applies the stage once to each line and then joins the results with newlines: in our case this means that the empty string returned by Grep for whitespace-only lines will become an empty line in the result.

Was just about to post this, nice. :)

I guess I still have many to learn about Retina.

sed, 6 bytes
/\S/!g

Try it online!
/  /!  # If the line doesn't contain...
 \S    # anything non-whitespace (i.e. the entire line is whitespace)
     g #   replace the pattern space with the hold space which is empty

I probably would have used a substitution.  Using a plain match and g was a clever way to save a couple of bytes.

@DigitalTrauma That was my first solution. This saved 1 byte.

Too bad sed doesn't have \S or "something that is not whitespace". Or does it? /\S/!g

@aragaer There is! Nice!

JavaScript (ES6), 26 bytes
I don't understand why this is getting so many upvotes!
s=>s.replace(/^\s+$/gm,``)

Try It

f=
s=>s.replace(/^\s+$/gm,``)
i.addEventListener("input",_=>o.innerText=f(i.value))
<textarea id=i></textarea><pre id=o>

V, 5, 4 bytes
ÇÓ/D

Try it online!
Explanation:
Ç       " On every line not matching the following regex:
 Ó/     "   a non-whitespace character...
   D    "   Delete the whole line

Hexdump:
00000000: c7d3 2f44                                ../D

Are you sure that's only 5? V often uses more than 1 byte per character.

@papayamam1000 V never uses more than one byte per character. Right here it uses the Latin1 encoding, where all of those non-ASCII symbols are one byte. I've added a hexdump

very well, so it is.

"a non-whitespace character" how does this not exempt linew with multiple whitespace chars from deletion?

Python 3, 63 55 36 bytes
lambda s:[x.strip()and x for x in s]

Input and output are arrays of strings. Join on '\n'.
For the original program that I/O's strings:
lambda s:'\n'.join(x.strip()and x for x in s.split('\n'))

Try it online!
Saved 8 bytes thanks to @Rod!
Saved 19 bytes thanks to @LeakyNun!

@LeakyNun Oh hm, forgot that I could do that. Thanks!

I think your original code was more in tune with the challenge. It asks for you to be able to copy paste text into an input, so really your code should take a single string, not array, and split it.

CJam, 18 16 bytes
qN/{_" 	"-\e&N}%

Note that the string contains 1 space and 1 tab.
Try it online!
Explanation
q                 e# Read the input
 N/               e# Split it on newlines
   {              e# Apply this block to each line:
    _             e#  Copy the line
     "  "-        e#  Remove all spaces and tabs from the copy
          \       e#  Bring the original to the top of the stack
           e&     e#  Logical AND; returns the original line if the copy is truthy
                  e#    (non-empty), otherwise returns the copy line
             N    e#  Push a newline after the line
              }%  e# (end of block)

Retina, 8 bytes
m`^\s+$

A really pointless challenge. m makes it multiline (ignores newline). \s matches both space and tab.
Try it online!

Retina is always first. Even while its poster is asking for [questionably necessary] clarifications in the comments.

@Papayaman1000 People do that all the time. Then they can change their answers if the rules turn out to be different from what's expected.

The Perl version, for 2 more bytes: s;^\d+$; (there is a final newline and -p flag)

Tha challenge may not be very interesting, but calling it really pointless seems excessive

@LuisMendo you can edit my wording as you see fit.

It's your wording, and only you know the intent of your words. Editing it or not, and which new wording to use, is entirely your decision

@HyperNeutrino the correct course of action is to close the challenge as unclear and reopen it once those clarifications have been added.

@MartinEnder Okay. I think it's clear enough now.

APL (Dyalog), 11 10 bytes
'\s+$'⎕R''

⎕R is an operator which derives a function which replaces stuff. In this case, anything matched by the RegEx is replaced with an empty string.

Vim, 20 18 16 13 10 bytes
I am by no means a Vim expert, but this question needs a Vim answer.
:%s/^\s*$<cr>
<cr> is a carriage return.
Changelog:

:norm instead of :normal (-2 bytes)
Switching to * instead of + means we will match already empty lines, but that doesn't matter. And now we can get rid of \v (very magic option) (-2 bytes)
New approach: Instead of replacing every line that matches with an empty line, we replace every line that doesn't have a no non-whitespace characters with an empty line. (-3 bytes)
Actually, a normal replacement is shorter (thanks, @DJMcMayhem) (-3 bytes)

This is shorter as a substitute command: :%s/^\s*$<cr>

AWK, 12 11 bytes
!NF{$0=""}1

Try it online!
I was just feeling like AWK should have an answer too
It works by:

Checking if there are no fields in the input. AWK by default uses all whitespace as separator between fields
If there are no fields, change the input line to an empty string
Print the line. As 1 is a truthy value, it runs the default command which is printing the line

Removed one byte as the semicolon is not necessary after the curly bracket

you gave me an idea ... ^^  I reverted this and end up with 2 bytes: 'NF'

ow... I thought we had to get rid of empty lines... :(

I did exactly the same as my first try and for the same reason. I know that feel :)

the good news is : now I know how to simply get rid of those in my own programs (or when displaying a file) with a really tiny awk oneliner ^^. Your answer is good and tight, by the way. Well done.

Ruby, 22 bytes
->s{s.gsub /^\s+$/,''}

Straightforward regex solution

Java 7, 57 bytes
String c(String s){return s.replaceAll("(?m)^\\s+$","");}

Explanation:
String c(String s){     // Method with String parameter and String return-type
  return s.replaceAll(  //  Return the input String after we've replaced
    "(?m)^\\s+$",       //  all lines only containing whitespaces
    "");                //  with empty Strings
                        //    (NOTE: `(?m)` enables multiline regex)
}                       // End of method

Test code:
Try it here.
class M{
  static String c(String s){return s.replaceAll("(?m)^\\s+$","");}

  public static void main(String[]a){
    System.out.println(c("if (this.Color !== 'blue') {\n \t\n  this.Color = 'blue';\n}"));
    System.out.println();
    System.out.println(c("function outputSomething(times) {\n  for (var iter = 0; iter < times; iter++) {\n    console.log('\"# # \" represents a tabulator');\n    // This is a comment\n  \t\n}}"));
    System.out.println();
    System.out.println(c("var x = 'Do you prefer spaces or tabs?';\nvar y = 'I\'m using both here. Sue me.';\n    \t\t\t \nconsole.log(x + ' ' + y);"));
  }
}

Groovy, 31 bytes
{it.replaceAll(/\n\s+\n/,"\n")}

Won't that remove the empty line?

Perl 6,  15  12 bytes
15
{S:g/^^\h+$$//}

Try it
{         # bare block lambda with implicit parameter ｢$_｣

  S       # string replace (implicitly against ｢$_｣)
  :global # globally
  /
    ^^    # match beginning of line
      \h+ # match at least one horizontal whitespace
    $$    # match end of line

  //      # replace with nothing
}

11+1
perl6 -pe 's/^^\h+$$//'

Largely the same as above.

-p runs the code for every line of input, putting the line into $_ and printing whatever is left in $_.
s replaces in-place, whereas S returns the result.
No need for :g/:global as -p takes care of that.

Python 2, 26 bytes
lambda l:map(str.rstrip,l)

Try it online! Inputs and outputs a list of strings.
This takes advantage of the ruling in the comments that trailing whitespace may be removed on non-empty lines.

Vim, 13 9 bytes
:v/\S/le↵
Edits:

Original answer: :v/\S/d↵ (based on this vim question on SO).
It deletes empty lines, which isn't the expected behavior.
Valid answer using vglobal: :v/\S/norm D↵
Now using the left-align ex command instead of normal D

Welcome to PPCG! I'm not really sure why you apologized, because this is a valid answer on its own.

Thank you! It expands on @L3viathan's answer and uses the same "language", so i'd have commented on his solution to limit the (already large) number of answers if I could.

We aren't terribly concerned with having a lot of answers, or having multiple solutions in the same language. While we do encourage comments instead of new answers for small improvements upon existing answers, it's still OK to post a new answer (especially given that you can't comment yet).

C, 168 bytes
#define P putchar(*t++)
s;e(char*t){s=0;while(*t>10)if(*t!=32|*t!=9)return 0;else t++,s++;return s;}
r(char*t){while(*t==10)P;if(!*t)return;if(!e(t))while(*t)P;t+=e(t);}

Detailed
#include <stdio.h>

int e (char * t)
{
    int s = 0;

    // till the end of the line
    while (*t!='\0' && *t!='\n')
        // if it's not a space
        if (*t!=' ' || *t!='    ')
            // ignore the line
            return 0;
        else
            // count the space
            t++, s++;

    // return number of spaces
    return s;
}

void r (char * t)
{
    // skip to empty lines
    while (*t != '\0' && *t == '\n') putchar('\n'), t++;

    // stop at end of string
    if (*t == '\0') return;

    // if there is contnet print it
    if (!e(t)) while(*t != '\0') putchar(*t), t++;

    // skip to the end of line
    t += e(t);
}

int main (int argc, char**argv)
{
    if (argc > 1) r(argv[1]);
    putchar('\n');
    return 0;
}

C, 100 bytes
c,i,j;f(char*s){for(i=j=c=0;s[i];s[++j]^10?c=s[j]^32:(printf(!c?"\n":"%.*s",j-i+1,s+i),c=0,i=j+1));}

See it work online.

QuadR, 5 bytes
\s+$

Try it online!
\s+ replace one or more whitespace chars followed by
$ end of line
 with nothing


text:
Displaying n with n
What I want:
Quite simply, I want a text based display, that asks for an input, n, then shows that value on the display! But there's a catch. Each of the 'true' 'pixels' (the ones filled in) has to be represented by that number n..
Example :
You are given an input n. You can assume n will be a single digit
Input: 0
Output:
000
0 0
0 0
0 0
000

Input: 1
Output:
  1
  1
  1
  1
  1

Input: 2
Output:
222
  2
222
2
222

Input: 3
Output:
333
  3
333
  3
333

Input: 4
Output:
4 4
4 4
444
  4
  4

Input: 5
Output:
555
5
555
  5
555

Input: 6
Output:
666
6
666
6 6
666

Input: 7
Output:
777
  7
  7
  7
  7

Input: 8
Output:
888
8 8
888
8 8
888

Input: 9
Output:
999
9 9
999
  9
999

Challenge:
Do the above it in as few bytes as possible.
I will only accept answers that meet all requirements.
Surrounding whitespace is optional, as long as the digit is displayed properly.
Also, <75 bytes is a vote from me, the lowest accept, but I could always change the accepted answer, so don't be discouraged to answer.

Related

Surely, this is a duplicate. It's definitely very close to this

Possible duplicate of Golf me an ASCII Alphabet

I don't think its a dup.  While the questions are very similar, I think the reduced set of characters (0-9) will make for some quite different answers.

SOGL V0.12, 30 bytes
■'τč▲Β►║⁰ΡāQšJ┘tXdnοO¹‘'¹n.w3n

Try it Here!
The compressed string ■'τč▲Β►║⁰ΡāQšJ┘tXdnοO¹‘ is
  ŗ  ŗ  ŗ  ŗ  ŗŗŗŗ  ŗŗŗŗŗ  ŗŗŗŗŗŗ  ŗŗŗŗ  ŗŗŗŗŗ ŗŗ ŗŗŗŗ  ŗ  ŗŗŗŗŗ  ŗŗŗ  ŗŗŗŗŗŗŗŗ  ŗŗŗŗ ŗŗŗŗŗŗŗ  ŗ  ŗ  ŗ  ŗŗŗŗŗ ŗŗŗŗŗ ŗŗŗŗŗŗŗŗ ŗŗŗŗ  ŗŗŗŗŗŗŗŗ ŗŗ ŗŗ ŗŗŗŗ

which is (starting with 1, ending with 0) the numbers, line by line, number to number.
The rest
...‘             push the compressed string, replacing the ŗs with pop - the input
    '¹n          split into chunks of 15
       .w        push the (1-indexed, wrapping) input-th item of that array
             3n  split into chunks of 3
                 implicitly output the array, line by line

I am impressed about how you managed to do it in 35 bytes in one go! Although I have never used SOGL before, I used an online tester and it works!

The number shape data is really only 17 bytes (the 6 bytes lost there are length data and that it's   and -), and the rest is easy. I'm curious, what online tester did you use? I haven't made nor seen any.

Oh, just click on the SOGL above! You have to download something like 1MB or something. I deleted it instantly. :/

How did you do it?

Oh, wow! Congrats to you! You seem to have a lot of files in it. Maybe seperate it a little bit

What's p5parser?

Let us continue this discussion in chat.

JavaScript (ES6), 88 bytes

f=
n=>`019
2 3
459
6 7
889`.replace(/\d/g,c=>[2,18,142,96,130,131,698,4,146][c]>>n&1?` `:n)
<input type=number min=0 max=9 oninput=o.textContent=f(this.value)><pre id=o>

The numbers encode which squares contain spaces for a given digit e.g. the bottom left corner has a value of 146 because the 1, 4 and 7 don't use it and 146 = 2¹ + 2⁴ + 2⁷.

05AB1E, 40 39 38 bytes
•Y¤ŸèK'¦ú’ò™^N•4B5ô¹èvð¹«5714yè8+b¦Sè,

Try it online!
Explanation
•Y¤ŸèK'¦ú’ò™^N•            # the compressed string "318975565561233953387608032537"

4B                         # convert to base-4
  5ô                       # split into strings of size 5
    ¹è                     # get the string at index <input>
      v                    # for each digit y in string
          5714yè           # get the digit in 5714 at index y
                8+         # add 8
                  b        # convert to binary
                   ¦       # remove the leading 1
       ð¹«          Sè     # with each digit in the binary number,
                           # index into the string " <input>"
                      ,    # print with newline

Japt, 43 bytes
"Ýûÿ©ÿßY÷ß"®c s4Ã¤ëAU ¬£2839¤ë4XÃ·d0S1U

Contains some unprintables. Try it online!
Tallies: 13 bytes of compressed data, 9 bytes to decompress it, and 21 bytes to form the output.
Explanation
Ungolfed code:
"Ýûÿ©ÿßY÷ß"®   c s4Ã ¤  ëAU ¬ £  2839¤  ë4XÃ ·  d0S1U
"Ýûÿ©ÿßY÷ß"mZ{Zc s4} s2 ëAU q mX{2839s2 ë4X} qR d0S1U

There are exactly 4 different row possibilities: (# represents a digit)
#
  #
# #
###

Thus, each number can be stored as a set of five base-4 digits. Since each number can be then stored in 10 bits, the total is 100 bits, which corresponds to 13 bytes. I'll skip the compression process and instead explain the decompression.
mZ{Zc s4}

mZ{     }  // Replace each character Z in the compressed string with the following:
   Zc      //   Take the char-code of Z.
      s4   //   Convert to a base-4 string.

After decompression, the 13-byte compressed string looks like this:
3131332333332111200122213333313321011121213133133133

Note that this would fail if any of the 4-digit runs started with 0, as the leading zeroes would be left off when s4 is run. We can fix this by having 0 represent #  , which only appears three times, and none of those fall at the start of a 4-digit run.
s2         // Slice off the first two chars of the result.

Okay, so in order to get our 50-digit string to compress nicely in chunks of 4, we had to add two extra digits. Adding them to the beginning of the string means we can chop them off with the one-byter ¤.
ëAU        // Take every 10th (A) char in this string, starting at index <input> (U).

Embarrassingly, Japt lacks a built-in for splitting a string into slices of length X. It does have a built-in for getting every Xth char, however, so we can store all the data by encoding all of the top rows first, then all of the second rows, etc.
So now we have the 5-digit string encoding the digit we want to create, e.g. 32223 for 0.
q mX{2839s2 ë4X} qR
q                    // Split the resulting string into chars.
  mX{          }     // Replace each char X with the result of this function:
     2839s2          //   Convert the magic number 2839 to a binary string.
            ë4X      //   Take every 4th char of this string, starting at index X.
                 qR  // Join the result with newlines.

To explain the magic number, refer back to the four distinct rows. If you replace # with 1 and   with 0, you get
100
001
101
111

Transposing this and then joining into a single string gives us 101100010111. Convert to decimal and, voilà, you have 2839. Reversing the process maps the digits 0123 into the four binary rows shown above.
Almost done! Now all that's left to do is add in the spaces and digits:
d0S1U      // In the resulting string, replace 0 with " " (S) and 1 with <input> (U).

And presto, implicit output takes care of the rest. I'm sorry this explanation is so long, but I don't see any real way to golf it without making it less understandable (if it is understandable...)

JavaScript (ES6), 115 111 bytes
Takes input as a string.
n=>'02468'.replace(/./g,c=>(n+n+n+`   ${n} `+n).substr([126,341,36,68,327.5,66,98,340,102,70][n]*4>>c&6,3)+`
`)

How it works
Pattern encoding
The four distinct patterns "XXX", "X..", "..X" and "X.X" can be compressed as "XXX...X.X" and extracted this way:
XXX...X.X
^^^        --> XXX  (id = 0 / pointer = 0)
  ^^^      --> X..  (id = 1 / pointer = 2)
    ^^^    --> ..X  (id = 2 / pointer = 4)
      ^^^  --> X.X  (id = 3 / pointer = 6)

By substituting the input digit n for "X" and using actual spaces, this gives the expression:
n+n+n+`   ${n} `+n

Digit encoding
Using the pattern identifiers defined above, each digit can be represented by a 5 * 2 = 10-bit quantity.
For instance:
XXX  -->  0 *   1 =   0
X.X  -->  3 *   4 =  12
XXX  -->  0 *  16 =   0
..X  -->  2 *  64 = 128
XXX  -->  0 * 256 =   0
                    ---
                    140

The complete list is:
[252, 682, 72, 136, 655, 132, 196, 680, 204, 140]

However, dividing these values by 2 allows to save two bytes. So instead we store:
[126, 341, 36, 68, 327.5, 66, 98, 340, 102, 70]

Demo

let f =

n=>'02468'.replace(/./g,c=>(n+n+n+`   ${n} `+n).substr([126,341,36,68,327.5,66,98,340,102,70][n]*4>>c&6,3)+`
`)

console.log(f('0'))
console.log(f('1'))
console.log(f('2'))
console.log(f('3'))
console.log(f('4'))
console.log(f('5'))
console.log(f('6'))
console.log(f('7'))
console.log(f('8'))
console.log(f('9'))

Bash + GNU utils, 114

2 bytes saved thanks to @SophiaLechner

There are probably some more opportunities for compression here, but here's a start:
dc<<<4o16iEAC00CDF33AC373DEF00EEFB3p|fold -5|sed "$[$1+1]!d
s/0/  x\n/g
s/1/x\n/g
s/2/x x\n/g
s/3/xxx\n/g
y/x/$1/"

Explanation
Each row of of every digit is one of these four patterns:
  x
x
x x
xxx

By labeling these 0-3, each digit can be represented by 5 base-4 digits.  E.g. 0 would be 32223, and the full list of digits is encoded in base-4 as 32223000003031330303223003130331323300003232332303.  This encoded in hex as EAC00CDF33AC373DEF00EEFB3.

dc converts hex EAC00CDF33AC373DEF00EEFB3 to base-4.
fold puts 5 base-4 digits on each line
sed:

deletes all input lines apart from line number n+1 (sed 1-indexes lines)
translates the base-4 digits to the pattern (of xes) for each line of the given digit, along with a newline for the end of each row
transliterates the xes to digit n.

Try it online.

Good idea! Save a couple bytes by replacing s/1/x  \n/g with s/1/x\n/g, since those spaces won't visually affect the output.

MATL, 45 43 bytes
'V~4;LR`I-D2q (z%eI)P-nc'F TFZa15eiZ)5eGV*c

Try it online!
Explanation
'V~4;LR`I-D2q (z%eI)P-nc' % Compressed string using printable ASCII except '
F TFZa                    % Decompress (change of base) into alphabet [1 0]
15e                       % Reshape into 15-row matrix. Each column contains the
                          % art for one digit, packed in column-major order
iZ)                       % Take input number and pick the corresponding column.
                          % Indexing is 1-based and modular, so 0 is at the end
5e                        % Reshape into a 5-row matrix. This already looks like
                          % the number, with active pixels as 1 and inactive as 0
GV                        % Push input number again. Convert to string, of one char
*                         % Multiply, element-wise. The previous char is
                          % interpreted as its ASCII code. This changes 1 into the
                          % ASCII code of the input digit, and leaves 0 as is
c                         % Convert to char. Implicitly display. Char 0 is shown as
                          % a space

Retina, 166 164 163 bytes
Two spaces on the third line from the bottom
0
0addda
d
0 0
1
1b1b1b1b1b1
2
2ab2a2b222
3
3ab3ab3a
4
44 44 4ab4b4
5
55ab555b5a
6
66ab6a 6a
7
7ab7b7b7b7
8
88a 8a8 8a
9
99a 9ab9a
(\d)a
$1$1$1$1
^.

b
  .{3}
$+¶

Try it Online!
An improved version of @Okx's solution

Pyth 82 85 91 100 bytes
Km?dC+48Q\ m.&C@"w$kn<^_d\x7f~"Qdj1906486293414135453684485070928 128V5p.)Kp.)K.)K

A lot of golfing probably possible, my first challenge.

Welcome to PPCG!

Batch File, 8 + 184 bytes
Here's my obligatory batch solution. Unfortunately the standard method of accomplishing this is over 300 bytes in batch, so we resort to much cheaper tactics.
@type %1

In the current directory, I have 10 files set up, named from 0 to 9. In each of these is the respective 5x3 grid of pixels. For example:

The byte counts for these are:
19 0
19 1
17 2
19 3
19 4
17 5
17 6
19 7
19 8
19 9
Total - 184

Still beat Java.

Retina, 190 bytes
0
000¶aaa000
a
0 0¶
1
aaaaa
a
b1¶
2
ab2¶a2¶a
a
222¶
3
ab3¶ab3¶a
a
333¶
4
4 4¶4 4¶444¶b4¶b4
5
a5b¶ab5¶a
a
555¶
6
a6¶a6 6¶a
a
666¶
7
777aaaa
a
¶b7
8
a8 8¶a8 8¶a
a
888¶
9
a9 9¶ab9¶a
a
999¶
b

There are two spaces on the last line but SE doesn't want to render it :/ Fixed!
Try it online!

I have a feeling there's a way to combine the repeated replacement of a with three digits and a newline. (Maybe using lookaheads?)

@mathjunkie Yeah :/

PowerShell,159 135 128 118 bytes
param($n);0..4|%{("$n$n$n","$n $n","  $n","$n  ")['01110333330203002020110220302003010022220101001020'[$_+($n*5)]-48]}

Current answer: removed extraneous variable naming
Try it online!
I'll have to see if I can get some tricks from the other answers :P
EDIT Getting smarter with calling the mega string
EDIT2 Switched to using a string of numbers to index into $a to save 7 bytes. Although I liked my previous dynamic variable name calls in the below code (135 bytes)
param($n);$a="$n$n$n";$b="$n $n";$c="  $n";$d="$n  ";$r="abbbadddddacadaacacabbaccadacaadabaaccccababaabaca";0..4|%{gv $r[$_+($n*5)]-v}

PHP, 115 Bytes
for(;$i<5;)echo strtr(sprintf("%03b\n","1754"[[425,0,465,273,26,285,413,1,409,281][$argn]/4**$i++%4]),[" ",$argn]);

Try it online!
Expanded
for(;$i<5;)
  echo strtr(
    sprintf("%03b\n",  # make a binary
      "1754"[[425,0,465,273,26,285,413,1,409,281][$argn]/4**$i++%4])
    ,[" ",$argn]); # replace 0 with space and 1 with the input

Encoding
Try it online!

Ruby, 94 bytes
->n{20.times{|i|print i%4>2?$/:[" ",n]["_Q_@@_]UWUU_GD_WU]_U]AA__U_WU_"[n*3+i%4].ord>>i/4&1]}}

Ungolfed in test program
f=->n{
  20.times{|i|                           #4 characters * 5 rows = 20
    print i%4>2?$/:                      #If i%4=3 print a newline else
    [" ",n][                             #either a space if the expression below is 0 or the digit n if 1.
      "_Q_@@_]UWUU_GD_WU]_U]AA__U_WU_"[  #bitmap data for digits, one character for each column
        n*3+i%4].ord>>i/4&1              #Select the correct character for the column, convert to ascii code,
    ]                                    #rightshift to find the correct bit for the row,
  }                                      #use & to isolate the bit: 0 or 1
}

f[gets.to_i]

PowerShell, 126 120 113 109 101
$n="$args"
-split'ϽϭϿ·ͱ Ο·ͽͼϿ·Ņ ϻ·ͭͭϿ'|%{-join($_[0..2]|%{"$n·"[!($_-band1-shl$n)]})}

Unicode is fun. Characters are also way shorter than numbers. Above code contains U+0000 twice, thus cannot be copied directly (works fine in a file, though). The following code can be copied:
$n="$args"
-split"ϽϭϿ ͱ`0Ο ͽͼϿ Ņ`0ϻ ͭͭϿ"|%{-join($_[0..2]|%{"$n "[!($_-band1-shl$n)]})}

We lose three bytes because we need the UTF-8 signature at the start. Otherwise the string won't work.

Retina, 125 bytes
.
A$&¶B$&¶C$&¶D$&¶E$&
([ACE][235689]|A0|E0|C4|A7)(?<=(.))
$2$2$2
(B[0489]|D[068]|A4|C0)(?<=(.))
$2 $2
D2
2
B5
5
B6
6
[A-E]

Try it online! (Delete test suite in header to test individual input digits.) Last line contains two spaces.

Python 2, 174 125 bytes
lambda n:'\n'.join('xxx  x x'[int(i):][:3]for i in oct(0x3028000adba93b6b0000c0ad36ebac30180c0)[:-1][n::10]).replace('x',`n`)

Try it online!

Java 8, 278 214 210 204 bytes
n->("A"+n+"\nB"+n+"\nC"+n+"\nD"+n+"\nE"+n).replaceAll("([ACE][235689]|A0|E0|C4|A7)(?<=(.))","$2$2$2").replaceAll("(B[0489]|D[068]|A4|C0)(?<=(.))","$2 $2").replaceAll("D2|B5|B6",n).replaceAll("[A-E]","  ")

Port of @Neil's Retina answer. Takes the input as a String.
Try it here.

Jelly, 35 32 bytes
Ṿ⁶,“SÐ~ẈoI9Ẇ¦Y./,0&Ƥɓ€ọ’ṃs15ị@s3

Try it online! or see them all.
Same as dzaima's method.

Charcoal, 61 38 33 bytes
Ｅ§⪪”{⊞¶↙⬤\→(Ｂ⊘K→υ^⎇\`｜;ε”⁵Ｎ⮌⍘Ｉι⁺ θ

Try it online! Link is to verbose version of code. Explanation:
   ”...”            Compressed data string
  ⪪     ⁵           Split into groups of 5 digits
 §                  Indexed by
         Ｎ          First input as an integer
Ｅ                   Map over digits
             ι      Current digit
            Ｉ       Cast to integer
           ⍘        Converted to custom base
              ⁺ θ   Space concatenated with input digit
          ⮌         Reversed
                    Implicitly print

A generic port is a bit boring, so here's a more idiomatic 61-byte answer:
ＧＨ✳✳§⟦⟦↑L↓¬⟧⟦↓↓⟧⟦T↓→⟧⟦T→¬⟧⟦↑↑¬↑⟧⟦←↓T⟧⟦T↑L⟧⟦→↓↓⟧⟦+L↓⟧⟦+↓T⟧⟧Ｎ³θ

Try it online! No verbose version as the deverbosifier doesn't understand lists of directions or even multidirectionals inside ordinary polygons. Explanation:
     ⟦...⟧      Array of paths, see below
          Ｎ     Input as an integer
    §           Index into the array
  ✳✳            Treat the element as direction data
           ³    Length of each segment (including 1 character overlap)
            θ   Draw using the input character
ＧＨ              Draw a path

Each path is specified using a list of directions (←↑→↓). Four usable shortcuts save bytes: L represents ↑→, ¬ represents ↓←, T represents →↓← while + represents →↓←↑, although at least one arrow must remain for the list to be recognised as a direction list (so for instance TT cannot be used for 3).
60 bytes using the newer version of Charcoal available on ATO:
ＧＨ✳✳§⟦⟦⌈¬↑↑⟧⟦↓↓⟧⟦T↓→⟧⟦T→¬⟧⟦↑↑¬↑⟧⟦←↓T⟧⟦+↑→⟧⟦⌈↓⟧⟦+↑⌈⟧⟦+↓T⟧⟧Ｎ³θ

Attempt This Online! Link is to verbose version of code. Explanation: The order in which multidirectionals execute changed which means that 7 can now be drawn using a multidirectional and an arrow instead of three arrows. Some of the other digits have had to have their multidirectionals tweaked but this was possible without changing the length of the code.

Perl 5 -Mbigint -pa, 101 bytes
$_=sprintf"%16b",0xf79ef7dee492f3def39eb792e79ee7ce4924f6de>>16*$_&65535;eval"y/01/ @F/";s/...\K/\n/g

Try it online!

Python 3, 119 bytes
lambda n:(3*f"%s%s{n}\n%s %s\n")[:30]%(*[n if i//(2**n)%2else" "for i in[1021,1005,881,927,893,892,325,1019,877,877]],)

Try it online!
Each 'pixel' is represented as an integer where each power of two indicates whether the pixel is solid.
This takes advantage of the fact that the three right-hand corners are always the digit.

Befunge, 192 174 bytes
3040040403333004010030103304403030010302222204440&:09p5*>:  #v_v
   9g86*+:00p:10p:20p:01p:12p:23p:04p24p 6v             ^-1$\< >
   ,+55,g\2,g\1:,g\0:\_@#:-1p31p30:p41:*84<$

Try it online!
First stab was ~360 bytes doing if/else & pushing characters to stack. Which was devoting 150 characters to encoding numbers. So instead encode characters as 5 numbers based on each line. Then pop 5x input to have top 5 stack elements be desired character. 2nd line sets up line pieces with correct characters in top left 3x5 of memory

JavaScript (ES8), 87 bytes
n=>`019
2 3
459
6 7
889`.replace(/\d/g,c=>[2,18,142,96,130,131,698,4,146][c]>>n&1?' ':n)

This is exactly the same answer as @Neil's JavaScript answer of April 27th.. If you have something he can improve, you should comment to his answer instead of posting a new one that is the same (EDIT: And yes, I realize you don't have enough reputation to comment yet..)