Skip to main content
We’ve updated our Terms of Service. A new AI Addendum clarifies how Stack Overflow utilizes AI interactions.
Code Golf

Return to Answer

Commonmark migration
Source Link

###How it works

How it works

###How it works

How it works

added 1419 characters in body
Source Link
Peter Taylor
  • 43.4k
  • 4
  • 72
  • 179

###How it works

# On the stack: a string such as "1,3-5,9,16,18-23"
','/
# Split on commas to get ["1" "3-5" "9" "16" "18-23"]
{
 # This is executed for each of those strings in a map
 # So stack holds e.g. "1" or "3-5"
 # Evaluate the string.
 # If it's a single number, this puts the number on the stack.
 # Otherwise it's parsed as a positive number followed by a negative number.
 ~
 # Stack holds e.g. 1 or 3 -5
 # Duplicate the last element on the stack and make a list of that length.
 # If it's negative or zero, the list will be empty
 .,
 # Negate. An empty list => 1; a non-empty list => 0
 !
 # If the string was a single number "n", the stack now holds n 0
 # If the string was a range "m-n", the stack now holds m -n 1
 # The following block will be executed 0 times for "n" and once for "m-n"
 {
 # Here we rely on twos-complement numbers satisfying ~n = -n -1
 # Stack: m -n
 ~))
 # Stack: m -(-n)-1+2 = m n+1
 ,
 # Stack: m [0 1 2 ... n]
 >
 # Stack: [m m+1 ... n]
 ~
 # Stack: m m+1 ... n
 }*
}%
# On the stack: e.g. [1 3 4 5 9 16 18 19 20 21 22 23]
','*
# Joined by , to give the desired output

###How it works

# On the stack: a string such as "1,3-5,9,16,18-23"
','/
# Split on commas to get ["1" "3-5" "9" "16" "18-23"]
{
 # This is executed for each of those strings in a map
 # So stack holds e.g. "1" or "3-5"
 # Evaluate the string.
 # If it's a single number, this puts the number on the stack.
 # Otherwise it's parsed as a positive number followed by a negative number.
 ~
 # Stack holds e.g. 1 or 3 -5
 # Duplicate the last element on the stack and make a list of that length.
 # If it's negative or zero, the list will be empty
 .,
 # Negate. An empty list => 1; a non-empty list => 0
 !
 # If the string was a single number "n", the stack now holds n 0
 # If the string was a range "m-n", the stack now holds m -n 1
 # The following block will be executed 0 times for "n" and once for "m-n"
 {
 # Here we rely on twos-complement numbers satisfying ~n = -n -1
 # Stack: m -n
 ~))
 # Stack: m -(-n)-1+2 = m n+1
 ,
 # Stack: m [0 1 2 ... n]
 >
 # Stack: [m m+1 ... n]
 ~
 # Stack: m m+1 ... n
 }*
}%
# On the stack: e.g. [1 3 4 5 9 16 18 19 20 21 22 23]
','*
# Joined by , to give the desired output
Source Link
Peter Taylor
  • 43.4k
  • 4
  • 72
  • 179

GolfScript (24 chars)

','/{~.,!{~)),>~}*}%','*

E.g.

$ golfscript.rb expand.gs <<<"1,3-5,9,16,18-23"
1,3,4,5,9,16,18,19,20,21,22,23

I actually have four 24-char solutions, but I chose this one because it doesn't have any alphanumeric characters.

AltStyle によって変換されたページ (->オリジナル) /