# Question
Title: Count the number of vowels in each word of a string
This is a rather easy challenge.

# Challenge

Input will contain a string (not `null` or empty) of maximum length 100. Output the number of vowels in each word of the string, separated by spaces.

# Rules

* The string will not be more than 100 characters in length.
* The string will only contain alphabets `A-Z` , `a-z` and can also contain spaces.
* Input must be consumed from the `stdin` or command line arguments.
* Output must be outputted in the `stdout`.
* You can write a full program, or a function that takes input from the `stdin` and outputs the result.
* The vowels that your program/function needs to count are `aeiou` and `AEIOU`.

# Test Cases

```
This is the first test case     --> 1 1 1 1 1 2
one plus two equals three       --> 2 1 1 3 2
aeiou AEIOU                     --> 5 5
psst                            --> 0
the quick brown fox jumped over the lazy dog --> 1 2 1 1 2 2 1 1 1

```

# Scoring

This is , so the shortest submission (in bytes) wins.

# Answer
# Pyth, 17 bytes

```
jdml@"aeiou"dcrzZ

```

Straightforward solution. Try it online: Demonstration or Test harness

### Explanation:

```
               z   input
              r Z  convert to lower-case
             c     split at spaces
  m                map each word d to:
    @"aeiou"d         filter d for chars in "aeiou"
   l                  length
jd                 join by spaces and implicitly print

```
> 8 votes

# Answer
# C, ~~113 108 103~~ 96 bytes

Thanks @andrea-biondo for a particularly nice 5 byte saving.

```
main(a,v,c)char**v;{do{for(a=0;c=*v[1]++%32;2016%(c+27)||a++);printf("%d ",a);}while(v[1][-1]);}

```

This still feels sort of bloated so hopefully I can get it down quite some bytes later tonight.

The interesting part is perhaps that

```
!(124701951%((c-65&31)+33))

```

will be `1` if `c` is an (upper or lower case) ASCII vowel, and `0` for other characters `a-zA-Z`. The subexpression `c-65&31` maps `'a'` and `'A'` to `0`, `'b'` and `'B'` to `2`, etc. When we add `33` the vowels correspond to the numbers `33, 37, 41, 47, 53` respectively, all of which are (conveniently) prime. In our range only such numbers will divide `124701951 = 33*37*41*47*53`, ie only for vowels will the remainder of `124701951%(...)` be zero.

EDIT: In this way one can consider the expression `!(n%((c-65&31)+s))` where `(n,s) = (124701951, 33)` as determining whether the character `c` is a vowel. In the comments @andrea-biondo pointed out that the pair `(n,s) = (2016,28)` can also be used in this expression to determine vowelhood. I'll leave the current explanation in terms of primes above, but the reason this shorter pairing works is again because in the range 28--53 the only numbers with prime factors entirely in the set of prime factors of 2016 are 28, 32, 36, 42, 48, which correspond precisely to the vowels.

EDIT2: Another 5 bytes saved since `(c-65&31)+28` can be shortened to `c%32+27`.

EDIT3: Converted to a do-while loop to finally get it below 100 bytes.

Test cases:

```
$ ./vowelc "This is the first test case"
1 1 1 1 1 2
$ ./vowelc "one plus two equals three"
2 1 1 3 2
$ ./vowelc "aeiou AEIOU"
5 5
$ ./vowelc "psst"
0

```
> 11 votes

# Answer
# CJam, ~~21~~ 19 bytes

```
r{el_"aeiou"--,Sr}h

```

**How it works**:

```
r{               }h    e# Read the first word and enter a do-while loop
  el_                  e# Convert the word into lower case and take a copy of it
     "aeiou"           e# All small caps vowels
            -          e# Remove all vowels from the copied word
             -         e# Remove all non-vowels from the original word
              ,        e# At this point, we have a string with all vowels of the word
                       e# Simply take its length
               S       e# Put a space after the number of vowel
                r      e# Read the next word. This serves as the truthy condition for the
                       e# do-while loop for us as if there are no word left, this returns
                       e# null/falsy and the do-while loop is exited

```

Try it online here
> 7 votes

# Answer
# R, ~~44~~ 43 bytes

```
cat(nchar(gsub("[^aeiou]","",scan(,""),T)))

```

Ungolfed + explanation:

```
# Read a string from STDIN. scan() automatically constructs a vector
# from input that contains spaces. The what= argument specifies that
# a string will be read rather than a numeric value. Since it's the
# second specified argument to scan(), we can simply do scan(,"").

s <- scan(what = "")

# For each word of the input, remove all consonants using gsub(),
# which is vectorized over its input argument.

g <- gsub("[^aeiou]", "", s, ignore.case = TRUE)

# Print the number of remaining characters in each word to STDOUT
# using cat(), which automatically separates vector values with a
# single space.

cat(nchar(g))

```
> 6 votes

# Answer
# Perl, 35 34 31

```
say map{lc=~y/aeiou//.$"}split

```

`30` characters `+1` for `-n`.

Like a lot of Perl code, this works from right to left. `split` will split the inputted line on whitespace. `map` will run the code between `{}` on each word that was split. `lc` makes the word lower case. `=~y/aeiou//` will give us the count of vowels. `.$"` will append a space to the word. `say` then prints all the words!

Run with:

```
echo 'aeiou AEIOU' | perl -nE'say map{lc=~y/aeiou//.$"}split'

```
> 5 votes

# Answer
# Python 3, 65 bytes

```
print(*[sum(c in'aeiouAEIOU'for c in w)for w in input().split()])

```

Very straightforward, fairly readable. `w` stands for word, `c` stands for character.
> 5 votes

# Answer
# Ruby, 38 bytes

```
$><<$*.map{|x|x.count'AIUEOaiueo'}*' '

```

Usage:

```
mad_gaksha@madlab /tmp/ $ ruby t.rb This is the first test case
1 1 1 1 1 2

```
> 4 votes

# Answer
# Perl: 30 characters

(Kind of forces the rules: the numbers in the output are separated with as many spaces as the input words were.)

```
s|\w+|@{[$&=~/[aeiou]/gi]}|ge

```

Sample run:

```
bash-4.3$ while read s; do printf '%-30s --> ' "$s"; perl -pe 's|\w+|@{[$&=~/[aeiou]/gi]}|ge' <<< "$s"; done < test-case.txt
This is the first test case    --> 1 1 1 1 1 2
one plus two equals three      --> 2 1 1 3 2
aeiou AEIOU                    --> 5 5
psst                           --> 0

```

### Perl: 27 characters

(Just to show how short would be if I didn't forget about `y///`'s return value. Again. Now go and upvote chilemagic's answer which reminded me about `y///`'s return value. Again.)

```
s|\w+|lc($&)=~y/aeiou//|ge

```
> 4 votes

# Answer
# JavaScript (*ES6*), 68

I/O via popup. Run the snippet in Firefox to test.

```
// As requested by OP

alert(prompt().replace(/\w+/g,w=>w.replace(/[^aeiou]/ig,'').length))

// Testable
f=s=>s.replace(/\w+/g,w=>w.replace(/[^aeiou]/ig,'').length)

test=[
 ['This is the first test case','1 1 1 1 1 2']
,['one plus two equals three','2 1 1 3 2']
,['aeiou AEIOU', '5 5']
]

out=x=>O.innerHTML+=x+'\n'

test.forEach(t=>{
  r=f(t[0])
  out('Test '+ ['Fail','OK'][0|r==t[1]]
      +'\nInput:  '+ t[0]
      +'\nOutput: '+r
      +'\nCheck:  '+t[1]+'\n')
})
```

```
<pre id=O></pre>
```
> 3 votes

# Answer
# Rebol - 70

```
print map-each n split input" "[c: 0 find-all n charset"aeiou"[++ c]c]

```
> 3 votes

# Answer
# Julia, ~~76~~ ~~72~~ ~~69~~ 65 bytes

```
for w=split(readline()) print(count(i->i∈"aeiouAEIOU",w)," ")end

```

Ungolfed + explanation:

```
# Read a string from STDIN and split it into words
s = split(readline())

# For each word in the string...
for w in s
    # Get the number of vowels of any case in the word
    c = count(i -> i ∈ "aeiouAEIOU", w)

    # Print the number of vowels identified
    print(c, " ")
end

```

This will include a single trailing space, which I'm told is legit.
> 3 votes

# Answer
## PowerShell, 35 bytes

```
%{($_-replace"[^aeiou]",'').length}

```

Kinda boring, but actually competing for once? (PowerShell is case insentitive by default, woo)
> 3 votes

# Answer
# Bash - 85

```
while read l;do for w in $l;do x=${w//[^aouieAOUIE]};echo -n ${#x}\ ;done;echo;done

```

## Explanation

* `read l` read one line from input
* `for w in l` splits the line into words using whitespace separator
* `x=${w//[^aouieAOUIE]/}` deletes all except vowels from the word
* `${#x}` is the length of resulting string === number of vowels
> 3 votes

# Answer
# Mathematica, 95 bytes

Not going to win any contests, but...

```
Print@StringRiffle[ToString[#~StringCount~Characters@"aeiouAEIOU"]&/@StringSplit@InputString[]]

```
> 2 votes

# Answer
# golflua, 55 bytes

```
~@W I.r():l():gm("%w+")_,c=W:g("[aeiou]",'')I.w(c,' ')$

```

Basic pattern matching of vowels after forced lowercase. An (ungolfed) Lua equivalent would be

```
line=io.read()
for word in line:lower():gmatch("%w+") do
   _,c=word:gsub("[aeiou]",'')
   io.write(c," ")
end

```
> 2 votes

# Answer
## **R**, 139 bytes

Read/write stdout() is terrible

```
s=function(x,y)strsplit(x,y)[[1]]
write(unlist(Map(function(x)sum(x%in%s("AIUEOaiueo","")),Map(s,s(readLines("stdin")," "),"")),),stdout())

```
> 2 votes

# Answer
# Python 3, 72 bytes

Inspired by @randomra's answer. It's ~~the same length~~ slightly longer, but using regex instead of list comprehension. It's also less readable.

```
import re
print(*map(len,re.sub("[^aeiou ]","",input(),0,2).split(" ")))

```
> 2 votes

# Answer
# PHP - 94

```
foreach(explode(' ',$argv[1]) as$d){preg_match_all('/[aeiou]/i',$d,$v);echo count($v[0]).' ';}

```

Ungolfed version

```
$a = explode(' ',$argv[1]);
foreach($a as $d) {
    preg_match_all('/[aeiou]/i', $d, $v);
    echo count($v[0]).' ';
}

```
> 2 votes

# Answer
# Objective-C, 223 bytes

```
-(void)p:(NSString*)s{NSArray*a=[s componentsSeparatedByString:@" "];for(NSString*w in a){int c=0;for(int i=0;i<w.length;i++){if([@"aeiouAEIOU"containsString:[w substringWithRange:NSMakeRange(i,1)]]){c++;}}NSLog(@"%d",c);}}

```

Not the most compact language, but it works.

Uncompressed version:

```
- (void)p:(NSString*)s{
    NSArray*a=[s componentsSeparatedByString:@" "];
    for (NSString*w in a) {
        int c=0;
        for (int i=0;i<w.length;i++) {
            if ([@"aeiouAEIOU" containsString:
                 [w substringWithRange:NSMakeRange(i, 1)]]) {
                c++;
            }
        }
        NSLog(@"%d",c);
    }
}

```
> 2 votes

# Answer
# Matlab, 73 bytes

Your challenge is not very clear (but it is interesting). I'm assuming

* By "vowel" you mean `a`, `e`, `i`, `o`, `u`.
* The string does not contain leading or trailing spaces

Code:

```
diff(find(regexprep([' ' input('','s') ' '],'[^aeiouAEIOU ]','')==' '))-1

```
> 2 votes

# Answer
# Haskell, ~~76~~ 68 bytes

```
f=interact$unwords.map(show.length).filter(`elem`"aeiouAEIOU").words

```

Straightforward implementation, not sure if there is anything to golf here.
> 2 votes

# Answer
# Perl, ~~60~~ 45

```
$/=" ";while(<>){$n=()=/[aeiou]/gi;print"$n "

```

Thanks to kirbyfan64sos for saving me 15 bytes - that really helped!
Note there's an extra space at the end of the output.
> 2 votes

# Answer
# rs, 50 bytes

This doesn't quite count; rs was uploaded around 2 weeks after this was posted. However, evidently this wouldn't win anything anyway, so it's still cool.

```
*[aeiou]/_
(^| )[^_\s]+ |$/ 0
[^_\s0]/
(_+)/(^^\1)

```

Live demo.

The implementation is rather straightforward:

```
*[aeiou]/_            Replace all vowels with underscores.
(^| )[^_\s]+ |$/ 0    Replace words that have no vowels with a zero.
[^_\s0]/              Remove all other letters.
(_+)/(^^\1)           Convert the underscore sequences into numbers (e.g. '___' to 3).

```
> 2 votes

# Answer
# APL (Dyalog Extended), 2̶9̶ 28 bytes

```
{+/¨(∊∘'aeiou'⊢)¨' '(≠⊆⊢)⌊⍵}
 +/¨ ⍝ sum each word's vowel bit array
    (∊∘'aeiou'⊢)¨ ⍝ for each word, check for vowels
       ' '(≠⊆⊢) ⍝ split string on spaces
          ⌊⍵ ⍝ convert to lowercase

```

-1 thanks to Razetime

Try it online!
> 2 votes

# Answer
# KDB(Q), 30 bytes

```
{sum@'lower[" "vs x]in"aeiou"}

```

# Explanation

```
            " "vs x              / split x string by space
      lower[       ]             / lower case
                    in"aeiou"    / check vowel
 sum@'                           / sum each booleans
{                            }   / lambda

```

# Test

```
q){sum@'lower[" "vs x]in"aeiou"}"This is the first test case"
1 1 1 1 1 2i

```
> 1 votes

# Answer
# Smalltalk - 66 72

This is in Smalltalk/X; the names for stdin and stdout may be different in squeak/pharo.

```
Stdin nextLine subStrings do:[:w|(w count:[:c|c isVowel])print.' 'print]

```

In Smalltalk/X (and many other dialects), symbols understand #value:, so it can be abbreviated to 66 chars:

```
 Stdin nextLine subStrings do:[:w|(w count:#isVowel)print.' 'print]

```

If coded as a function which get the string as argument "s":

```
[:s|s subStrings do:[:w|(w count:#isVowel)print.' 'print]]

```

Of course, in real code, one would use a utility function "f", which returns a vector of the counts, and print that. However, the output format is then not exactly what the challenge asked for:

```
f := [:s|s subStrings collect:[:w|(w count:#isVowel)]].
(f value: Stdin nextLine) print.

```
> 1 votes

# Answer
# Python 2, 76 bytes

I made this before I saw any other solution, then checked to find two P3 solutions that are shorter :( Darn P2 limitations.

```
print' '.join(`sum(y in'aeiouAEIOU'for y in x)`for x in raw_input().split())

```
> 1 votes

# Answer
# SAS, 72

```
data;infile stdin;file stdout;input c$@@;x=countc(c,'aeiou','i');put x@;

```

The restrictive I/O format for this one really hurts this one as it is responsible for 25 of the bytes here.
> 1 votes

# Answer
## PowerShell, 65 bytes

```
($input-split'\s'|%{($_-split''-match'a|e|i|o|u').count})-join' '

```

test by using the pattern below after saving as `vowels.ps1`

```
"the quick brown fox" | vowels.ps1

```

This way it is an actual script and not just a code snippet thereby satisfying constraint:

*"Input must be consumed from the stdin or command line arguments."*
> 1 votes

# Answer
# Jelly, 7 bytes

```
Ḳf€ØcL€

```

Try it online!

Found with help from Mr. Xcoder in chat

## Explanation

```
Ḳf€ØcL€ - Main link. Argument: s (a string)  e.g. "aeiou AEIOU"
Ḳ       - Split the input on spaces               ["aeiou", "AEIOU"]
   Øc   - Generate the string "AEIOUaeiou"
 f€     - Filter out consonants from €ach         ["aeiou", "AEIOU"]
     L€ - Length of €ach                          [5, 5]

```

If the output *must* be space-separated, then append a `K` to the end
> 1 votes

# Answer
# Arn `-a`, 22 bytes

```
(Ø-═É┤<LO¼‚R€Ê■ÊÕ'à¦┴%

```

My first Arn answer.

`-a` encloses the final array, separating the strings by spaces.

**Uncompressed:** `:s@+{"AEIOUaeiou":i&!!1+}\`

Arn has some trouble with strings, so this is a bit long.

you can omit the `-u` flag to give input directly through STDIN.

-13 bytes from Zippymagician.
> 1 votes

# Answer
# AWK, 42 bytes

```
BEGIN{RS=ORS=FS}$0=gsub(/[aeiouAEIOU]/,e)e

```

Try it online!

Regards each word as a different record (i.e., line), and substitute them for the count of vowels, calculated by the substitution function `gsub`. `e` is a dummy null variable, that, when appended to the number, makes awk parse it as string, so zero can be printed.
> 1 votes

# Answer
# Vyxal, 6 bytes

```
⌈ƛk∨↔L

```

Try it Online!

Explanation:

```
        # Implicit input
⌈       # Split input on ' '
 ƛ      # For each word in input:
  k∨↔   #   Remove all non-vowels
     L  #   Length of resulting string
        # Implicit output

```
> 1 votes

# Answer
# Vyxal, 4 bytes

```
⌈ƛA∑

```

Try it Online!

```
⌈    # Split on spaces
 ƛ   # Map...
  A  # Vowel mask (1 for vowel, 0 for not)
   ∑ # Sum

```
> 1 votes

# Answer
# C# 186

```
public class a{public static void Main(string[] a){Console.Write(string.Join(" ",Console.ReadLine().Split(' ').Select(x=>x.ToCharArray().Count(y=>"aeoui".ToCharArray().Contains(y)))));}}

```
> 0 votes

# Answer
# K (oK), 22 bytes

**Solution:**

```
(+/,/"aeiou"=\:)'" "\_

```

Try it online!

**Examples:**

```
> (+/,/"aeiou"=\:)'" "\_"This is the first test case"
1 1 1 1 1 2
> (+/,/"aeiou"=\:)'" "\_"aeiou AEIOU"
5 5

```

**Explanation:**

Interpretted right-to-left, lowercase input, split on whitespace, then check each word against each vowel, flatten and sum results:

```
(+/,/"aeiou"=\:)'" "\_ / the solution
                     _ / convert to lowercase
                 " "\  / split on " "
                '      / each
(              )       / do all this together
     "aeiou"=\:        / check each-left (\:) "aeiou" equal (=) to right argument
   ,/                  / flatten
 +/                    / sum

```
> 0 votes

# Answer
# Java 8, ~~137~~ 135 bytes

**As full program:**

```
interface M{static void main(String[]a){for(String s:a[0].split(" "))System.out.print(s.replaceAll("[^aeiouAEIOU]","").length()+" ");}}

```

Try it here.

**As function:**

A full program is apparently shorter than a function in this case (**137 bytes**):

```
v->{for(String s:new java.util.Scanner(System.in).nextLine().split(" "))System.out.print(s.replaceAll("[^aeiouAEIOU]","").length()+" ");}

```

Try it here.

**Explanation:**

```
interface M{                       // Class
  static void main(String[]a){     //  Mandatory main-method
    for(String s:a[0].split(" "))  //   Loop over the words of the input:
      System.out.print(s.replaceAll("[^aeiouAEIOU]","")
                                   //    Remove every non-vowel,
                        .length()  //    and print the length of the remainder
                       +" ");      //    + a space
                                   //   End of loop (implicit / single-line body)
  }                                //  End of main-method
}                                  // End of class

```
> 0 votes

# Answer
## Perl 5, 23 bytes

**19 bytes code + 4 for `-p040`.**

```
$_=lc=~y/aeiou//.$"

```

Try it online!
> 0 votes

# Answer
# Common Lisp, 74 bytes

```
(loop as i =(read)do(print(count-if(lambda(x)(find x"AEIOU"))(string i))))

```

Try it online!
> 0 votes

# Answer
# Japt v2.0a0, 5 bytes

```
mè\vS

```

Try it
> 0 votes

# Answer
# Python 3.8 (pre-release), 106 bytes

```
for x in input().upper().split():
 p=0
 for y in x:
  if 1065233>>(ord(y)-65)&1:
   p+=1
 print(p,end=" ")

```

Ehh, fairly long solution, but it's a start

Try it online!
> 0 votes

# Answer
# Thunno 2, 4 bytes

```
O€ṃʂ

```

Try it online!

Add the  flag if the input needs to be joined on spaces.

#### Explanation

```
O€ṃʂ  # Implicit input
O     # Split it on spaces
 €ṃ   # Then check if each is a vowel
   ʂ  # Sum each inner list
      # Implicit output

```
> 0 votes

---
Tags: code-golf, string, number
---


title: Shortest Floor Function

text:
# Question
Title: Shortest Floor Function
Your task is to implement a floor function in as few bytes as possible.

A floor function is a function that takes a real number and returns the largest integer less than or equal to the input.

Your program should support both positive and negative inputs. Since it is provably impossible to support all real numbers you need only support a reasonable subset of them. This subset should include positive numbers, negative numbers and of course numbers that are not integers. Such number systems include fixed-point numbers, floating point numbers and strings.

Your code may be a complete program or function.

This is so answers will be scored in bytes with less bytes being a better score.

# Answer
> 8 votes
### PARI/GP (10)

In gp (and some other languages) x%1 gives the decimal part of x:

```
f(x)=x-x%1

```

NOTE: For negative x, x%1 returns (1 - abs(decimal part of x)), so the above works both for positive and negative numbers.

# Answer
> 6 votes
## Javascript - 6 bytes

Usage of the arrow function declaration (as an anonymous function here) and a bitwise "AND" operator

```
x=>x&x

```

Try it online!

or alternatively using the bitwise "OR" operator:

```
x=>x|0

```

Try it online!

# Answer
> 5 votes
## JavaScript, ~~50~~ ~~34~~ ~~33~~ 32 characters

```
function f(n){return~~n-(~~n>n)}

```

Works the same way as the PHP one I submitted.

# Answer
> 5 votes
# Python (20)

```
f=lambda x:int(x//1)

```

or, if the result doesn't need to be of type `int`, 15 characters:

```
f=lambda x:x//1

```

# Answer
> 4 votes
## DC (15 bytes)

Makes use of a nifty little trick that occurs during division in DC. Add a 'p' to then end to get output (it performs the floor correctly anyway), I assume that stuff is not already on the stack, and that input is in stdin.

```
[1-]sazk?z/d0>a

```

EG: `echo 0 2.6 - | dc -e '[1-]sazk?z/d0>ap'`

# Answer
> 4 votes
# Python (81)

```
def f(x):return str(x - float("." + str(float(x)).split('.')[-1])).split('.')[0]

```

# Answer
> 3 votes
### C (51)

```
int F(float x){int i=x-2;while(++i<=x-1);return i;}

```

# Answer
> 3 votes
### LISP (26)

(Same trick as in PARI/GP answer)

```
(defun f(x)(- x(mod x 1)))

```

# Answer
> 3 votes
## C 126 (including NL)

Doesn't use any built-in conversion such as `(int)x`.

```
r(float x) {
int
p=*(int*)&x,
f=p&8388607|1<<23,
e=((p>>23)&255)-150;
if(e>0)f*=1<<e;
if(e<0)f/=1<<-e;
return p>>31?-f-1:f;
}

```

# Answer
> 3 votes
## C (80)

Well it's not the shortest, but it's a great opportunity to show off my bit twiddling skills :D.

```
main(){int I,X=0x7FFFFF;scanf("%f",&I);printf("%d",((I&X)|X+1)>>-(I>>23)+150);}

```

# Answer
> 3 votes
## J 7 chars

```
f=:-1&|  NB. x - (x mod 1)

```

eg.

```
f 3.14
3
f _3.14
_4

```

# Answer
> 3 votes
# C, ~~42~~ 41 bytes

```
int F(float x){int i=x;return i<=x?i:i-1;}

```

Try it online!

```
int F(float x){int i=x;return x>i?i:i-1;}

```

Try it online!

# Answer
> 2 votes
**Ruby 1.9 (12 14)**

```
 f=->x{x-x%1}

```

It's more a "for the record" type solution along the lines of the PARI/GP one.

```
>> f[3.4] #=> 3.0
>> f[-3.4] #=> -4.0

```

# Answer
> 2 votes
# APL, 1 byte (SBCS)

According to the updated rules, built-ins are allowed:

# APL (dzaima/APL), ~~5~~ 4 bytes

Anonymous tacit prefix function abiding by the old prohibition on built-ins:

```
⊢-1|

```

Try it online!

the argument

`-` minus

`1|` the division remainder when divided by 1

# Answer
> 2 votes
# Julia, 17 bytes

```
f(x)=x-x%1-(x<0)

```

port of the PARI/GP answer

```
f(-pi) = -4
f(pi) = 3

```

# Answer
> 2 votes
# Turing Machine Code, 39 bytes

```
0 * * r 0
0 _ _ l 1
1 * _ l 1
1 . _ l 2

```

Try it online!

# Answer
> 1 votes
**C# (56 chars):**

My quick and naive answer earlier had a stupid logical flaw in it. Two approaches here, which I believe are both the same length. Double approach relies on the fact that casting to int removes the decimal part of a double.

```
int F(double d){return(int)(d%1==0?d:(int)d-(d<0?1:0));}

```

Decimal approach relies on the fact that d%1 returns the decimal part of the number for decimal data type.

```
int F(decimal d){return(int)(d%1==0?d:d-d%1-(d<0?1:0));}

```

Could save a few characters in both cases by returning their own type instead of int, but I feel a floor function should return an int.

# Answer
> 1 votes
## PHP, ~~51~~ ~~45~~ ~~43~~ 37 characters

```
function f($n){return~~$n-(~~$n>$n);}

```

This should be able to be applied to most languages that do not support the `n%1` trick.

# Answer
> 1 votes
## Perl (23)

```
$_=int($_)-(int($_)>$_)

```

**Example:**

```
perl -ple '$_=int($_)-(int($_)>$_)'

```

Every value entered on input will now be printed "floored".

Its bass5098's technique, but smaller =).

### As a function(36):

```
sub f{int($_[0])-(int($_[0])>$_[0])}

```

# Answer
> 1 votes
# Java 8, 19 bytes

Lambda from `double` to `int`. There are plenty of choices for types to assign to: `Function<Double, Integer>`, `DoubleFunction<Integer>`, or `DoubleToIntFunction`.

```
n->(int)(n<0?n-1:n)

```

Try It Online

# Answer
> 1 votes
# RProgN 2, 4 bytes

```
]1%-

```

## Explained

```
]1%-
]   # Duplicate the implicit input
 1% # Modulo 1
   -# Subtract Modulo 1 of the input from the input, inplicitly outputting the floor'd result.

```

Try it online!

# Answer
> 1 votes
# x86\_64 machine language (Linux), 11 bytes

```
0:       c4 e3 79 0b c0 01       vroundsd $0x1,%xmm0,%xmm0,%xmm0
6:       f2 0f 2c c0             cvttsd2si %xmm0,%eax
a:       c3                      retq

```

This requires a processor with AVX instructions.

To Try it online!, compile and run the following C program.

```
#include<stdio.h>
#include<math.h>
int f(double x){return floor(x);}
const char g[]="\xc4\xe3\x79\x0b\xc0\x01\xf2\x0f\x2c\xc0\xc3";

int main(){
  for( double d = -1.5; d < 1.5; d+=.2 ) {
    printf( "%f %d %d\n", d, f(d), ((int(*)(double))g)(d) );
  }
}

```

# Answer
> 1 votes
# 05AB1E, 2 bytes

Try it online or verify all values in the range \\$\[5,-5\]\\$ in \\$0.1\\$ increments.

**Explanation:**

```
O   # Sum the stack, which will use the (implicit) input-string if the stack is empty
    # (the input is read as string by default, so this `O` basically casts it to a float)
 ï  # Floor this input-float
    # (and output the resulting integer implicitly)

```

Although it may look pretty straight-forward, there are actually some things to note:

In the legacy version of 05AB1E, which was built in Python. The `ï` builtin would translate to the following code snippets:

```
# Pop number
a = str(number)         # Cast number to a string
a = ast.literal_eval(a) # Evaluate this string as Python structure (so it goes back to a float)
a = int(a)              # Cast this float to an integer (which will truncate)

```

So whether you had string input or decimal input, it would cast it to a string during the code execution anyway, before casting it to an integer to truncate all decimal values.

Try it online with `-0.5` as decimal argument.
Try it online with `"-0.5"` as string argument.

The new version of 05AB1E is built in Elixir however. Now, the `ï` builtin translates to the following code snippets (huge parts removed to only keep the relevant stuff):

```
call_unary(fn x -> to_integer(x) end, a)      # Call the function `to_integer`, which will:
                                              # (I've only kept relevant parts of this function)
 is_float(value) -> round(Float.floor(value)) #  If it's a float: floor it down
 true ->                                      #  Else (it's a string):
     case Integer.parse(to_string(value)) do  #   Parse it from string to integer
        :error -> value                       #   If this resulted in an error: return as is
        {int, string} ->
            cond do                           #   Else it was parsed without errors:
                Regex.match?(~r/^\.\d+$/, string) -> int
                                              #    If it contains no decimal values:
                                              #      Return parsed int
                true -> value                 #    Else: return as is

```

Or as a TL;DR: float inputs are floored; string inputs are truncated.

Try it online with `-0.5` as decimal argument.
Try it online with `"-0.5"` as string argument.

As you can see, a string input gives the incorrect floored result for negative decimals. Unfortunately, the default (implicit) input from STDIN is always a string, so we'll have to convert it to a float first (for which I've used `O` \- which only works on an empty stack in the new 05AB1E version built in Elixir; for the legacy 05AB1E version built in Python, the sum would result in `0` for an empty stack).

# Answer
> 1 votes
# Excel, 7

Tested in Excel Online. Closing parens not counted toward score.

The only reason I posted this is because, oddly enough, it seems to work the exact same as `FLOOR.MATH()` with 1 argument.

```
=INT(A1)

```

Semantically, at least to me, it would make sense if this didn't work for negative numbers. However, `INT(-.5)` is `-1` for some reason. `TRUNC()` does what I think `INT()` should do.

# Answer
> 1 votes
# C (gcc), ~~16~~ 15 bytes

```
g;f(d){g=d>>9;}

```

Try it online!

> Such number systems include **fixed-point numbers**, floating point numbers and strings.

I don't know why people insist on using floats... Fixed point is much easier

Uses 32-bit fixed9 precision. Abuses arithmetic shift right. Return hack, not much else to say.

# Answer
> 1 votes
# x86-64 machine code, 7 bytes

Machine code:

```
00000000: 66 0f 3a 0b c0 01 c3                             f.:....

```

Assembly:

```
        .intel_syntax noprefix
        .globl floor_sse4
floor_sse4:
        roundsd xmm0, xmm0, 1
        ret

```

Try it online!

Accepts a `double` in an `xmm0`.

Returns the floored `double` in `xmm0`.

Outgolfs the previous answer without cheesing with fixed point.

* Nowhere did it say the return type had to be an `int`, just an *integer*. Therefore, I can just skip the conversion code, storing the integer as a `double`. JavaScript has been doing it for decades.
* This one only requires SSE4.1.

Yes, I know the SSE conversion functions are a little redundant in the test code.

# x86-64 machine code, fixed point joke, 1 byte

Machine code:

```
00000000: c3                                               .

```

Assembly:

```
        .intel_syntax noprefix
        .globl floor_fixed
floor_fixed:
        ret

```

Try it online!

This function takes a 16-bit fixed8 in `ax` and returns a signed 8-bit integer in `ah`. It is not sign extended.

Nobody gave any specifics about precision

# Answer
> 1 votes
# Vyxal, 3 bytes

```
1%-

```

Push input, modulo with 1 and negate!

Try it!

# Vyxal, 1 byte

Though a builtin.....

Try it!

# Answer
> 1 votes
# Hexagony, 31 bytes

```
,{.4{?<.(@!?\"!3'-<_".$>@>?~..@

```

```
    , { . 4
   { ? < . (
  @ ! ? \ " !
 3 ' - < _ " .
  $ > @ > ? ~
   . . @ . .
    . . . .

```

Try it online! or Try it online differently!

Takes input of the form `+/-a.b`, ex: `+4.5` or `-0.1` or `+3.` Since hexagony doesn't have built in decimal types, the input must contain a `+` if positive in order to not cut off the first digit of the number. This answer can definitely be improved, but its a start.

# Answer
> 1 votes
# floor, 5 bytes

`floor`

The floor function is a (the only) built-in.

## Full program (17 bytes):

Floor only accepts integers as program Input, so the program uses two inputs to generate a rational number to be passed to the floor function

`f:x y->floor(x/y)`

implementation

# Answer
> 0 votes
# Python, 13

If the OP wants all functions to be non-anonymous, add `f=` to the front of each for two additional characters.

```
lambda x:x//1

```

Since `x%1` returns the amount following the decimal point, this is pretty short (14):

```
lambda x:x-x%1

```

The shortest using string casting I could come up with (40):

```
lambda x:int(`x`.split('.')[0])+cmp(x,0)

```

# Answer
> 0 votes
# MATL, 5 bytes

*The programming language used in this answer was created after the challenge was posted.*

```
it1\-

```

### Examples

```
>> matl it1\-
> 5.6
5

>> matl it1\-
> -5.2
-6

```

### Explanation

Pretty straightforward. It uses a modulo operation with divisor `1`.

```
i      % input
t      % duplicate
1      % number literal
\      % modulus after division
-      % subtraction

```

# Answer
> 0 votes
# Mouse-2002, 13 bytes

Second place, ahh! (And this is a full program, not a function definition)

```
?&DUP &FRAC -

```

Take the fractional bit of the input and subtract it from the input.

# Answer
> 0 votes
# Perl 5, 22 bytes

```
s/\..+//&&$_<0?$_--:$_

```

This is larger than my first answer, which merely truncated the number - so, for negative numbers, it wasn't correct. This was due to a misunderstanding on my part of what a floor function does.

# Answer
> 0 votes
# RProgN, 1 byte

```
_

```

A builtin, thanks to the new challenge spec.

Try it online!

# Answer
> 0 votes
# AArch64 machine language (Linux), 8 bytes

```
0: 1e700000 fcvtms w0, d0
4: d65f03c0 ret

```

To try it out, compile and run the following C program

```
#include<stdio.h>
#include<math.h>
int f(double x){return floor(x);}
const char g[]="\x00\x00\x70\x1e\xc0\x03\x5f\xd6";

int main(){
  for( double d = -1.5; d < 1.5; d+=.2 ) {
    printf( "%f %d %d\n", d, f(d), ((int(*)(double))g)(d) );
  }
}

```

# Answer
> 0 votes
# Wren, 16 bytes

Exactly ported from the PARI/GP answer.

```
Fn.new{|x|x-x%1}

```

Try it online!

# Wren, 26 bytes

Ported from the Keg answer.

```
Fn.new{|x|x.split(".")[0]}

```

Try it online!

# Answer
> 0 votes
# Keg, ~~6~~ ~~5~~ 4 bytes

```
:1%-

```

Try it online!

 Look ma, no unicode!

A port of the RProgN2 answer

# Answer
> 0 votes
# Jelly, 1 byte

Try it online!

or a non-builtin answer

```
%1_@

```

Try it online!

## How the second one works

```
%1_@ - Main link. Takes n on the left
%1   - Fractional part of n
  _@ - n - frac(n)

```

# Answer
> 0 votes
# Python 3, 15 bytes

```
f=lambda n:n//1

```

Try it online!

# Answer
> 0 votes
# Lua, 27 25 18 15 bytes

```
print(...//1|0)

```

Try it online!

### Explanation

`...` variable-argument operator, returns the remaining arguments passed to the current function (top-level code block with all the program arguments in this case).

`//1` floor divides by 1.

`|0` bitwise OR, we use this to convert to an int.

# Answer
> 0 votes
# Pyth, 3 bytes

```
/Q1

```

Try it online!

# Answer
> 0 votes
# MMIX, 8 bytes (2 instrs)

```
05000300 F8010000

```

**Disassembly**

```
    FIX $0,ROUND_DOWN,$0
    POP 1,0

```

MMIX has a builtin instruction for this. You can specify the rounding mode if you like, but you can use the default. (Options are towards 0, towards \\$-\infty\\$, towards \\$\infty\\$, or to nearest half to even.)

Honestly, I'd advise using a `FIX` directly, as opposed to calling.

# Answer
> 0 votes
# ARBLE, 4 bytes

```
n//1

```

Try it online!

Outputs with a leading `.0`. If this is forbidden, then...

# ARBLE, 5 bytes

```
floor

```

Try it online!

# Answer
> 0 votes
# Thunno 2, 2 bytes

Try it online!

Floor divide by one.

Funnily enough, Thunno 2 doesn't have a proper floor built-in. For positive numbers, you can use `N` (truncate), but that doesn't work for negative numbers.

---
Tags: code-golf
---


title: Make some Alphabet Rain

text:
# Question
Title: Make some Alphabet Rain
# Alphabet Rain

## The Task:

The basic premise is to print out the input string and then repeat each character vertically, based on it's (0-indexed) position in the (case-insensitive) alphabet `A-Z`. `A` is at location 0 so is not repeated, `e` is at position 4 so is repeated 4 times, `P` is at position 15 so is repeated 15 times, `!` is not in `A-Z` so is repeated 0 times, etc.

For clarity, anything that falls outside of the range `B-Zb-z`, for example digits or special characters, will not be repeated, and thus will only appear on the first line.

This is , so shortest solution in each language is the winner.

## Input:

* Input will be in the standard printable ASCII character set, from 32  up to 126 `~`.
* The input string will be 1 character long or longer.
* There will not be any leading or trailing whitespace.
* You can take take input as a string (`"hello"`) or list of characters ( `["h", "e", "l", "l", "o"]`)

## Examples:

Input of `aaaa` gives:

```
aaaa

```

Input of `abcda` gives:

```
abcda
 bcd
  cd
   d

```

Input of `Programming Puzzles & Code Golf!`, gives:

```
Programming Puzzles & Code Golf!
Progr mming Puzzles   Code Golf
Progr mming Puzzles   Code Golf
Progr mming Puzzles    ode Golf
Progr mming Puzzles    o e Golf
Progr mming Puzzl s    o   Golf
Progr mming Puzzl s    o   Gol
Pro r mmin  Puzzl s    o    ol
Pro r mmin  Puzzl s    o    ol
Pro r mm n  Puzzl s    o    ol
Pro r mm n  Puzzl s    o    ol
Pro r mm n  Puzzl s    o    ol
Pro r mm n  Puzz  s    o    o
Pro r    n  Puzz  s    o    o
Pro r       Puzz  s    o    o
Pr  r       Puzz  s
 r  r        uzz  s
 r  r        uzz  s
             uzz  s
             uzz
             uzz
              zz
              zz
              zz
              zz
              zz

```

Input of `~|[abc<0>cba]|~`, gives:

```
~|[abc<0>cba]|~
    bc   cb
     c   c

```

## Notes:

* standard loopholes apply
* output *can* be a list of strings, but:
* extraneous trailing newlines are not allowed (single `\n` on final line is acceptable)
* output *can* be a list of lists of characters, so long as it looks like it's raining characters
* no leading newline
* to our Nordic users who have a few extra letters in their "A-Z" alphabet, feel free to support them, but it's not part of the challenge

# Answer
# 6502 machine code (C64), 113 bytes

```
00 C0 20 FD AE 20 9E AD 85 FB 20 A3 B6 A0 00 84 FC B1 22 99 6F C1 C9 41 90 14
C9 5B B0 04 E9 40 B0 0E C9 C1 90 08 C9 DB B0 04 E9 C0 B0 02 A9 00 99 6F C0 C5
FC 30 02 85 FC C8 C4 FB D0 D3 A9 00 99 6F C1 A0 C1 A9 6F 20 1E AB A9 0D 20 D2
FF A6 FC D0 01 60 C6 FC A0 00 B9 6F C1 F0 E6 BE 6F C0 D0 07 A9 20 99 6F C1 D0
05 CA 8A 99 6F C0 C8 D0 E7

```

**Online demo**

**Usage:** `sys49152,"[string]"`, e.g. `sys49152,"Programming Puzzles & Code Golf!"`.

**Important:** If the program was loaded from disk (like in the online demo), issue a `new` command first! This is necessary because loading a machine program trashes some C64 BASIC pointers.

**Note:** The C64 is by default in a mode without lowercase letters -- in order to be able to enter a mixed-case string, switch to lowercase mode first by pressing `SHIFT`+`CBM`.

---

### Explanation

Here's a commented disassembly listing:

```
         00 C0       .WORD $C000        ; load address
.C:c000  20 FD AE    JSR $AEFD          ; consume comma
.C:c003  20 9E AD    JSR $AD9E          ; evaluate expression
.C:c006  85 FB       STA $FB            ; store string length
.C:c008  20 A3 B6    JSR $B6A3          ; free string
.C:c00b  A0 00       LDY #$00           ; initialize counter
.C:c00d  84 FC       STY $FC            ; and number of "extra" lines
.C:c00f   .copyloop:
.C:c00f  B1 22       LDA ($22),Y        ; load next character
.C:c011  99 6F C1    STA .outbuf,Y      ; store to buffer
.C:c014  C9 41       CMP #$41           ; compare with 'a'
.C:c016  90 14       BCC .zerocount     ; smaller -> no repetition
.C:c018  C9 5B       CMP #$5B           ; compare with 'z'
.C:c01a  B0 04       BCS .checkupper    ; larger -> check for uppercase
.C:c01c  E9 40       SBC #$40           ; subtract 'a' ('a' - 1 and carry)
.C:c01e  B0 0E       BCS .cl_storecount ; and jump to store in repeat count
.C:c020   .checkupper:
.C:c020  C9 C1       CMP #$C1           ; compare with 'A'
.C:c022  90 08       BCC .zerocount     ; smaller -> no repetition
.C:c024  C9 DB       CMP #$DB           ; compare with 'Z'
.C:c026  B0 04       BCS .zerocount     ; larger -> no repetition
.C:c028  E9 C0       SBC #$C0           ; subtract 'A' ('A' - 1 and carry)
.C:c02a  B0 02       BCS .cl_storecount ; and jump to store in repeat count
.C:c02c   .zerocount:
.C:c02c  A9 00       LDA #$00           ; store 0 ...
.C:c02e   .cl_storecount:
.C:c02e  99 6F C0    STA .repcount,Y    ; ... in repeat count
.C:c031  C5 FC       CMP $FC            ; compare with number of extra lines
.C:c033  30 02       BMI .cl_next       ; smaller -> go on with loop
.C:c035  85 FC       STA $FC            ; repeat count to number of extra lines
.C:c037   .cl_next:
.C:c037  C8          INY                ; next
.C:c038  C4 FB       CPY $FB            ; compare with string length
.C:c03a  D0 D3       BNE .copyloop      ; not yet reached? -> repeat
.C:c03c  A9 00       LDA #$00           ; terminate string in buffer
.C:c03e  99 6F C1    STA .outbuf,Y      ; with 0 byte
.C:c041   .outloop:
.C:c041  A0 C1       LDY #>.outbuf      ; output ...
.C:c043  A9 6F       LDA #<.outbuf      ; ...
.C:c045  20 1E AB    JSR $AB1E          ; ... string
.C:c048  A9 0D       LDA #$0D           ; and output ...
.C:c04a  20 D2 FF    JSR $FFD2          ; ... newline
.C:c04d  A6 FC       LDX $FC            ; load extra line count
.C:c04f  D0 01       BNE .ol_step       ; not zero -> go on
.C:c051  60          RTS                ; WE ARE DONE HERE ;)
.C:c052   .ol_step:
.C:c052  C6 FC       DEC $FC            ; decrease extra line count
.C:c054  A0 00       LDY #$00           ; initialize counter
.C:c056   .eraseloop:
.C:c056  B9 6F C1    LDA .outbuf,Y      ; load next character from buffer
.C:c059  F0 E6       BEQ .outloop       ; 0 byte? -> end of string, output
.C:c05b  BE 6F C0    LDX .repcount,Y    ; load repeat count for this characer
.C:c05e  D0 07       BNE .el_step       ; not 0 yet? -> jump to decrement
.C:c060  A9 20       LDA #$20           ; load code for space
.C:c062  99 6F C1    STA .outbuf,Y      ; store in current string position
.C:c065  D0 05       BNE .el_next       ; and jump to next loop iteration
.C:c067   .el_step:
.C:c067  CA          DEX                ; decrease repeat count ...
.C:c068  8A          TXA                ; ... and ...
.C:c069  99 6F C0    STA .repcount,Y    ; ... store back
.C:c06c   .el_next:
.C:c06c  C8          INY                ; increase counter ...
.C:c06d  D0 E7       BNE .eraseloop     ; and jump back to loop

.C:c06f   .repcount:
.C:c06f              .RES $100          ; 256 bytes for repeat count
.C:c16f   .outbuf:
.C:c16f              .RES $100          ; 256 bytes as buffer for output

```
> 22 votes

# Answer
# 05AB1E, ~~13~~ 12 bytes

```
,εDlAsk×}ζ»,

```

Try it online!

**Explanation**

```
,             # print input
 ε      }     # apply to each char in input
  D           # duplicate
   l          # convert to lower case
    Ask       # get index of current char in the lower case alphabet
       ×      # repeat the char that many times
         ζ    # transpose with space as filler
          »,  # join on newlines and print

```
> 15 votes

# Answer
# Pyth, ~~12~~ ~~10~~ 9 bytes

```
.tm+*xGr0

```

Test suite.

Explanation:

```
.tm+*xGr0dddQ   Expanded program with autofilled input variable
  m      dddQ    For each character d in the input:
       r0d     get its lowercase variant
     xG        and return its 0-based index in the alphabet
                   (-1 if not found, for special chars)
                (empty string for A/a and special characters)
    *     d    that many of the corresponding character
   +       d   and one more for good measure (because x is 0-indexed)
.t             Transpose it and fill blanks with spaces

```

12 bytes:

```
j.t*VmxGr0d

```

(with trailing newline)

Test suite.

Explanation:

```
j.t*VmxGr0d
QQ              Expanded program with autofilled input variable
Q               print the input verbatim
     m    dQ    For each character d in the input:
        r0      get its lowercase variant
      xG        and return its 0-based index in the alphabet
                    (-1 if not found, for special chars)
   *V       Q   multiply the corresponding characters in (the second autofilled input)
                 by their alphabet indices we just calculated
                 (empty string for A/a and special characters)
 .t             Transpose it and fill blanks with spaces
j               Join the result on newlines

```
> 8 votes

# Answer
# Python 3, 83 bytes

```
f=lambda s,k=65:[*{*s}-{' '}]and[s]+f([[' ',c][91>ord(c.upper())>k]for c in s],k+1)

```

Try it online! Takes a list of characters. Returns a list of lists of characters.

## Python 2, 90 bytes

```
f=lambda s,k=65:s.strip()and s+'\n'+f(''.join([' ',c][91>ord(c.upper())>k]for c in s),k+1)

```

Try it online! Takes a string. Returns a string.
> 8 votes

# Answer
# Mathematica, ~~115~~ 89 bytes

It takes as `input` a **list of characters** `[{"a", "b", "c", "d", "a"}]` and outputs **a list of lists of characters**

```
Thread[PadRight[Table[#,Max@Position[Alphabet[]/."a"->#,#|ToLowerCase@#]]&/@#]/. 0->" "]&

```

Try it online!

*-26 bytes from Misha Lavrov*

*-5 bytes from user202729*

but if you want to see the output as it is in the test case, try this (128 bytes) code
Try it online!
> 7 votes

# Answer
# Dyalog APL, ~~27~~ 22 bytes

*5 bytes saved thanks to @Adám*

```
⍉∘↑⊢⍴¨⍨1⌈27|⎕A⍳819⌶⍨∘1

```

Try it online!

**How?**

`⍴¨⍨` \- shape each char to length of

`1⌈` \- at least one or

`⎕A⍳819⌶⍨∘1` \- index of the char uppercased in alphabet

`27|` \- modulo 27

\- flatten to a matrix

\- and transpose
> 6 votes

# Answer
# Charcoal, 12 bytes

```
θ↙↓Ｅ⮌θ×ι⌕α↥ι

```

Try it online!

-3 thanks to Neil.
> 6 votes

# Answer
# Python 2, ~~111~~ ~~106~~ ~~99~~ ~~98~~ ~~97~~ ~~87~~ 93 bytes

```
s=input()
i=65
while s.strip():print s;s=''.join([' ',c][91>ord(c.upper())>i]for c in s);i+=1

```

Try it online!
> 5 votes

# Answer
# Python, ~~105~~ 103 bytes

*2 bytes saved thanks to @TFeld*

```
lambda s:'\n'.join(''.join((' '+l)[i<1or 91>ord(l.upper())>i+64]for l in s)for i in range(26)).rstrip()

```

Try it online!
> 5 votes

# Answer
# C# (.NET Core), 162 bytes

```
s=>{string A="abcdefghijklmnopqrstuvwxyz",r=s;for(int i=-1;++i<s.Max(A.IndexOf);)r+='\n'+string.Concat(s.Select(c=>A.IndexOf(char.ToLower(c))>i?c:' '));return r;}

```

Try it online!
> 5 votes

# Answer
# Bash, ~~78~~, ~~76~~ 71 bytes

```
for c in {B..a};{ [[ -n ${1// } ]]&&echo "$1";set "${1//[!$c-Z${c,}-z]/ }";}

```

Depending on collation (default LC\_ALL) can save some more bytes

```
for c in {b..z} _;{ [[ -n ${1// } ]]&&echo "$1";set "${1//[!$c-Z]/ }";}

```

Try It Online
> 5 votes

# Answer
# Perl 5, 43 bytes

**41 bytes code + 2 for `-nl`.**

```
$c=A;print,s/$c|[^a-z]/ /gi,$c++while/\S/

```

Try it online!
> 4 votes

# Answer
# JavaScript (ES6), ~~87~~ ~~78~~ 76 bytes

*-9 bytes thanks to @RickHitchcock.*
*-2 bytes thanks to @Neil.*

```
f=(s,i=10)=>s.trim()&&s+`
`+f(s.replace(/./g,c=>parseInt(c,36)>i?c:" "),i+1)

```

Takes input as a string and returns with one trailing newline.

## Test Cases

```
f=(s,i=10)=>s.trim()&&s+`
`+f(s.replace(/./g,c=>parseInt(c,36)>i?c:" "),i+1)

;["hello", "Programming Puzzles & Code Golf!", "~|[abc<0>cba]|~", "abcdefg0123456789"]
.forEach(s=>console.log(f(s)));
```

```
.as-console-wrapper{max-height:100%!important}
```
> 4 votes

# Answer
# , ~~125~~ 123 bytes

*Outgolfed by plannapus*

```
for(i in 1:max(p<-pmax(1,match(tolower(S<-el(strsplit(scan(,""),''))),letters),na.rm=T)))cat(ifelse(p<i," ",S),'\n',sep='')

```

Try it online!

Prints to stdout with a single trailing newline and reads from `stdin()`.

Let's break it down:

```
S <- el(strsplit(scan,""))            # split the string to characters

m <- match(tolower(S),letters)        # 1-based index in letters (lowercase a-z)
p <- pmax(1,m,na.rm=T)                # parallel max, replaces NA (non-alphabet) or 0 with 1
for(i in 1:max(p)){                   # iterate
 cat(                                 # print
  ifelse(p<1,' ',S),                  # the corresponding letter in S if p>=1, space otherwise
  '\n',sep='')                        # newline, and no spaces between chars
}

```

## Alternate answer, 106 bytes

```
function(S)for(i in 1:max(p<-pmax(1,match(tolower(S),letters),na.rm=T)))cat(ifelse(p<i,' ',S),'\n',sep='')

```

Try it online!

Function; prints to stdout but it's basically my response above ported to accept a list of characters rather than splitting the string, so I feel like it's "cheating." Plus, plannapus' approach with regex is quite neat!
> 4 votes

# Answer
# Octave / MATLAB, ~~74~~ 66 bytes

```
@(s)char(arrayfun(@(c){repmat(c,1,prod(find(upper(c)==65:90)))},s))'

```

**Try it online!**
> 4 votes

# Answer
# R, ~~118~~ 114 bytes

```
function(a)while(grepl("[^ ]",a)){F=F+1;cat(a,"\n");for(j in c("[^a-zA-Z]",letters[F],LETTERS[F]))a=gsub(j," ",a)}

```

Thanks to @Giuseppe for those 4 bytes off

Try it online!

Short explanation:

```
function(a)
    while(grepl("[^ ]",a)){ #As long as the string is not just spaces.
        F=F+1 #Increment letter counter (F is FALSE, hence 0 by default)
        cat(a,"\n") #Print string
        for(j in c("[^a-zA-Z]",letters[F],LETTERS[F])) #Get rid of non-letters, and the current letter in lower and upper case
             a=gsub(j," ",a)
    }

```
> 4 votes

# Answer
# PHP, ~~69 78 77~~ 85+1 bytes

```
for($c=A;!$c[1]&&~trim($s=&$argn);$s=eregi_replace("[^".++$c."-Z]"," ",$s))echo"$s
";

```

requires PHP\<7. Run as pipe with `-nR` or try it online.
> 3 votes

# Answer
# Japt, ~~15~~ ~~14~~ ~~11~~ 10 bytes

First chance to play with Japt's new string padding methods so there might still be room for improvement.

```
y_ùZInZu c

```

Try it

---

## Explanation

Implicit input of string `U`.

```
y_

```

Pass each column of `U` through a function, where `Z` is the current element (or letter, in this case).

```
InZu c

```

Convert `Z` to uppercase (`u`), get its charcode (`c`) and subtract (`u`) 64 (`I`).

```
ùZ

```

Pad the start of `Z` with itself until it reaches that length.

---

## Alternative

```
y_ùZ9aZn36

```

Try it
> 3 votes

# Answer
# Haskell, ~~137~~ ~~136~~ ~~127~~ 119 bytes

```
import Data.Char
p c=last$0:[k|k<-[0..25],k+65==ord(toUpper c)]
f s=[[last$c:[' '|i>p c]|c<-s]|i<-[0..maximum$map p s]]

```

Try it online!

Pretty long but I can't think of any way to shorten it further. ~~I feel like there must be some way shorter than the if-then syntax but I don't see it.~~

EDIT: Thanks @streetster for helping me shave off one byte! I didn't use `toUpper` at first because of the cost of importing `Data.Char` but I forgot that it also provides `ord` which is much shorter than `fromEnum`

EDIT 2: Thanks to @Laikoni for shaving off another 6 bytes and identifying a bug which I have now fixed. I used 26 instead of 25 because I forgot that Haskell arrays are inclusive. Then I noticed I could use `last` instead of `head` which would allow me to use `0:` rather than `++[0]`.

EDIT 3: Thanks again Laikoni for those 8 bytes. I had actually forgotten about that space. For some reason Sublime Text flips out without it and I forgot to remove it. I wasn't aware that lists of lines were allowed, I should've read the rules more carefully.
> 3 votes

# Answer
# Excel VBA, 110 Bytes

Anonymous VBE Immediate Window Function that takes input as expected type `Variant\String` from range `[A1]` and uses it to make it rain the alphabet in the VBE immediate window.

```
?[A1]:For i=1To 26:For j=1To[Len(A1)]:c=Mid([A1],j,1):d=Asc(UCase(c)):?IIf((d>64+i)*(d<91),c," ");:Next:?:Next

```

### Sample I/O

```
[A1]="qwertyuiop[]ASDFGHJKL:'zxcvbnm,./"
?[A1]:For i=1To 26:For j=1To[Len(A1)]:c=Mid([A1],j,1):d=Asc(UCase(c)):?IIf((d>64+i)*(d<91),c," ");:Next:?:Next
qwertyuiop[]ASDFGHJKL:'zxcvbnm,./
qwertyuiop   SDFGHJKL  zxcvbnm
qwertyuiop   SDFGHJKL  zxcv nm
qwertyuiop   SDFGHJKL  zx v nm
qwertyuiop   S FGHJKL  zx v nm
qw rtyuiop   S FGHJKL  zx v nm
qw rtyuiop   S  GHJKL  zx v nm
qw rtyuiop   S   HJKL  zx v nm
qw rtyuiop   S    JKL  zx v nm
qw rtyu op   S    JKL  zx v nm
qw rtyu op   S     KL  zx v nm
qw rtyu op   S      L  zx v nm
qw rtyu op   S         zx v nm
qw rtyu op   S         zx v n
qw rtyu op   S         zx v
qw rtyu  p   S         zx v
qw rtyu      S         zx v
 w rtyu      S         zx v
 w  tyu      S         zx v
 w  tyu                zx v
 w   yu                zx v
 w   y                 zx v
 w   y                 zx
     y                 zx
     y                 z
                       z

```
> 3 votes

# Answer
# Bash + sed, 37

```
sed -rne"/^ *$/q;p;s/\W|"{a..z}/\ /gi

```

Try it online.
> 3 votes

# Answer
## Ruby, ~~70~~ ~~67~~ 74 bytes

```
f=->s{puts s;(?b..?z).each{|c|s.gsub! /[^#{c}-z]/i,' ';puts s if s=~/\S/}}

```

Thanks to @TuukkaX for pointing out some parens could be dropped (-3 bytes)

Unfortunately I then had to add 7 bytes because original version failed to handle "z".

Calling it:

```
f.call('The quick brown fox jumps over the lazy dog!')
The quick brown fox jumps over the lazy dog!
The quick brown fox jumps over the l zy dog
The quick  rown fox jumps over the l zy dog
The qui k  rown fox jumps over the l zy dog
The qui k  rown fox jumps over the l zy  og
Th  qui k  rown fox jumps ov r th  l zy  og
Th  qui k  rown  ox jumps ov r th  l zy  og
Th  qui k  rown  ox jumps ov r th  l zy  o
T   qui k  rown  ox jumps ov r t   l zy  o
T   qu  k  rown  ox jumps ov r t   l zy  o
T   qu  k  rown  ox  umps ov r t   l zy  o
T   qu     rown  ox  umps ov r t   l zy  o
T   qu     rown  ox  umps ov r t     zy  o
T   qu     rown  ox  u ps ov r t     zy  o
T   qu     row   ox  u ps ov r t     zy  o
T   qu     r w    x  u ps  v r t     zy
T   qu     r w    x  u  s  v r t     zy
T    u     r w    x  u  s  v r t     zy
T    u       w    x  u  s  v   t     zy
T    u       w    x  u     v   t     zy
     u       w    x  u     v         zy
             w    x        v         zy
             w    x                  zy
                  x                  zy
                                     zy
                                     z

```
> 2 votes

# Answer
# C (gcc), 189 bytes

```
#define F for(q=c,p=s;*p;++p,++q)
char*p,*q,s[99],c[99];main(h){gets(s);F{*q=*p>64&&*p<91?*p-65:*p>96&&*p<123?*p-97:0;h=h>*q?h:*q;}for(puts(s);h--;){F{putchar(*q?--*q,*p:32);}putchar(10);}}

```

Try it online!
> 2 votes

# Answer
# Haskell, 98 bytes

```
p c=sum[length[a..c]|a:e<-["B[","b{"],[c]<e]
f s=[[last$c:[' '|i>p c]|c<-s]|i<-[0..maximum$p<$>s]]

```

Try it online!

Example usage: `f "[Abc]"` yields a list of lines: `["[Abc]"," bc "," c "]`. Use `putStr.unlines.f $ "[Abc]"` for pretty-printed output:

```
[Abc]
  bc
   c
```

~~Partly inspired by~~ Now directly based on user1472751's Haskell answer.

---

### Previous approach (~~100~~ 99 bytes)

```
f s=[h|i<-[0..26],h<-[[(c:concat[c<$[a..c]|[a,e]<-["B[","b{"],c<e]++cycle" ")!!i|c<-s]],any(>' ')h]

```

Try it online!
> 2 votes

# Answer
# Oracle SQL, 186 Bytes

Assumes the string will be in a table `t` in column `v`:

```
WITH a(s,l)AS(SELECT v,64 FROM t UNION ALL SELECT REGEXP_REPLACE(s,'[^'||CHR(l+1)||'-Z]',' ',1,0,'i'),l+1 FROM a WHERE l<90)SELECT LISTAGG(RTRIM(s),CHR(10))WITHIN GROUP(ORDER BY l)FROM a

```

SQL Fiddle

**Oracle 11g R2 Schema Setup**:

```
CREATE TABLE t ( v ) AS
SELECT '~|[abc<0>cba]|~' FROM DUAL
/

```

**Query 1**:

```
WITH a(s,l)AS(
  SELECT v,64 FROM t
UNION ALL
  SELECT REGEXP_REPLACE(s,'[^'||CHR(l+1)||'-Z]',' ',1,0,'i'),l+1
  FROM a
  WHERE l<90
)
SELECT LISTAGG(RTRIM(s),CHR(10))WITHIN GROUP(ORDER BY l)
FROM a

```

**Results**:

```
|      LISTAGG(RTRIM(S),CHR(10))WITHINGROUP(ORDERBYL) |
|-----------------------------------------------------|
| ~|[abc<0>cba]|~                                     |
|    abc   cba                                        |
|     bc   cb                                         |
|      c   c                                          |

```
> 2 votes

# Answer
# PowerShell, ~~122~~ 127 bytes

```
param($a)$a;(1..25|%{$i=$_;(-join([char[]]$a|%{(' ',$_)[$_-match'[a-z]'-and[math]::Max(0,($_-bor32)-96-$i)]})).TrimEnd()})-ne''

```

Try it online!

Short thanks to how PowerShell can dynamically cast between `[char]` and `[int]`, but long because of removing extraneous whitespace and the calculation of whether to output a space or the character.

*Bugfix thanks to beatcracker.*
> 2 votes

# Answer
# Jelly, 15 bytes

```
ØaḊiÐ€Œl‘⁸ẋ"z⁶Y

```

Try it online!
> 2 votes

# Answer
# Java 8, ~~151~~ ~~147~~ ~~144~~ ~~143~~ 139 bytes

```
s->{String x="\n"+s;for(int i=64,t;++i<91;)for(char c:x.toCharArray())s+=(t=c&~32)>64&t<91&t>i|c<11?c:" ";return s.replaceAll("\\s+$","");}

```

**Explanation:**

Try it here.

```
s->{                   // Method with String as both parameter and return-type
  String x="\n"+s;     //  Temp-String (equal to leading new-line + input)
  for(int i=64,        //  Index-integer `i` (starting at 64)
          t;           //  Temp-integer
      ++i<91;)         //  Loop (1) from 'A' (65) to 'Z' (90) (inclusive)
    for(char c:x.toCharArray())
                       //   Inner loop (2) over the character of the array
      s+=(t=c&~32)>64  //    If the current character as uppercase is larger than 'A'
         &t<91         //    and smaller or equal to 'Z'
         &t>i          //    and larger than the current index
         |c<11?        //    or the current character is a new-line
          c            //     Append the current character to `s`
         :             //    Else:
          " ";         //     Append a space to `s` instead
                       //   End of inner loop (2) (implicit / single-line body)
                       //  End of loop (1) (implicit / single-line body)
  return s             //  Return the result,
    .replaceAll("\\s+$","");
                       //   after we've removed all trailing spaces and new-lines
}                      // End of method

```
> 2 votes

# Answer
# , ~~42~~ 37 bytes

```
{(+)max[m]$(m:1+mod[.Q.a?(_)x]26)#'x}

```

-5 thanks to streetster!

---

old solution+explanation:

```
{(+)max[m]$'(m:1+mod[.Q.a?lower x;26])#'x}

{                                        }  / lambda func
                     .Q.a?lower x           / get lowercase of input (ignores non-alpha values) and find (?) their index in "a...z" (.Q.a). non-alpha values return `26`
                 mod[.Q.a?lower x;26]       / get mod 26 of each index, this returns 0 where index is 26
            (m:1+mod[.Q.a?lower x;26])      / add 1 and assign to m
            (m:1+mod[.Q.a?lower x;26])#'x   / m and x conform, so we can take (#) m copies of each (') x at corresponding indices
    max[m]$'(m:1+mod[.Q.a?lower x;26])#'x   / get max of m, and pad each ($') of right-side list to that length
 (+)                                        / transpose the char matrix

```
> 2 votes

# Answer
# SOGL V0.12, ~~12~~ 11 bytes

```
ā,{Z⁴UW1Χ∙┼

```

Try it Here!

Explanation:

```
ā            push an empty array
 ,{          for each character in the input, pushing it
   Z           push the uppercase alphabet
    ⁴          push a duplicate of the character
     U         uppercase it
      W        find its index in that alphabet
       1Χ      get the maximum of that and 1
         ∙     repeat the character that many times
          ┼    append horizontally to that array

```
> 1 votes

# Answer
# QBIC, 141 bytes

```
_L;|dim g(a)┘dim H(a)[a|_SA,b,1|┘H(b)=B┘o=asc(ucase$(B))-65~o<1or o>25|o=0]g(b)=o~g(b)>p|p=g(b)}?A[p|[a|~g(d)|g(d)=g(d)-1\H(d)=@ `]?H(d)';`]?

```

Wow, this has to be the longest entry I've made using QBIC...

## Explanation

```
_L |                        Assign to num var 'a' the length of
  ;                         A$, which is read off the CMD line
dim g(a)                    Define 'g' as an array of 'a' slots. The lower-
                            case letter denotes it will store numbers.
                            g() will store if we still need to rain down the char at pos ()
                            of the input string.
┘                           Inject a linebreak in the compiled QBasic
dim H(a)                    Define H$ to be an array, also of length 'a', for strings
                            H$(x) will store what to rain down if g(x) > 0
[a|                         Run along the length of the input string
                            (QBasic: FOR b = 1 TO a STEP 1)
  _SA,b,1|┘                 Take a substring at index b on string A$, length 1 and
                            store as B$; lift out each character one at a time
  H(b)=B┘                   Save the character in H$(x)
  o=asc(ucase$(B))-65       Take the ASCII codepoint of that substring, as uppercase
                            minus 65. [A-Z] maps to 0-25. Save that number as 'o'
  ~o<1or o>25               IF o is not in range
  |o=0]                     THEN set o to zero (the same value as 'A/a')
  g(b)=o                    SET the number of rain-down copies to 'o'
  ~g(b)>p                   IF the number of raindowns exceeds the prvious max,
  |p=g(b)                   THEN store the new max into 'p'. This defines the rain-down depth
}                           END IF, NEXT
?A                          PRINT the original, \n
[p|                         FOR c = 1 TO max-depth
  [a|                       FOR d = 1 to LEN(A$)
    ~g(d)                   IF the rain-down counter is positive
    |g(d)=g(d)-1            THEN decrement it by 1
    \H(d)=@ `               ELSE replace the char by a literal space in the char map
    ]                       END IF
    ?H(d)                   PRINT the character at the current pos int he char map
      ';`                   and suppress newlines
  ]                         NEXT character
?                           PRINT \n at the end of the line

```
> 1 votes

# Answer
# Stacked, 47 bytes

```
[[:upcase ALPHA\index 0 max#+*]"!LF#`togrid tr]

```

Try it online! Takes input as list of characters, and returns a list of list of characters.

```
[[:upcase ALPHA\index 0 max#+*]"!LF#`togrid tr]          input: str
 [                            ]"!                        for(char of str)
   upcase ALPHA\index                                        get index of uppercase char
                                                             in uppercase alphabet
                      0 max                                  max(0, index)
  :                        #+*                               repeat char ^ times
                                 LF#`togrid                  convert to aligned char array
                                            tr               transpose

```
> 1 votes

# Answer
# Jq 1.5, 106 bytes

```
foreach("\n","^B-Zb-z",(range(24)|[.+66,.+98]|implode))as$x(.;gsub("[\($x)]";" ");.)|select(.!=length*" ")

```

Expanded

```
   foreach ("\n",                            # first pattern won't match anything
            "^B-Zb-z",                       # next a, A and punctuation
            (range(24)|[.+66,.+98]|implode)  # then Bb, Cc, ...
   ) as $x (
     .
   ; gsub("[\($x)]";" ")                     # apply each pattern to input
   ; .
   )
 | select(.!=length*" ")                     # eliminate blank lines

```

Try it online!
> 1 votes

# Answer
# SNOBOL4 (CSNOBOL4), 181 bytes

```
	S =OUTPUT =INPUT
	U =&UCASE
	L =&LCASE
Z	S NOTANY(U L ' ') =' '	:S(Z)
N	U LEN(1) . X REM . U
	L LEN(1) . Y REM . L
R	S (X | Y) =' '	:S(R)
	S NOTANY(' ')	:F(END)
	OUTPUT =S	:(N)
END

```

Try it online!

```
	S =OUTPUT =INPUT		;* read input and print it
	U =&UCASE			;* alias for uppercase letters
	L =&LCASE			;* alias for lowercase letters
Z	S NOTANY(U L ' ') =' '	:S(Z)	;* replace non-alphabet, non-space characters with space
N	U LEN(1) . X REM . U		;* get the Next uppercase letter
	L LEN(1) . Y REM . L		;* get the Next lowercase letter
R	S (X | Y) =' '	:S(R)		;* replace all those with spaces
	S NOTANY(' ')	:F(END)		;* if S is all spaces, terminate the program
	OUTPUT =S	:(N)		;* else print S and goto N
END

```
> 1 votes

# Answer
# Julia 1.0, 97 bytes

```
f(s,h=c->isletter(c)&&(c-'A')%32)=println.([s;[map(c->h(c)>i ? c : ' ',s) for i=0:maximum(h,s)]])

```

Try it online!
> 1 votes

# Answer
# Stax, 12 bytes

```
î┌→♠─l∙╨"«Pò

```

Run and debug it
> 1 votes

# Answer
# Assembly (MIPS, SPIM), 319 bytes

```
.text
.globl main
main:
lw $4 4($5)
li $2 4
syscall
li $9 65
li $11 91
li $14 122
move $12 $4
li $2 11
syscall
g:
li $4 10
syscall
addi $9 1
bge $9 $11 n
addi $8 $12 -1
l:
addi $8 1
lb $4 ($8)
beqz $4 g
blt $4 $9 e
blt $4 $11 f
addi $13 $9 32
blt $4 $13 e
bgt $4 $14 e
f:
syscall
j l
e:
li $4 32
j f
n:
li $2 10
syscall

```

Try it online!

almost positive this can be golfed further, (might be able to use mod instead of a bunch of branches, idk) but i'm not complaining. Takes the string as a command line argument. most of the registers are used for magic ascii numbers, though $9 and $8 update - $9 is the current iteration, starting at 65 (a). $8 starts at the beginning of the string, then iterates over the string until reaching a null terminator. characters that are no longer valid are replaced with '32' or space. Prints a single trailing newline, on the last line.

The output is padded - that is, if the input string is 5 characters long, each printed row will also be 5 characters long, even if this means the last few bytes in a row are space characters. or more practically: "Faa"=\>
`"Faa"
 "F "
 "F "
 "F "
 "F "
 "F "`
The instructions did not specify if we had to trim each row to the shortest possible or if this behavior was allowed. If the trimmed variant is desired I can mark this non-competing.
> 1 votes

# Answer
# PHP 7, 110 Bytes

```
$t.="
";for($i=66;$i<90&&trim($t);){echo$t;$t=preg_replace('~[^\n'.chr($i).'-Z'.chr(32+$i++).'-z]~', ' ',$t);}

```

Try it online

## Ungolfed

Input given in $t

```
$t.="
";

for($i=66;$i<90&&trim($t);){
    echo$t;
    $t=preg_replace('~[^\n'.chr($i).'-Z'.chr(32+$i++).'-z]~', ' ',$t);
}

```
> 1 votes

# Answer
# Pip, 23 bytes

```
PaFi,26P{z@?LCa>i?as}Ma

```

Try it online!

## Explanation

```
PaFi,26P{z@?LCa>i?as}Ma
Pa                      Print the original string
  Fi,26                 loop with variable i across range 0-26
                     Ma Map the input to the following function
        {z@?LCa>i?as}   Replace any symbols with index lesser than i with a space
       P                Print the mapped string

```
> 0 votes

# Answer
# Husk, 15 bytes

```
T' m?SRȯ-64ca;√

```

Try it online!

repeat each character, then transpose-pad.
> 0 votes

# Answer
# Thunno 2 `N`, 7 bytes

```
Ä1|Ḟ×ðƬ

```

Try it online!

#### Explanation

```
Ä1|Ḟ×ðƬ  # Implicit input
Ä        # Get the 1-based index in the alphabet
         # for each character in the input string
 1|      # Replace 0s (non-alphabets) with 1s
   Ḟ×    # Multiply elementwise with the input
     ðƬ  # Transpose with filler space
         # Implicit output, joined on newlines

```
> 0 votes

---
Tags: code-golf, string, alphabet
---


title: Repeated! Factorials!

text:
# Question
Title: Repeated! Factorials!
Not to be confused with Find the factorial!

## Introduction

The factorial of an integer `n` can be calculated by $$n!=n\times(n-1)\times(n-2)\times(...)\times2\times1$$

This is relatively easy and nothing new. However, factorials can be extended to double factorials, such that $$n!!=n\times(n-2)\times(n-4)\times(...)\times4\times2$$ for even numbers, and $$n!!=n\times(n-2)\times(n-4)\times(...)\times3\times1$$ for odd numbers. But we're not limited to double factorials. For example $$n!!!=n\times(n-3)\times(n-6)\times(...)\times6\times3$$ or $$n!!!=n\times(n-3)\times(n-6)\times(...)\times5\times2$$ or $$n!!!=n\times(n-3)\times(n-6)\times(...)\times4\times1$$ depending on the starting value.

In summary: $${\displaystyle n!^{(k)}={\begin{cases}1&{\text{if }}n=0 \\n&{\text{if }}0\<n\leq k\\n\cdot\left({(n-k)!}^{(k)}\right)&{\text{if }}n\>k\end{cases}}}$$ where $${\displaystyle n!^{(k)}=n\underbrace{!\dots!}\_{k}}$$ Or, in plain English: **Subtract the factorial count from the base number repeatedly and multiply all resulting positive integers.**

## The Challenge

Write a function that will calculate any kind of repeated factorial for any non-negative integer.

### Input

Either

* A string containing a non-negative base-ten integer, followed by 1 or more exclamation marks. E.g. `"6!"` or `"9!!"` or `"40!!!!!!!!!!!!!!!!!!!!"`.

or

* The same values represented by two integers: one non-negative base value and one positive value representing the factorial count. This can be done according to any format from the default I/O rules.

### Output

The result of said calculation.

## Challenge remarks

* `0!` equals `1` by definition. Your code must account for this.
* The factorial count is limited by $$ 0 \< factorial~count \leq base~value $$outside this range, you are free to output whatever. Aside from `0!`, which is the only exception to this rule.

## Examples

```
Input                              Output

3!!!                               3
0!                                 1
6!                                 720
9!!                                945
10!!!!!!!!                         20
40!!!!!!!!!!!!!!!!!!!!             800
420!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!  41697106428257280000000000000000

```

Try it with an ungolfed Python implementation: Try it online!

## General remarks

# Answer
> 17 votes
# , 33 bytes

```
function(n,k)prod(seq(n+!n,1,-k))

```

Try it online!

Handles \\$n=0\\$ by adding the logical negation of \\$n\\$.

# Answer
> 14 votes
# ArnoldC, 702 698 634 bytes

```
LISTEN TO ME VERY CAREFULLY f
I NEED YOUR CLOTHES YOUR BOOTS AND YOUR MOTORCYCLE n
I NEED YOUR CLOTHES YOUR BOOTS AND YOUR MOTORCYCLE p
GIVE THESE PEOPLE AIR
HEY CHRISTMAS TREE r
YOU SET US UP 1
HEY CHRISTMAS TREE c
YOU SET US UP 0
STICK AROUND n
GET TO THE CHOPPER r
HERE IS MY INVITATION r
YOU'RE FIRED n
ENOUGH TALK
GET TO THE CHOPPER n
HERE IS MY INVITATION n
GET DOWN p
ENOUGH TALK
GET TO THE CHOPPER c
HERE IS MY INVITATION 0
LET OFF SOME STEAM BENNET n
ENOUGH TALK
BECAUSE I'M GOING TO SAY PLEASE c
GET TO THE CHOPPER n
HERE IS MY INVITATION 0
ENOUGH TALK
YOU HAVE NO RESPECT FOR LOGIC
CHILL
I'LL BE BACK r
HASTA LA VISTA, BABY

```

Try it online!

Translated to pseudocode:

```
f(n,p) {
  r=1;
  c=0;
  while (n) {
    r=r*n;
    n=n-p;
    c=n<0;
    if (c) n=0;
  }
  return r;
}

```

Note: ArnoldC has only one type of data: 16-bit signed integer. Hence I cannot test the `420!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!` case.

# Answer
> 13 votes
# Jelly, 4 bytes

```
RṚmP

```

Try it online!

**How?** Given \\$n\\$ and \\$k\\$, it first generates the range \\$n,\cdots, 1\\$ (with `RṚ`), then with `m` it keeps every \\$k^{\text{th}}\\$ element of this range (so \\$n, n-k, n-2k,\cdots,n-\lfloor n/k\rfloor k\\$), and finally multiplies them using `P`.

# Answer
> 8 votes
# Haskell, 21 bytes

```
n%a=product[n,n-a..1]

```

Try it online!

Combining the built-in product function with stepped range enumeration beats what I could code up recursively (even with flawr saving a byte).

**22 bytes**

```
n%a|n<1=1|m<-n-a=n*m%a

```

Try it online!

Here's a solution taking input in string format like `9!!`, which I think is more interesting.

**42 bytes**

```
(\[(n,a)]->product[n,n-length a..1]).reads

```

Try it online!

# Answer
> 8 votes
# APL (Dyalog Extended), 7 bytesSBCS

Anonymous tacit prefix function. Takes `[n,b]` as argument.

```
×/-\…1¨

```

Try it online!

one for each element of the argument; `[1,1]`

`-\` cumulative difference; `[n,n-b]`

range using second element of left argument as indicator of step, e.g. `[9,7]` continues with `5`

`×/` product

# Answer
> 6 votes
# Pyth, 6 bytes

These are all equivalent 6-byters:

```
*F:Q1E
*F:E1Q
*F%E_S

```

Try it online! (`*F:Q1E`)

Or, **11 bytes**, taking input as a string:

```
*F:.vQ1/Q\!

```

Test suite.

# Answer
> 5 votes
# JavaScript (ES6), 21 bytes

Takes input as `(k)(n)`.

```
k=>g=n=>n<1||n*g(n-k)

```

Try it online!

Or **24 bytes** to support BigInts.

---

# JavaScript (ES6), 55 bytes

Takes input as a string, using the format described in the challenge.

```
s=>(a=s.split`!`,k=a.length-1,g=n=>n<1||n*g(n-k))(a[0])

```

Try it online!

# Answer
> 5 votes
# 05AB1E, ~~10~~ ~~8~~ 7 bytes

```
Ý¦RIιнP

```

Input as two separated inputs: first input being `base`; second input being `factorial`.

Try it online or verify all test cases.

-2 bytes thanks to *@Mr.Xcoder*.
-1 byte thanks to *@JonathanAllan*.

**Explanation:**

```
Ý        # Create a list in the range [0, (implicit) base-input]
 ¦       # And remove the first item to make it the range [1, base]
         # (NOTE: this is for the edge case 0. For the other test cases simply `L` instead
         #  of `Ý¦` is enough.)
  R      # Reverse this list so the range is [base, 1]
   Iι    # Uninterleave with the second input as step-size
         #  i.e. base=3, factorial=7: [[3],[2],[1],[],[],[],[]]
         #  i.e. base=10, factorial=8: [[10,2],[9,1],[8],[7],[6],[5],[4],[3]]
         #  i.e. base=420, factorial=30: [[420,390,360,...,90,60,30],[419,389,359,...],...]
     н   # Only leave the first inner list
      P  # And take the product of its values
         # (which is output implicitly as result)

```

**Original 10 bytes answer:**

```
L0KD¤-IÖÏP

```

Input as two separated inputs: first input being `base`; second input being `factorial`.

Try it online or verify all test cases.

**Explanation:**

```
L           # Create a list in the range [1, (implicit) base-input]
 0K         # Remove all 0s (edge case for input 0, which will become the list [1,0])
   D        # Duplicate this list
    ¤       # Get the last value (without popping)
            # (could also be `Z` or `¹` for max_without_popping / first input respectively)
     -      # Subtract it from each item in the list
      IÖ    # Check for each if they're divisible by the second factorial-input
        Ï   # In the list we copied, only leave the values at the truthy indices
         P  # And take the product of those
            # (which is output implicitly as result)

```

# Answer
> 5 votes
# Whitespace, 91 bytes

```
[S S S T    N
Push_1][S N
S _Duplicate_1][S N
S _Duplicate_1][T   N
T   T   _Read_STDIN_as_integer_(base)][T    T   T   _Retrieve_base][S S S N
_Push_0][T  N
T   T   _Read_STDIN_as_integer_(factorial)][N
S S N
_Create_Label_LOOP][S N
S _Duplicate_base][S S S T  N
_Push_1][T  S S T   _Subtract][N
T   T   S N
_If_negative_jump_to_Label_PRINT_RESULT][S N
S _Duplicate_base][S T  S S T   S N
_Copy_0-based_2nd_(result)][T   S S N
_Multiply][S N
T   _Swap_top_two][S S S N
_Push_0][T  T   T   _Retrieve_factorial][T  S S T   _Subtract][N
S N
N
_Jump_to_Label_LOOP][N
S S S N
_Create_Label_PRINT_RESULT][S N
N
_Discard_top][T N
S T _Print_result_as_integer]

```

Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only.
`[..._some_action]` added as explanation only.

Try it online (with raw spaces, tabs and new-lines only).

**Explanation in pseudo-code:**

```
Integer result = 1
Integer base = STDIN as integer
Integer factorial = STDIN as integer
Start LOOP:
  If(base <= 0):
    Call function PRINT_RESULT
  result = result * base
  base = base - factorial
  Go to next iteration of LOOP

function PRINT_RESULT:
  Print result as integer to STDOUT

```

# Answer
> 5 votes
# Python 2, 29 bytes

```
f=lambda n,b:n<1or n*f(n-b,b)

```

**Try it online!**

# Answer
> 4 votes
# Perl 6, 22 bytes

```
{[*] $^a,*-$^b...^1>*}

```

Try it online!

Anonymous codeblock that returns the product of the range starting from the first input, decreasing by the second until it is below `1`, excluding the last number. This works for `0`, since the base case of a the reduce by product is 1, so the output is 1.

# Answer
> 4 votes
# x86-64 machine code, 12 bytes

Same machine code does the same thing in 32-bit mode, and for 16-bit integers in 16-bit mode.

This is a function, callable with args `n=RCX`, `k=ESI`. 32-bit return value in `EAX`.

Callable from C with the x86-64 System V calling convention with dummy args to get the real args into the right registers. `uint32_t factk(int, uint32_t k, int, uint64_t n);` I couldn't just use Windows x64 because 1-operand `mul` clobbers RDX, and we don't want REX prefixes to access R8/R9. `n` must not have any garbage in the high 32 bits so JRCXZ works, but other than that it's all 32-bit.

NASM listing (relative address, machine code, source)

```
 1                         factk:
 2 00000000 6A01             push 1
 3 00000002 58               pop rax             ; retval = 1
 4 00000003 E306             jrcxz  .n_zero      ; if (n==0) return
 5                         .loop:                ; do {
 6 00000005 F7E1              mul   ecx            ; retval *= n  (clobbering RDX)
 7 00000007 29F1              sub   ecx, esi       ; n -= k
 8 00000009 77FA              ja   .loop         ; }while(sub didn't wrap or give zero)
 9                         .n_zero:
10 0000000B C3               ret

```

0xc = 12 bytes

---

Or 10 bytes if we didn't need to handle the `n=0` special case, leaving out the `jrcxz`.

For standard factorial you'd use `loop` instead of sub/ja to save 2 bytes, but otherwise the exact same code.

---

Test caller that passes `argc` as `k`, with `n` hard-coded.

align 16
global _start
_start:
  mov  esi, [rsp]
;main:
  mov  ecx, 9
  call factk

  mov  esi, eax
  mov  edx, eax
  lea  rdi, [rel print_format]
  xor  eax, eax
extern printf
  call printf
extern exit
  call exit

section .rodata
print_format: db `%#x\t%u\n`

```
</code></pre>

# Answer
> 3 votes
# APL (Dyalog Unicode), 11 bytes<sup>SBCS</sup>

Anonymous tacit infix function. Takes `n` as right argument and `b` as left argument.

```
×/1⌈⊢,⊢-×∘⍳

```

Try it online!

`×∘⍳` multiply `b` by the **ɩ**ntegers 1 through `n`

`⊢-` subtract that from `n`

`⊢,` prepend `n`

`1⌈` max of one and each of those

`×/` product

# Answer
> 3 votes
# Java 10, 44 bytes

```
f->b->{int r=1;for(;b>0;b-=f)r*=b;return r;}

```

Takes the factorial as first input, base as second.

Try it online.

This above doesn't work for the largest test case due to the limited integer range (32-bits). To fix this we can use `BigIntegers`, which ~~coincidentally~~ is ~~exactly double the size - **88**~~ **79 bytes**:

```
f->b->{var r=f.ONE;for(;b.signum()>0;b=b.subtract(f))r=r.multiply(b);return r;}

```

-9 bytes thanks to *@OlivierGrégoire*.

Try it online.

**Explanation:**

```
f->b->{       // Method with two integer parameters and integer return-type
  int r=1;    //  Result-integer, starting at 1
  for(;b>0;   //  Loop as long as the base is still larger than 0
      b-=f)   //    After every iteration: decrease the base by the factorial
    r*=b;     //   Multiply the result by the base
  return r;}  //  Return the result

```

# Answer
> 3 votes
# Ruby, 25 bytes

```
f=->s,r{s<1?1:s*f[s-r,r]}

```

Try it online!

# Answer
> 3 votes
# Wolfram Language (Mathematica), ~~22~~ 21 bytes

```
1##&@@Range[#,1,-#2]&

```

Try it online!

-1 thanks to attinat: `Times --> 1##&`

Explanation: use `Range` to make a list of the values `{n, n-k, n-2k, n-3k, ...}`, stopping before going below 1 (i.e., stopping just right). Then multiply all numbers in this list with `Times` (or `1##&`).

# Answer
> 3 votes
# Vyxal, 4 bytes

```
ɾṘḞΠ

```

Try it Online!

# Answer
> 3 votes
# Knight, ~~34~~ 33 bytes

```
;=p=xE P;=yP;W<0=x-x y=p*x pO+p!p

```

Try it online!

-1 byte thanks to Aiden Chow

# Answer
> 2 votes
# Japt, 8 bytes

```
TõUV f ×

```

Try it

-1 thanks to EoI pointing out how dumb uncaffeinated Shaggy can be!

# Answer
> 2 votes
# C (gcc), 41 bytes

```
r;f(n,k){for(r=1;n>0;n-=k)r*=n;return r;}

```

Try it online!

# Answer
> 2 votes
# MathGolf, ~~7~~ 6 bytes

```
╙╒x%ε*

```

Try it online!

Found a clever way to handle 0! without changing the other test cases. Takes input as `k n` (reverse order), which helps with implicit popping.

## Explanation

```
╙        maximum of two elements (pops largest of k and n,
         which is n for every valid case except 0!, where 1 is pushed)
 ╒       range(1,n+1)
  x      reverse int/array/string
   %     slice every k:th element
    ε*   reduce list with multiplication

```

# Answer
> 2 votes
# Scala, 53 bytes

Takes two arguments, the first being the number and the second being the `!` count.
Somehow breaks on the big test case. This step range costs many bytes in the end because of this `-1*` so improvements ought to be possible by refactoring.
I have, as always, a doubt about how we count bytes for function declarations, because everyone doesn't do the same way everywhere down there, so well... It's **17 bytes less**, so **36 bytes**, if we count out func variables' (`a` and `b`) declaration and func brackets.

```
(a:Int,b:Int)=>{var s=1
for(i<-a to b by -1*b)s*=i
s}

```

Try it online! I commented out the broken test cases, because, well, they do break.

# Answer
> 2 votes
# Attache, ~~21~~ 19 bytes

```
${x<y∨x*$[x-y,y]}

```

Try it online! Pretty direct recursive implementation. (Note: `true` is essentially `1`, as it can be used in arithmetic operations as `1`.) This is one of the few programs I've written for this site where using a unicode operator saves bytes (1, to be precise).

## Alternatives

**20 bytes:** `${x<y or x*$[x-y,y]}`

**21 bytes:** `Prod@${{_%y=x%y}\1:x}`

**27 bytes:** `${x*[`1,$][x>y][x-y,y]∨1}`

**27 bytes:** `${If[x>y,x*$[x-y,y],_or 1]}`

**27 bytes:** `${x*[`1,$][x>y][x-y,y]or 1}`

**29 bytes:** `${If[x>y,x*$[x-y,y],_+not _]}`

# Answer
> 2 votes
# Rust, ~~92~~ ~~73~~ 61 bytes

```
fn f(n:i128,k:i128)->i128{if n<=0{return 1}return n*f(n-k,k)}

```

I am just starting to learn rust, so I'm sure this can be shorter. Will update as I learn. The return value should be `i128` in order to compute the last test.

Edit: Recursion is shorter.

Try it online!

You can add your own test, or edit one of the already existing ones.

# Answer
> 2 votes
## **, ~~59 57 55~~ 53 bytes**

```
{prd 2+(&)1_i=last i:("J"$x(&)not[n])#(!)sum n:"!"=x}

```

explanation:

```
q)x:"12!!" / let our input be 12!!, assign to x
q)sum n:"!"=x / count "!"s
2i
q)(!)sum n:"!"=x / (!)m -> [0,m)
0 1
q)("J"$x(&)not[n]) / isolate the number in input
12
q)("J"$x(&)not[n])#(!)sum n:"!"=x / x#y means take x items from list y, if x>y, circle around
0 1 0 1 0 1 0 1 0 1 0 1
q)i:("J"$x(&)not[n])#(!)sum n:"!"=x / assign to i
q)i
0 1 0 1 0 1 0 1 0 1 0 1
q)(last i)=i:("J"$x(&)not[n])#(!)sum n:"!"=x / take last elem of i and see which are equal in i
010101010101b
q)1_(last i)=i:("J"$x(&)not[n])#(!)sum n:"!"=x / drop first elem
10101010101b
q)(&)1_(last i)=i:("J"$x(&)not[n])#(!)sum n:"!"=x / indices of 1b (boolean TRUE)
0 2 4 6 8 10
q)2+(&)1_(last i)=i:("J"$x(&)not[n])#(!)sum n:"!"=x / add 2 across array
2 4 6 8 10 12
q)prd 2+(&)1_(last i)=i:("J"$x(&)not[n])#(!)sum n:"!"=x / product across array
46080

```

here also is a version in k (same logic), ~~42~~41 bytes

```
{*/2+&1_i=last i:("J"$x@&~:n)#!+/n:"!"=x}

```

# Answer
> 2 votes
# Factor \+ `math.unicode`, ~~30~~ ~~29~~ 24 bytes

* Saved 1 byte thanks to @Bubbler
* Saved 5 bytes thanks to @chunes!

```
[ 1 rot neg <range> Π ]

```

Try it online!

Takes `k` (which -th factorial) and then `n`. First we push an `n` onto the stack, then `rot` makes the stack look like `n 1 k`. `neg` negates `k`, which will act as the step for a range from `n` to 1 (made using `<range>`). Then `Π` finds the product of that range, and that's it.

# Answer
> 2 votes
# Nibbles, 3.5 bytes (7 nibbles)

```
`*`%@\,

```

```
      ,         # get the range from 1..first input,
     \          # reverse it,
   %            # and take each element in steps of
    @           # the second input,
`*              # and finally get the product

```

---

Or **7.5 bytes (15 nibbles)** with input as string of a base-ten integer followed by exclamation marks:

```
`*`%,|$\$D\,`r$

```

# Answer
> 1 votes
# Physica, 22 bytes

```
f=>n;k:n<1||n*f[n-k;k]

```

Try it online!

---

**26 bytes**

Re-learning how to use my own "language" \o/... If I knew how to write a parser 2 years ago, this would have been 20 bytes :(

```
->n;k:GenMul##[n…1]{%%k}

```

or

```
->n;k:GenMul##Range[n;1;k]

```

Try it online!

# Answer
> 1 votes
# Japt, 8 bytes

```
1õUV f ×

```

Try it

# Answer
> 1 votes
# Retina, 66 bytes

```
^0
1
\d+
*!,
+`(!+)(!+),\1$
$1$2,$2,$1
!+$
1
+`(!+),(\d+)
$.($2*$1

```

Try it online! Link includes faster test cases. Mauls numbers without exclamation marks. Explanation:

```
^0
1

```

Fix up `0!`.

```
\d+
*!,

```

Convert `n` to unary and add a separator.

```
+`(!+)(!+),\1$
$1$2,$2,$1

```

Repeatedly subtract `k` from `n` while `n>k`, and collect the results.

```
!+$
1

```

Replace `k` with `1` (in decimal).

```
+`(!+),(\d+)
$.($2*$1

```

Multiply by each intermediate value in turn, converting to decimal.

# Answer
> 1 votes
# PHP, 47 bytes

Recursive function with tests

```
function f($n,$c){return$n>0?f($n-$c,$c)*$n:1;}

```

Try it online!

---

# PHP, 54 bytes

Loop version (original answer)

```
for($n=$argv[1],$f=1;$n>0;$f*=$n,$n-=$argv[2]);echo$f;

```

Try it online!

---

First argument is the the base value and second one is the factorial count.

Supports specified valid range, but outputs big numbers in scientific notation. For example the last sample is shown as `4.1697106428257E+31`.

# Answer
> 1 votes
# JavaScript (Node.js), 35 bytes

```
(n,i,f=i)=>i-n<1?f:r(n,i-n,f*(i-n))

```

Try it online!

# Answer
> 1 votes
# Forth (gforth), 50 bytes

```
: f 1 1 2over / 1+ 0 do 2over i * - 1 max * loop ;

```

Try it online!

### Code Explanation

```
: f                \ start a new word definition
  1 1              \ add placeholder and accumulator to stack
  2over / 1+       \ get the number of times to run the loop (num/factorial + 1)
  0 do             \ start loop from 0 to num/factorial
    2over          \ copy num and factorial to the top of the stack
    i * -          \ get the current number to multiply by (num - factorial * i)
    1 max          \ make sure it can't be 0 or negative [set to 1 if it is]
    *              \ multiply accumulator by result
  loop             \ end loop
;                  \ end the word definition

```

# Answer
> 1 votes
# Perl 5 `-Mbigint -p`, 45 bytes

```
$b=s/!//g;$\=1*$_||1;$\*=$_ while($_-=$b)>0}{

```

Try it online!

# Answer
> 1 votes
# Stax, 6 bytes

```
å▐█ΩV∟

```

Run and debug it

It takes input in the form `{count} {base}`.

# Answer
> 1 votes
# Gaia, 6 bytes

```
…)¦v%Π

```

Try it online!

Takes input as `n`, `k`, so input of `3 4` would be `3!!!!`.

```
…	 push [0...n-1], or [] if n == 0
 )¦	 increment each value (does nothing if [])
   v	 reverse list
    %	 take every k'th element
     Π	 product; product([]) = 1.
```

# Answer
> 1 votes
# Bash \+ coreutils, 27

```
seq -s\* $[$1+!$1] -$2 1|bc

```

Try it online!

# Answer
> 1 votes
# Lua, ~~150~~ ~~145~~ 129 bytes

```
i=io.read()p,c=i.gsub(i,"!","")p=p+0
function f(n,c)r=1 if n~=0 then
while(n>0) do r=r*n n=n-c
end
end
return r end
print(f(p,c))

```

Try it online!

Ported from Charlie's ArnoldC psuedocode. *-16 bytes thanks to Charlie*

# Answer
> 1 votes
# Python 3 (Input as string), 82 bytes

```
m=lambda n,s:n<1or n*m(n-s,s)
f=lambda x:int(m(int(x.split("!")[0]),x.count("!")))

```

Try it online!

Note: the outer `int()` in `f` is solely for the fact that without it, `0!` will output `True`

# Answer
> 1 votes
# Regex  (RME / PCRE2 <sub><sup>v10.35+</sup></sub>), 25 bytes

```
^(x+),((?*x+)(?>\1|.*))*$

```

Attempt This Online! \- PCRE2
Try it on replit.com! \- RegexMathEngine, in ECMAScript+`(?*)`+`(?>)` mode

Takes its input in unary, as two strings of `x` characters whose lengths represent the numbers, in the order {factorial count, base value}, joined/delimited by a `,`. Returns its output as the number of ways the regex can match. (The rabbit emoji indicates this output method.)

```
^(x+),      # \1 = input factorial count; tail = input base value
(
    (?*x+)  # Assert tail > 0; multiply the number of possible matches by tail
    (?>     # Atomic group – lock in this match once it's finished
        \1  # tail -= \1
    |       # or
        .*  # tail = 0
    )
)*          # Iterate the above as many times as possible, minimum zero
$           # Assert tail == 0

```

# Regex  (RME / PCRE2 <sub><sup>v10.35+</sup></sub>), 26 bytes

```
^((?=(x*).*,\2)(?*x+)\2)*,

```

Attempt This Online! \- PCRE2
Try it on replit.com! \- RegexMathEngine, in ECMAScript+`(?*)` mode

Takes the two numbers in the order {base value, factorial count}. Although this is 1 byte longer, it does not need an atomic group to be this length, using an atomic lookahead instead.

```
^             # tail = input base value
(
    (?=       # Atomic lookahead
        (x*)  # \2 = maximum value ≤ tail for which the following matches:
        .*,   # tail = input factorial count
        \2    # Assert tail ≥ \2
    )
    (?*x+)    # Assert tail > 0; multiply the number of possible matches by tail
    \2        # tail -= \2
)*            # Iterate the above as many times as possible, minimum zero
,             # Assert tail == 0

```

# Answer
> 1 votes
# Thunno 2, 5 bytes

```
RrẈhp

```

Try it online!

#### Explanation

```
RrẈhp  # Implicit input
Rr     # Push the range [n..1]
  Ẉ    # Uninterleave into k pieces
   hp  # Product of first group
       # Implicit output

```

---
Tags: code-golf, integer, factorial
---