-2

To convey the merits of Lambda Calculus, and even JavaScript's ability to implement such (Turing-complete) formulas, I'd like to see the most elegant and concise way that one JS file could print the correct string of the following language, given a natural number n (zero-based):

anbncn

This would also mean without the use of external libraries, nor iterative machinery (e.g. "while", "for", etc.).

anbn , for example, being a context-free grammar perhaps can get no simpler than:

function print(n) {if(n>0) {console.log('a'); print(n--); console.log('b');}}

  • I suspect that using JavaScript's embedded array stack would work, but I think there would be a design more elegant than that. – Benjamin Paige Jul 25 '20 at 17:08
  • This is a question for [codegolf.SE], not StackOverflow. Btw your rules are unclear, do you consider `'a'.repeat(n)` to be "iterative machinery"? – Bergi Jul 26 '20 at 14:32
  • @Bergi you are correct. Sorry, was not aware of a "Code Golf". And yes, I could be more clear in defending against unknown features like "repeat". I should have further specified the abstract nature of the design that I'm intending. – Benjamin Paige Jul 27 '20 at 14:06
  • I moved the question, thanks again: https://codegolf.stackexchange.com/questions/207690/what-is-the-most-concise-way-to-generate-strings-of-language-anbncn-using-javasc – Benjamin Paige Jul 27 '20 at 14:18

1 Answers1

0

Since you're OK with recursion in your example,

function print(n) {
  printA(n);
  printB(n);
  printC(n);
}

function printA(n) {
  if (n > 0) {
    console.log('a');
  }
  printA(n - 1);
}

// with printB and printC implemented similarly.

If that's not as appealing, you could roll the three printX functions together in a manner like this:

function printABC(n) {
  print(n,3*n);
}

function print(division, current) {
  if (current > 0) {
    if (current < division) {
      console.log('c');
    }
    else if (current < division * 2) {
      console.log('b');
    }
    else {
      console.log('a');
    }
    print(division, current - 1);
  }
}

Give or take some off-by-ones with < vs <=.

Welbog
  • 59,154
  • 9
  • 110
  • 123
  • That's good. It works. But I think it could be better. The first solution seems like a lot of code. While the second has a complicated logic path. Regardless, I placed the question on the wrong platform. Thank you for your answer. https://codegolf.stackexchange.com/questions/207690/what-is-the-most-concise-way-to-generate-strings-of-language-anbncn-using-javasc – Benjamin Paige Jul 27 '20 at 14:22