# PWC 054 › kth Permutation

This post is part of a series on Mohammad Anwar’s excellent Weekly Challenge, where hackers submit solutions in Perl, Raku, or any other language, to two different challenges every week. (It’s a lot of fun, if you’re into that sort of thing.)

Task #1 this week is as follows:

Write a script to accept two integers n (>=1) and k (>=1). It should print the kth permutation of n integers. For more information, please follow the wiki page.

For example, for n=3 and k=4, the possible permutation sequences are 123, 132, 213, 231, 312, 321. The script should print the 4th permutation sequence, 231.

This is fairly straightforward. There are a number of easy ways to generate permutations that we’ve all seen time and time again, but as I need to optimize for programmer time this week, I’m going to use Algorithm::Combinatorics for my Perl solution. However, since it’s an efficient module, it’ll also optimize for processor time!

## Perl

```use Algorithm::Combinatorics qw<permutations>;
say join '', @{ ( permutations([1..\$n], \$n) )[\$k-1] };
```

You can make this a bit more efficient (on average) by using the iterator version of `permutations` and stopping on the `\$k`th iteration:

```my \$it = permutations([1..\$n], \$n);
\$it->next for 1..\$k-1;
say join '', @{ \$it->next };
```

In benchmarks, the iterator performed 10-30% better on average, and was sometimes a bit worse, mainly due to function call and loop overhead.

You’d think this is a bit too easy, but that would be before you see the Raku solution.

## Raku

```say (1..\$n).permutations[\$k-1];
```

This one ended up being very easy, maybe a little too easy in Perl, but I didn’t see much point to re-inventing such a basic wheel.
{"ft_lang_label":"__label__en","ft_lang_prob":0.8878639,"math_prob":0.9129923,"size":1654,"snap":"2022-27-2022-33","text_gpt3_token_len":426,"char_repetition_ratio":0.10484848,"word_repetition_ratio":0.0,"special_character_ratio":0.2732769,"punctuation_ratio":0.1707989,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.96126246,"pos_list":[0],"im_url_duplicate_count":[null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2022-07-01T11:46:07Z\",\"WARC-Record-ID\":\"<urn:uuid:19c2e19a-391a-4660-870a-2ca749fd4a51>\",\"Content-Length\":\"145427\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:dd760ee7-b81e-4302-befb-03262f14f2d5>\",\"WARC-Concurrent-To\":\"<urn:uuid:52623809-4c7c-4f6a-87d4-f0c74953b75d>\",\"WARC-IP-Address\":\"192.53.120.214\",\"WARC-Target-URI\":\"http://ry.ca/2020/04/kth-permutation/\",\"WARC-Payload-Digest\":\"sha1:YLJDCGOPI7AFCC2TPCBKR3QKKZMNXDHN\",\"WARC-Block-Digest\":\"sha1:QQAXASSHHBYJVV3P2PLLRDDVIMWLEVXN\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2022/CC-MAIN-2022-27/CC-MAIN-2022-27_segments_1656103940327.51_warc_CC-MAIN-20220701095156-20220701125156-00522.warc.gz\"}"}