title: Hiccup a string

text:
# Question
Title: Hiccup a string
Your challenge is to write a program or function that hiccups a string. It should take a string as input (via any standard method), then follow these steps:

1. Generate a (not necessarily uniformly) random integer **n** between 1 and 10, inclusive.
2. Wait **n** seconds.
3. Print the initial/next **n** chars of the input, or the rest of the input if there are less than **n** chars.
4. If there is input left to print, go back to step 1.

# Rules

* The input will always be a non-empty string containing only ASCII chars (32-126).
* The wait time does not have to be exactly **n** seconds, but it must be within 10% of **n**.
* You may print a trailing newline each time a section of text is printed.

# Example

A space here represents 1 second. If the input is `Hiccupinator!`, an output might be:

```
   Hic     cupin a          tor!

```

# Scoring

This is , so **the shortest code in bytes wins**.

# Answer
# Scratch, 16 blocks + 6 bytes

Assumes input is already defined as a list of characters (`["H","e","l","l","o"," ","W","o","r","l","d"]`)
> 9 votes

# Answer
# Pushy, ~~20~~ ~~17~~ 16 or 13 bytes

Depending on what's allowed, there are two solutions.

## 16 bytes:

```
@$LT1U&Wm:v;O"cI

```

Give arguments on the command line: `$ pushy hiccup.pshy 'hiccupinator'`. This prints with trailing newlines after each 'hiccup'. Here's the breakdown:

```
                      % Implicit: input on stack as charcodes
@                     % Reverse input, so chars are pulled from start
 $             I      % While there are items on stack:
   T1U                %   Push a random number, 1-10
      &W              %   Wait that many seconds
  L     m:            %   min(time waited, chars left) times do:
          v;          %     Pull a char from the input.
            O"c       %   Print & delete pulled chars

```

## 13 bytes:

While coding the above answer I came up with this significantly shorter solution:

```
N@$L1TU&Wm:'.

```

Although it does a similar thing, it prints directly off the string rather than constructing a new string, for fewer bytes. This requires the `N` at the beginning of the program to prevent trailing newlines, or else each character would be on a newline.

However, whilst testing this I noticed a bug - `stdout` is line-buffered, so the program would wait the full length, and then display the hiccuped string.

I've fixed this in the latest commit by adding a simple `.flush()` \- this is technically not adding a new feature to the language, just fixing a bug, but I understand if you don't take this answer into account :)

The breakdown looks like this:

```
        % Implicit: input on stack as charcodes
N       % Set trailing newlines to False
@       % Reverse stack (so the charcodes are pulled off in order)
$       % While there are items left to print:
L       %    Push stack length
1TU     %    Push a random number 1-10
&W      %    Wait that amount of time
m:      %    min(time waited, chars left) times do:
'.      %      Pop and print last char

```
> 5 votes

# Answer
# Python 2, ~~93~~ 92 bytes

```
import random,time
def F(s):
 if s:n=random.randint(1,10);time.sleep(n);print s[:n];F(s[n:])

```

*-1 byte thanks to Flp.Tkc*

I'm sure there is a way to shorten the `random.randint` and `time.sleep`, but `from random,time import*` doesn't work...
> 4 votes

# Answer
## Javascript (ES6) ~~91~~ 89 Bytes

```
f=s=>s&&setTimeout(_=>console.log(s.slice(0,n))|f(s.slice(n)),(n=1+Math.random()*10)<<10)

console.log(2 + f.toString().length);
f('Hello sweet world!')
```

*saved 2 bytes thanks to @zeppelin*

Abuses the 10% tolerance for the wait time by waiting `n<<10 === 1024*n` milliseconds.

~~Since you said that the wait time needs to be within 10% of **n**, I decided to save one byte and wait for 999 milliseconds rather than 1 second.~~

*I don't need the 999 millisecond silliness anymore thanks to @ETHProductions*
> 4 votes

# Answer
# Perl 6, 62 bytes

```
{$_=$^a;while $_ {sleep my \t=(1..10).roll;put s/.**{0..t}//}}

```

## Expanded

```
{ # block lambda with parameter ｢$a｣

  $_ = $^a; # declare parameter, and store it in ｢$_｣
            # ( the input is read-only by default )

  while $_ {
    # generate random number and sleep for that many seconds
    sleep my \t=(1..10).roll;

    put
      s/              # substitution on ｢$_｣ ( returns matched text )
        . ** { 0..t } # match at most ｢t｣ characters
      //              # replace it with nothing
  }
}

```
> 3 votes

# Answer
# CJam, 28 bytes

```
q{Amr)__e3es+{_es>}g;2$<o>}h

```

Try it online! Or actually, don't. The effect doesn't really show up in any online interpreter, so try it on the Java interpreter instead.

Turns out, CJam has an operator that gets the current Unix timestamp. This program waits by entering a while loop until the timestamp passes the correct value.
> 2 votes

# Answer
## Batch, 131 bytes

```
@set/ps=
:l
@set/an=%random%%%10+1
@timeout/t>nul %n%
@call echo(%%s:~0,%n%%%
@call set s=%%s:~%n%%%
@if not "%s%"==2" goto l

```

Using `set/pn=<nul` would have given a nicer effect except that it trims spaces.
> 1 votes

# Answer
# Pyth, 16 bytes

```
Wz.d_JhOT<zJ=>zJ

```

You can try it online, but it doesn't work well since the online interpreter only displays the output once the program has finished.

### Explanation

```
Wz         While z (the input) is not empty:
     hOT   Get a random number between 1-10 (inclusive)
    J      Set the variable J to that number
 .d_       Sleep for that number of seconds
 <zJ       Get and implicitly print the first J characters of the input
  >zJ      Get all characters of z at and after index J
 =         Set z to that string

```
> 1 votes

# Answer
# **BaCon, 93 bytes**

A solution in BASIC. The RANDOM() function generates a number between 0 and n-1, therefore we have to use RANDOM(11) to get a number between 0 and 10 inclusive.

```
INPUT s$
WHILE LEN(s$)>0
n=RANDOM(11)
SLEEP n*1000
?LEFT$(s$,n),SPC$(n);
s$=MID$(s$,n+1)
WEND

```

Sample session, first line is the input, second the output:

```
Hiccupinator!
Hiccupi       nato    r!

```
> 1 votes

# Answer
# MATL, 19 bytes

```
`10YrtY.ynhX<:&)wDt

```

### How it works

Try it online! The online compiler does gradually produce the outputs with the pauses.

```
`         % Do...while loop
  10Yr    %   Random integer from 1 to 10
  tY.     %   Duplicate. Pause that many seconds
  y       %   Duplicate the second-top element. This is the remaining string; or it
          %   takes the input implicitly in the first iteration
  n       %   Number of elements
  hX<     %   Minimum of the number of elements and the random number
  :       %   Range from 1 to that
  &)      %   Apply as index. Push the substring as given by the index and the
          %   remaining substring
  w       %   Swap
  D       %   Display
  t       %   Duplicate the remaining substring. This is used as loop condition:
          %   if non-empty execute next iteration
          % End loop implicitly

```
> 1 votes

# Answer
## Perl, 42 bytes

**41 bytes code + 1 for `-n`.**

```
$|=$-=--$-||sleep 1+rand 10,print for/./g

```

I had to force Perl to flush output as it wasn't showing anything 'til the end at first, hence setting `$|`. We use `$-` to track the number of characters to `print` as this cannot be negative (so I can use `--$-` and it'll sill be falsy when it's empty) and it also `floor`s, although since I'm using the return of `sleep` for this now, that doesn't really matter.

### Usage

```
perl -ne '$|=$-=--$-||sleep 1+rand 10,print for/./g' <<< 'Hello, World!'
    Hell      o, Wor     ld!
# spaces showing delay!

```
> 1 votes

# Answer
# Ruby, 56 bytes

```
f=->s{n=sleep rand 1..10;print s.slice!0,n;f[s]if s!=""}

```

A recursive lambda. Call like `f["Hello, World!"]`.
> 0 votes

# Answer
# \>\<\> (Fish) ~~103~~ 88 Bytes

```
5>:?vl1-?!v+40.    >~
   1x2v
>^  0  |:!/>:?!v1-b2.
^-1}< <     |~!/:?!^1-i:1+?!;of3.

```

Online interpreter found here!

First attempt at this problem (not golfed).

It waits a certain amount of loops(n) as fish doesn't have a timer that is accessible (Execution in ticks).

Edit 1: Moved last line across to the top (last 2 characters and re-used the starting values. (saving of 15 bytes).
> 0 votes

# Answer
# Bash, 78 bytes

As nobody has posted a Bash solution yet, here is one. Straightforward, yet small enough.

**Golfed**

```
H() { N=$(($RANDOM%10+1));sleep $N;echo ${1:0:$N};S=${1:$N};[ "$S" ] && H $S;}

```

**Test**

```
>H "It's the Hiccupinator"
It's the
Hiccupi
n
ator

```
> 0 votes

# Answer
# PHP, 81 bytes

```
for(;''<$s=&$argv[1];$s=$f($s,$n))echo($f=substr)($s,0,sleep($n=rand(1,10))?:$n);

```

use like:

```
php -r "for(;''<$s=&$argv[1];$s=$f($s,$n))echo($f=substr)($s,0,sleep($n=rand(1,10))?:$n);" "Hiccupinator!"

```
> 0 votes

# Answer
# C++14, 202 bytes

```
#import<thread>
void f(auto c){if(c.size()<1)return;int n=(uintptr_t(&c)%99)/10+1;std::this_thread::sleep_for(std::chrono::seconds(n));std::cout<<c.substr(0,n)<<std::endl;f(n<c.size()?c.substr(n):"");}

```

Requires input to be a `std::string`

Ungolfed and usage:

```
#include<iostream>
#include<string>

#import <thread>

void f(auto c){
  if (c.size() < 1) return;
  int n=(uintptr_t(&c) % 99) / 10 + 1;
  std::this_thread::sleep_for(std::chrono::seconds(n));
  std::cout << c.substr(0,n) << std::endl;
  f(n < c.size() ? c.substr(n) : "");
}

int main(){
  std::string s="abcdefghijklmnopqrstuvwxyz";
  f(s);
}

```
> 0 votes

# Answer
# **C#, 205 bytes**

```
void X(string s){Random r=new Random();int n=r.Next(1,11);while(n<s.Length){Console.WriteLine(s.Substring(0,n));s.Remove(0,n);n*=1000;System.Threading.Thread.Sleep(n);n=r.Next(1,11);}Console.WriteLine(s);}

```

I'm sure this can be destroyed, I haven't really optimised it at all as it stands.

Un-golfed:

```
void X(string s)
{
    Random r = new Random();
    int n = r.Next(1,11);
    while(n < s.Length)
    {
        Console.WriteLine(s.Substring(0,n));
        s.Remove(0,n);
        n *= 1000;
        System.Threading.Thread.Sleep(n);
        n = r.Next(1,11);
    }
    Console.WriteLine(s);
}

```
> 0 votes

# Answer
# PHP, 74 bytes

```
for($s=$argv[1];$s[$p+=$n]>"";print substr($s,$p,$n))sleep($n=rand(1,10));

```

Run with `php -r 'code' "string"`.
> 0 votes

# Answer
# C, 149 bytes, not tested

```
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int f(char *s){int n;while(*s){sleep(n=rand()%10+1);for(;*s&&n--;s++)printf("%.*s",1,s);}}

```

to run, add

```
int main(){f("Programming Puzzles & CodeGolf");}

```

then compile and execute
> 0 votes

# Answer
# Python 3, 99 chars

```
i=input()
import os,time
while len(i):n=1+ord(os.urandom(1))%10;time.sleep(n);print(i[:n]);i=i[n:]

```
> 0 votes

# Answer
# C (gcc), 71 bytes

```
n;f(char*s){while(*s)for(sleep(n=time(0)%10+1);*s&&n--;)putchar(*s++);}

```

Try it online!

*-1 byte thanks to **ceilingcat***
> 0 votes

# Answer
# C++ (gcc), 109 bytes

```
#include<unistd.h>
int f(char*s){for(int n,m=0;*s;)for(sleep(m=n=(getpid()+m)%10+1);*s&&n--;)write(1,s++,1);}

```

Try it online!

*-10 bytes thanks to **ceilingcat***

*-8 bytes thanks to **ceilingcat***
> 0 votes

# Answer
# Assembly (NASM, 32-bit, Linux), 278 bytes

The signature is `void f(char* msg, int len)`. The standard x86 calling convetion is used. Therefore, `msg` is in `ecx`, and `len` is in `edx`. The random number is generated as `time(0)%10+1`.

```
f:push ebx
mov esi,ecx
mov edi,edx
push 0
l:mov ebx,0
mov eax,13
int 128
mov edx,0
mov ecx,10
div cx
inc dx
push edx
mov cx,0
mov ebx,esp
mov eax,162
int 128
pop edx
cmp edx,edi
cmova dx,di
mov ecx,esi
mov ebx,1
mov ax,4
int 128
add esi,edx
sub edi,edx
jnz l
pop eax
pop ebx
ret

```

Try it online!
> 0 votes

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


title: Easy-to-multiply numbers

text:
# Question
Title: Easy-to-multiply numbers
Your task is to determine whether two numbers are *easy to multiply*. This means that their base-10 long multiplication doesn't have any carrying (regrouping) between place values, looking at both the multiplication steps and the addition step. This happens when each pair of digits being multiplied gives 9 or less and the sum of each column is 9 or less.

For example, `331` and `1021` are easy to multiply:

```
   331
x 1021
------
+  331
  662
   0
331
------
337951

```

And the same is true (as is always) if we multiply in the other order:

```
  1021
x  331
------
+ 1021
 3063
3063
------
337951

```

But, `431` and `1021` are not easy to multiply, with carries happening between the columns indicated:

```
   431
x 1021
------
+  431
  862
   0
431
------
440051
 ^^^

```

Also, `12` and `16` are not easy to multiply because a carry-over happens when multiplying `12 * 6` to get `72`, even though no carries happen in the addition step.

```
  12
x 16
----
+ 72
 12
----
 192

```

**Input:** Two positive integers or their string representations. You may assume they will not overflow your language's integer type, nor will their product.

**Output:** One consistent value if they are easy to multiply, and another consistent value if not.

**Test cases:** The first 5 are easy to multiply, the last 5 are not.

```
331 1021
1021 331
101 99
333 11111
243 201

431 1021
12 16
3 4
3333 1111
310 13

[(331, 1021), (1021, 331), (101, 99), (333, 11111), (243, 201)]
[(431, 1021), (12, 16), (3, 4), (3333, 1111), (310, 13)]

```

**Leaderboard:**

```
var QUESTION_ID=151130,OVERRIDE_USER=20260;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/151130/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```

```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```

# Answer
> 14 votes
# Jelly, 7 bytes

```
Dæc/>9Ẹ

```

Try it online!

Uses convolution (which I contributed to Jelly :D)

## How it works

```
Dæc/>9Ẹ
D        converts to decimal list
 æc      convolution
    >9Ẹ  checks if any number is greater than 9

```

# Answer
> 8 votes
# JavaScript (ES6), 67 bytes

Takes input as 2 strings in currying syntax `(a)(b)`. Returns `false` for easy or `true` for not easy.

```
a=>b=>[...a].some((x,i,a)=>[...b].some(y=>(a[-++i]=~~a[-i]+x*y)>9))

```

### Test cases

```
let f =

a=>b=>[...a].some((x,i,a)=>[...b].some(y=>(a[-++i]=~~a[-i]+x*y)>9))

console.log('[Easy]')
console.log(f('331')('1021'))
console.log(f('1021')('331'))
console.log(f('101')('99'))
console.log(f('333')('11111'))
console.log(f('243')('201'))

console.log('[Not so easy]')
console.log(f('431')('1021'))
console.log(f('12')('16'))
console.log(f('3')('4'))
console.log(f('3333')('1111'))
console.log(f('310')('13'))
```

---

# Alt. version (flawed), ~~64~~ ~~55~~ 52 bytes

*Saved 3 bytes by taking strings, as suggested by @Shaggy*
*As pointed out by @LeakyNun, this method would fail on some large specific integers*

Takes input as 2 strings in currying syntax `(a)(b)`. Returns `true` for easy or `false` for not easy.

```
a=>b=>/^.(0.)*$/.test((g=n=>[...n].join`0`)(a)*g(b))

```

### Test cases

```
let f =

a=>b=>/^.(0.)*$/.test((g=n=>[...n].join`0`)(a)*g(b))

console.log('[Easy]')
console.log(f('331')('1021'))
console.log(f('1021')('331'))
console.log(f('101')('99'))
console.log(f('333')('11111'))
console.log(f('243')('201'))

console.log('[Not so easy]')
console.log(f('431')('1021'))
console.log(f('12')('16'))
console.log(f('3')('4'))
console.log(f('3333')('1111'))
console.log(f('310')('13'))
```

### How?

The idea here is to explicitly expose carries by inserting zeros before each digit of each factor.

Examples:

* **331 x 1021** becomes **30301 x 1000201**, which gives **30307090501** instead of **337951**. By adding a leading zero to the result and grouping all digits by 2, this can be written as **03 03 07 09 05 01**. All groups are less than **10**, meaning that there would not have been any carry in the standard multiplication.
* **431 x 1021** becomes **40301 x 1000201**, which gives **40309100501** and can be written as **04 03 09 10 05 01**. This time, we have a **10** which reveals a carry in the standard multiplication.

# Answer
> 6 votes
# Alice, 30 bytes

```
/Q.\d3-&+k!*?-n/ o @
\ic/*2&w~

```

Try it online!

Outputs `1` for easy and `0` for hard.

The numbers are easy to multiply if and only if the digit sum of the product equals the product of the digit sums.

```
/i    Input both numbers as a single string
.     Duplicate this string
/*    Coerce into two integers and multiply
2&w   Push return address twice (do the following three times)
~\Q     Swap the top two stack entries, then reverse the stack
        This produces a 3-cycle, and the first iteration coerces
        the original input string into two integers
c       Convert into individual characters
\d3-&+  Add all numbers on the stack except the bottom two (i.e., add all digits)
k     Return to pushed address (end loop)
      At this point, all three numbers are replaced by their digit sums
!*?   Multiply the digit sums of the original two numbers
-     Subtract the digit sum of the product
n     Logical negate: convert to 1 or 0
/o@   Output as character and terminate

```

# Answer
> 4 votes
# , ~~135~~ ~~110~~ ~~109~~ 86 bytes

```
function(m,n)any(convolve(m%/%10^(nchar(m):1-1)%%10,n%/%10^(1:nchar(n)-1)%%10,,"o")>9)

```

Try it online!

~~Takes input as strings.~~

~~It's ugly but it works™.~~

This now uses a convolution approach, as in Leaky Nun's answer, so it takes input as integers, and returns `TRUE` for hard to multiply numbers and `FALSE` for easy to multiply ones.

I have always had some trouble porting convolution approaches in the past, but today I finally read the documentation:

> Note that the usual definition of convolution of two sequences `x` and `y` is given by `convolve(x, rev(y), type = "o")`

Which is just silly. So the digit extraction is reversed for `n`, and it resolves into a port of Leaky Nun's answer.

# Answer
> 4 votes
# MATL, 10 bytes

```
,j!U]Y+9>a

```

Outputs `0` for easy, `1` for hard.

Try it online! Or verify all test cases.

### Explanation

```
,       % Do twice
  j     %   Input as a string
  !     %   Transpose into a column vector of characters
  U     %   Convert each character to number. Gives a numeric column vector
]       % End
Y+      % Convolution, full size
9>      % Greatear than 1? Element-wise
a       % Any: true if there is some true entry. Implicitly display

```

# Answer
> 4 votes
# Python 2, 88 bytes

```
lambda n,m:any(sum(n/10**(k-j)%10*(m/10**j%10)for j in range(k+1))>9for k in range(n+m))

```

Takes two integers as input and returns `False` (easy to multiply) or `True` (not).

Try it online! (too slow for one of the test cases)

# Answer
> 4 votes
# JavaScript (Node.js), ~~43~~ ~~41~~ ~~37~~ 36 bytes

Thanks @*Dennis* for the idea of using string interpolation in this answer and save 4 bytes!

Thanks @*ØrjanJohansen* for -1!

```
a=>b=>eval(`0x${a}*0x${b}<0x${a*b}`)

```

Try it online!

Of course when the destination base is less than the original base (like in my Jelly answer, the base is 2) the `<` must be flipped.

# Answer
> 3 votes
# Python 2, ~~158~~ ~~135~~ ~~123~~ 113 bytes

-12 bytes thanks to Leaky Nun -10 bytes thanks to ovs

```
a,b=input()
e=enumerate
l=[0,0]*len(a+b)
for i,x in e(a):
 for j,y in e(b):l[i-~j]+=int(x)*int(y)
print max(l)<10

```

Try it online! or Try all test cases

# Answer
> 3 votes
# Wolfram Language (Mathematica), ~~75~~ ~~66~~ ~~65~~ 56 bytes

```
f:=#~FromDigits~x&
g:=Max@CoefficientList[f@#2f@#,x]<=9&

```

Try it online!

Receiving 2 string inputs

Explanation:

```
f:=#~FromDigits~x&                      (* Turns the number to a polynomial
                                           with the digits as coefficients      *)
g:=Max@CoefficientList[f@#2f@#,x]<=9&   (* Polynomial multiplication, and check
                                           whether all coefficients are smaller
                                           than 10                              *)

```

-9 for changing to use string as input

-1 for using infix operator

-9 Thanks @MartinEnder for the `Max` function

# Answer
> 3 votes
# Julia 0.6, 30 bytes

```
~x=any(conv(digits.(x)...).>9)

```

Try it online!

Input is a tuple of numbers, output is `true` for hard to multiply numbers and `false` for easy ones.

`.` is element-wise function application.

`...` expands the tuple (of lists of integer digits) to two seperate inputs of the `conv` function.

# Answer
> 3 votes
# SNOBOL4 (CSNOBOL4), ~~268~~ ~~264~~ ~~247~~ ~~246~~ ~~243~~ 131 bytes

```
	DEFINE('D(A)')
	M =INPUT
	N =INPUT
	OUTPUT =EQ(D(M) * D(N),D(M * N)) 1	:(END)
D	A LEN(1) . X REM . A	:F(RETURN)
	D =D + X	:(D)
END

```

Try it online!

Ports the approach by Nitrodon. I think this is the first time I've ever defined a function in SNOBOL, `D` for digit sum.

```
	DEFINE('D(A)')					;* function definition
	M =INPUT					;* read input
	N =INPUT					;* read input
	OUTPUT =EQ(D(M) * D(N),D(M * N)) 1	:(END)	;* if D(M)*D(N)==D(M*N),
							;* print 1 else print nothing. Goto End
D	A LEN(1) . X REM . A	:F(RETURN)		;* function body
	D =D + X	:(D)				;* add X to D
END

```

### old version, 243 bytes:

```
	M =INPUT
	N =INPUT
	P =SIZE(M)
	Q =SIZE(N)
	G =ARRAY(P + Q)
Z	OUTPUT =LE(P)	:S(E)
	M LEN(P) LEN(1) . A
	J =Q
Y	GT(J)	:F(D)
	N LEN(J) LEN(1) . B
	W =I + J
	X =G<W> + A * B
	G<W> =LE(A * B,9) LE(X,9) X	:F(E)
	J =J - 1	:(Y)
D	P =P - 1	:(Z)
E
END

```

Try it online!

Input on STDIN separated by newlines, output to STDOUT: a single newline for easy to multiply, and no output for not easy to multiply.

This isn't going to win any awards but it presents another approach (well, really this is the naive approach). I don't think I could write this up in cubix, but SNOBOL is tough enough to work with as it is.

~~Since it takes input as a string, this will work for any input with less than 512 digits each; I'm not 100% sure how big `ARRAY`s in SNOBOL can be.~~

INPUT is buffered in this version of SNOBOL to have a maximum width of 1024 characters; all other characters are then lost. It appears that an ARRAY can be quite large; well over the 2048 cells necessary.

```
	M =INPUT				;*read input
	N =INPUT				;*read input
	P =SIZE(M)				;*P = number of M's digits, also iteration counter for outer loop
	Q =SIZE(N)				;*Q = number of N's digits
	G =ARRAY(P + Q)				;*G is an empty array of length P + Q
Z	GE(P)	:F(T)				;*if P<0, goto T (outer loop condition)
	M LEN(P) LEN(1) . A			;*A = P'th character of M
	J =Q					;*J is the iteration counter for inner loop
Y	GT(J)	:F(D)				;*if J<=0, goto D (inner loop condition)
	N LEN(J) LEN(1) . B			;*B = J'th character of N
	W =I + J				;*W=I+J, column number in multiplication
	X =G<W> + A * B				;*X=G[W]+A*B, temp variable for golfing
	G<W> =LE(A * B,9) LE(X,9) X	:F(END)	;*if A*B<=9 and X<=9, G[W]=X otherwise terminate with no output
	J =J - 1	:(Y)			;*decrement J, goto Y
D	P =P - 1	:(Z)			;*decrement P, goto Z
T	OUTPUT =				;*set output to ''; OUTPUT automatically prints a newline.
END

```

# Answer
> 3 votes
# Python 3, ~~58~~ ~~3513~~ ~~40~~ 39 bytes

```
lambda n,m:eval(f'0x{n}*0x{m}<0x{n*m}')

```

Looks like I had this idea two hours too late.

*Thanks to @ØrjanJohansen for golfing off 1 byte!*

Try it online!

# Answer
> 2 votes
# Charcoal, 38 bytes

```
≔Ｅ⁺θη⁰ζＦＬθＦＬη§≔ζ⁺ικ⁺§ζ⁺ικ×Ｉ§θιＩ§ηκ‹⌈ζχ

```

Try it online! Link is to verbose version of code. Outputs a `-` when the numbers are easy to multiply. Explanation:

```
≔Ｅ⁺θη⁰ζ

```

Initialise `z` to a large enough (sum of lengths of inputs) array of zeros.

```
ＦＬθＦＬη

```

Loop over the indices of the inputs `q` and `h`.

```
§≔ζ⁺ικ⁺§ζ⁺ικ×Ｉ§θιＩ§ηκ

```

Perform one step of the long multiplication.

```
‹⌈ζχ

```

Check for carries.

# Answer
> 2 votes
# Pari/GP, 52 bytes

```
f(a,b)=vecmax(Vec(Pol(digits(a))*Pol(digits(b))))<10

```

Try it online!

# Answer
> 2 votes
## Haskell, ~~82~~ 81 bytes

```
q=map$read.pure
f a=any(>9).concat.scanr((.(0:)).zipWith(+).(<$>q a).(*))(0<$a).q

```

The numbers a taken as strings. Returns `False` if the numbers are easy to multiply and `True` otherwise.

Try it online!

I think it's different enough from @Laikoni's answer. How it works:

```
q                    -- helper function to turn a string into a list of digits

f a =                -- main function, first number is parameter 'a'
      scanr    .q    -- fold the following function from the right (and collect
                     -- the intermediate results in a list) into the list of
                     -- digits of the second number
            0<$a     --   starting with as many 0s as there are digits in 'a'
                     -- the function is, translated to non-point free:
  \n c->zipWith(+)((*n)<$>q a)$0:c
                     -- 'n': next digit of 'b'; 'c': value so far
        (*n)<$>a     --    multiplay each digit in 'a' with 'n'
        0:c          --    prepend a 0 to 'c'
        zipWith(+)   --    add both lists element wise
                     --    (this shifts out the last digit of 'c' in every step)
   concat            -- flatten the collected lists into a single list
 any(>9)             -- check if any number is >9

```

# Answer
> 2 votes
# Haskell, ~~45~~ 44 bytes

Edit:

* -1 byte changing `==` to `<`.

I thought of this before looking at the other answers, then discovered that the Alice one used the same basic idea. Posting anyway since it's shorter than the other Haskell answers.

`?` takes two integers and returns a `Bool`. Use as `331?1021`. `False` means the multiplication is easy.

```
a?b=s(a*b)<s a*s b
s=sum.map(read.pure).show

```

Try it online!

* `s` is a function that calculates the sum of the digits of an integer. (`read.pure` converts a single digit character to an integer.)
* If a pair of numbers is easy to multiply, the digit sum of the product is equal to the product of the digit sums.
* Conversely, any carry during the long multiplication will reduce the digit sum of the product from that ideal.

# Answer
> 1 votes
# Ruby, 69 bytes

```
->a,b{(0..a+b=~/$/).all?{|r|(0..r).sum{|w|a[w].to_i*b[r-w].to_i}<10}}

```

Try it online!

# Answer
> 1 votes
# Haskell, 123 bytes

```
import Data.List
r=read.pure
a%b|l<-transpose[reverse$map((*r d).r)b++(0<$e)|d:e<-scanr(:)""a]=all(<10)$concat l++map sum l

```

Try it online! Example usage: `"331" % "1021"` yields `True`.

# Answer
> 1 votes
# Perl 5, 100 + 2 (`-F`) = 102 bytes

```
push@a,[reverse@F]}{map{for$j(@{$a[0]}){$b[$i++].='+'.$_*$j}$i=++$c}@{$a[1]};map$\||=9>eval,@b;say$\

```

Try it online!

outputs false for easy, true for not easy.

# Answer
> 1 votes
# Jelly, 8 bytes

```
;PDḄµṪ⁼P

```

Try it online!

A port of my Javascript answer. Not shorter than the existing Jelly answer because Jelly have powerful convolution built-in.

Take input as a list of two numbers. Returns `1` for easy, `0` for not easy.

---

Explanation:

```

;PDḄµṪ⁼P     Main link. Let input = [101, 99]
;P           Concatenate with product. Get [101, 99, 9999]
  D          Convert to decimal. Get [[1,0,1], [9,9], [9,9,9,9]]
   Ḅ         Convert from binary. Get [1 * 2^2 + 0 * 2^1 + 1 * 2^0,
             9 * 2^1 + 9 * 2^0, 9 * 2^3 + 9 * 2^2 + 9 * 2^1 + 9 * 2^0]
             = [5, 27, 135]
    µ        With that value,
     Ṫ       Take the tail from that value. Get 135, have [5, 27] remain.
      ⁼      Check equality with...
       P       The product of the remaining numbers (5 and 17).

```

# Answer
> 1 votes
# C (gcc), 104 bytes

Basically do a multiplication "by hand" into r\[\] and set return value if any column gets higher than 9, since that would mean a carry has occurred.

Surprisingly, this was shorter than my first attempt which took strings as arguments.

```
f(a,b){int*q,r[10]={0},*p=r,R=0,B;for(;a;a/=10)for(q=p++,B=b;B;B/=10)R|=(*q+++=a%10*(B%10))>9;return R;}

```

Try it online!

# Answer
> 1 votes
# Husk, 10 bytes

```
§§=¤`o*oΣd

```

Try it online! Outputs `1` if the arguments are easy to multiply, and `0` otherwise. A port of Nitrodon's answer.

# Answer
> 1 votes
# CJam, 18 bytes

```
{_{Ab:+}:T/*\:*T=}

```

Try it online!

Takes input on the stack in the form of `[1021 331]`. Checks that the product of the sum of the digits and the sum of the digits of the product are equal.

To take input as a space-delimited string, remove the outer curly braces and prepend with `q~]`.

## Alternate 18-byter

```
{{'0*i}/*`);-2%i!}

```

Try it online!

Takes input on the stack in the form of `["1021" "331"]`. A port of Arnauld's fantastic answer.

To take input as a space-delimited string, remove the outer curly braces and prepend with `qS/`.

---
Tags: code-golf, arithmetic, decision-problem
---


# Question
Title: Distribute a number into a list of values as equal as possible whose sum is equal to that number
Probably a simple code-golf challenge. Given 2 positive integers `m` and `n`, make a list of `n` values that are positive integers whose sum is equal to the number `m`. Either all values in the output are the same value or the difference is exactly 1.

**Examples**

For example

* `m=6` and `n=3` would become `2, 2, 2`
* `m=7` and `n=3` would become `2, 2, 3` or `2, 3, 2` or `3, 2, 2`
* `m=7` and `n=2` would become `3, 4` or `4, 3`
* `m=7` and `n=1` would become `7`
* `m=7` and `n=8` would generate an error because the sum of 8 positive integers cannot be 7.
* `m=10` and `n=4` would become `3, 3, 2, 2` or any other permutation

**Rules**

* Both input and output is only about positive integers.
* Either all values in the output are the same value or the difference is exactly 1.
* The order of the values in the list is not important.
* The sum of the values in the list is equal to `m`.
* When it's not solvable, generate an error or a false value (in case of m=7 and n=8 for example).
* As a result of the other rules `m=8` and `n=3` would generate any of the permutations of `3, 3, 2` (not `2, 2, 4`)

**The winner**

This is code-golf, so the shortest valid answer – measured in bytes – wins.

# Answer
> 2 votes
# Gaia, 4 bytes

```
…÷l¦

```

There's almost just a built-in for this...

### Explanation

```
…     Get the range [0 .. m-1].
 ÷    Split into n roughly even length chunks. Throws an error if the number of chunks if
       more than the list's length.
  l¦  Get the length of each chunk.

```

# Answer
> 8 votes
# Python 2, ~~48~~ 43 bytes

Returns `0` on error.

```
lambda m,n:m/n and[m/n]*(n-m%n)+m%n*[m/n+1]

```

Try it online!

---

### 41 bytes (with @xnor's trick)

Throws `NameError` on error.

```
lambda m,n:[m/n or _]*(n-m%n)+m%n*[m/n+1]

```

Try it online!

# Answer
> 6 votes
# MATL, 7 bytes

```
:gie!Xs

```

When there is no solution the output is an array containing at least one zero, which is falsy in MATL.

**Try it online!**

### Explanation

Consider inputs `m = 10` and `n = 4`.

```
:      % Implicitly input m. Push [1 2 ... m]
       % STACK: [1 2 3 4 5 6 7 8 9 10]
g      % Logical: convert nonzeros to 1
       % STACK: [1 1 1 1 1 1 1 1 1 1]
i      % Input n
       % STACK: [1 1 1 1 1 1 1 1 1 1], 4
e      % Reshape into matrix with n rows, padding with zeros
       % STACK: [1 1 1;
                 1 1 1;
                 1 1 0;
                 1 1 0]
!      % Transpose
       % STACK: [1 1 1 1;
                 1 1 1 1;
                 1 1 0 0]
Xs     % Sum of each column. Implicitly display
       % STACK: [3 3 2 2]

```

# Answer
> 5 votes
# Mathematica, 33 bytes

```
#>#2&&Last@IntegerPartitions@##1&

```

**input**

> \[63, 11\]

**output**

> {6, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5}

outputs ***False*** when it's not solvable

# Answer
> 5 votes
# Haskell, 30 bytes

```
m%n|m>=n=map(`div`n)[m..m+n-1]

```

Try it online!

# Answer
> 4 votes
# Charcoal, 15 bytes after applying NDD1

```
¿÷ＮＮＩＥＩη÷⁺ＩθιＩη

```

Try it online!

Outputs nothing if there is no solution. Link to the verbose version.

1NDD = Neil-Driven Development.

My previous answer:

# Charcoal, 32 27 24 20 bytes

```
ＮμＮν¿÷μνＩＥν⁺÷μν‹ι﹪μν

```

Try it online!

Outputs nothing if there is no solution. Link to the verbose version.

Of course, I couldn't have golfed it down without Neil's help.

# Answer
> 3 votes
# , 33 bytes

```
function(m,n)diff(trunc(0:n*m/n))

```

A port of Luis Mendo's Octave answer. Pretty sad that this is almost 50% shorter than my previous answer.

Try it online!

### previous answer, 63 bytes:

```
function(m,n,o=rep(m%/%n,n),d=m-sum(o))o+c(rep(0,n-d),rep(1,d))

```

An anonymous function that takes two (mandatory) arguments `m` and `n`, and two optional ones which are for golfing purposes. Returns a vector in increasing order. For failure, the first value will be `0`, which is falsey in R, since `if` only uses the first value of the vector (with a warning).

It is essentially equivalent to the following function:

```
function(m,n){o=rep(m%/%n,n)
d=m-sum(o)
o+c(rep(0,n-d),rep(1,d))}

```

Try it online!

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

```
:ȧœsL€

```

Try it online! Outputs nothing for falsy.

### How it works

```
:ȧœsL€    Main link. Arguments: m (integer), n (integer)
:         Integer division. Yields 0 if m < n; a positive integer otherwise.
 ȧ        Logical AND. Yields 0 if m < n; m otherwise.
  œs      Split into n roughly equal groups. Since the left argument is an integer,
          this implicitly converts it to [1..m] (or [] for 0) before splitting.
    L€    Length of €ach. If the inputs were 7 and 3, the previous result would be
          [[1,2,3],[4,5],[6,7]], so this would give [3,2,2].

```

# Answer
> 2 votes
# Octave, 24 bytes

```
@(m,n)diff(fix(0:m/n:m))

```

The code defines an anonymous function. The output is a numeric array (row vector). When there is no this array contains at least one zero, which is falsy in Octave.

**Try it online!**

### Explanation

`0:m/n:m` produces an array of `n+1` values from `0` to `m` with step `m/n`. `fix` rounds each entry towards `0`, and `diff` computes consecutive differences.

As an example, here are all intermediate results for `m = 7`, `n = 3`:

```
>> 0:m/n:m
ans =
         0    2.3333    4.6667    7.0000

>> fix(0:m/n:m)
ans =
     0     2     4     7

>> diff(fix(0:m/n:m))
ans =
     2     2     3

```

# Answer
> 2 votes
# C# (.NET Core), 86 82 71 bytes

```
using System.Linq;a=>b=>new int[b].Select((x,i)=>(i<a%b?1:0/(a/b))+a/b)

```

throws an error for invalid inputs.

Try it online!

-4 bytes thanks to *TheLethalCoder*

-11 bytes thanks to *OlivierGrégoire*

# Answer
> 2 votes
# Haskell, ~~93~~ ~~89~~ ~~88~~ ~~87~~ ~~86~~ 71 bytes

```
m!n|n<=m=e$m:(0<$[2..n])
e(a:b:x)|b<a=e$a-1:e(b+1:x)
e(a:x)=a:e x
e x=x

```

Try it online!

## Explanation

The main function here is `e`. `e` will take a list and essentially run a rolling pin along it from left to right. While there is an element in the list that is greater than its neighbor to the right we will move one from it to the right.

Now all we have to do is feed this function a sufficiently lopsided list and allow it to do the magic. The list we will choose is just `m` followed by `n-1` zeros. Since that is easy to make.

The last thing we need to do is make sure that the error case is handled. For this we just throw a `Non-exhaustive patterns in function` error as long as `m>n`.

# Answer
> 2 votes
## TI-Basic, 23 bytes

```
:Prompt M,N
:N(M≥N
:int(Ans⁻¹randIntNoRep(M,M+N-1

```

Returns ERR:DIVIDE BY 0 on error

# Answer
> 2 votes
## Haskell, 48 bytes

```
m#n|m>=n=iterate(\(a:b)->b++[a+1])(0<$[1..n])!!m

```

Start with a list of `n` zeros. Repeat `m` times: take the first element, add one and put it at the end of the list.

Fails with a pattern match error if `n < m`.

Try it online!

# Answer
> 1 votes
# Javascript (ES6), ~~57 56 53~~ 41 bytes

```
m=>n=>m>=n&&[...Array(n)].map(_=>m++/n|0)

```

Answer now includes smarter way of creating the values. Thanks @Neil

**Usage**

```
f=m=>n=>m>=n&&[...Array(n)].map(_=>m++/n|0)

f(6)(3) // [2, 2, 2]
f(7)(3) // [3, 2, 2]
f(7)(2) // [4, 3]
f(7)(1) // [7]
f(7)(8) // false
f(8)(3) // [3, 3, 2]

```

**History**

First mine

```
(m,n)=>m>=n&&Array(n).fill(~~(m/n)).map((v,i)=>v+(i<m%n))

(m,n)=>m>=n&&Array(n).fill().map((v,i)=>~~(m/n)+(i<m%n))

```

Then added the spread operator and currying syntax tipped by @Arnauld

```
m=>n=>m>=n&&[...Array(n)].map((v,i)=>~~(m/n)+(i<m%n))

```

# Answer
> 1 votes
# PHP\>=7.1, 62 bytes

```
for([,$s,$n]=$argv;$n;)$s-=$r[]=$s/$n--^0;$r[0]?print_r($r):0;

```

PHP Sandbox Online

# Answer
> 1 votes
# Braingolf, 30 bytes

```
.M>.M/v.mR>[.]$_v%!?[R1+>v]|R=

```

Try it online!

Takes inputs in reverse order (`n` is first input, `m` is second)

Divides `m` by `n`, duplicates the result `n` times, then loops through and increments one by one `m % n` times

# Answer
> 1 votes
## Batch, 71 bytes

```
@if %1 geq %2 for /l %%i in (1,1,%2)do @cmd/cset/an=(%1+%%i-1)/%2&echo(

```

`cmd/cset/a` doesn't output any separator, so I have to use `echo(` (`(` avoids printing `ECHO is on.`).

# Answer
> 1 votes
# Python 2, 41 bytes

```
lambda m,n:(m%n*[m/n+1]+[m/n or _]*n)[:n]

```

Try it online!

`NameError` when impossible.

---

**Python 2, 43 bytes**

```
lambda m,n:[c/n for c in range(m,m+n,m>=n)]

```

Try it online!

`ValueError` when impossible.

# Answer
> 1 votes
# Java (OpenJDK 8), ~~80~~ ~~73~~ ~~63~~ ~~61~~ 59 bytes

```
n->m->{for(int i=n;i-->0/(m/n);)System.out.println(m++/n);}

```

Try it online!

Note, for currying purpose, `m` and `n` are reversed.

# Answer
> 1 votes
# Pyth, 11 bytes

```
efqlTeQ./hQ

```

Try it online!

# Answer
> 1 votes
# Husk, 15 bytes

```
S`?ø▼Ẋ-mo÷³*⁰Θḣ

```

Try it online! A port of Luis Mendo's answer. Takes `n` followed by `m` as arguments. Outputs an empty list when no solution is possible.

# Answer
> 0 votes
# Pyth, 13 bytes

```
KE?>KQ0lMcK*d

```

Try it online! Output `0` on error.

**Cheating, 6 bytes**

```
lMcE*d

```

Try it online! The array contains a `0` on error. Sadly this isn't falsy in Pyth.

**Explanation**

```
KE?>KQ0lMcK*dQ    # Implicit input Q for m
KE                # Store n in K
           *d     # Generate a string of length Q containing only spaces
         cK       # Chop this string in K pieces of equal sizes, initial piece longer if necessary
       lM         # For each string, compute the length. Here we already have our result. However if the array contain a zero, we must output a falsy value
  ?>KQ            # If K > Q...
      0           # Then display zero, otherwise display the array

```

# Answer
> 0 votes
# CJam, ~~13~~ 12 bytes

```
{_2$>/,/z:,}

```

Try it online!

This is an anonymous block that takes the input as `n m` on the stack. It would have been a good answer, but the error handling requirement completely killed it.

Errors with a divide-by-zero when it's not possible to solve.

## Explanation

```
{   e# Stack:                | 3 10
 _  e# Duplicate:            | 3 10 10
 2$ e# Copy from back:       | 3 10 10 3
 >  e# Greater than:         | 3 10 1 (true)
 /  e# Divide:               | 3 10
    e# This will cause an error on invalid input.
 ,  e# Range:                | 3 [0 1 2 3 4 5 6 7 8 9]
 /  e# Split on nth element: | [[0 1 2] [3 4 5] [6 7 8] [9]]
 z  e# Transpose array:      | [[0 3 4 9] [1 4 7] [2 5 8]]
 :, e# Length of each:       | [4 3 3]
}

```

If the error-handling requirement is lifted, this can be shortened to 7 bytes, which is a decrease of over 40%:

```
{,/z:,}

```

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


title: Rank a list of integers

text:
# Question
Title: Rank a list of integers
You're given a non-empty list of positive integers, e.g.

```
[6 2 9 7 2 6 5 3 3 4]

```

You should rank these numbers by their value, but as is usual in leaderboards, if there is a tie then all the tied numbers get the same rank, and an appropriate number of ranks is skipped. The expected output for the above list would therefore be

```
[3 9 1 2 9 3 5 7 7 6]

```

For example, the highest value in the input was `9`, so this becomes a `1` (first rank). The third highest value is `6`, so both `6`s become `3`, and the rank `4` is skipped entirely.

## Rules

You can use any convenient, unambiguous, flat list format for input and output. The first/smallest rank in the output should always be **1**.

You may write a program or a function and use any of the our standard methods of receiving input and providing output.

You may use any programming language, but note that these loopholes are forbidden by default.

This is , so the shortest valid answer – measured in *bytes* – wins.

## Test Cases

```
[8] -> [1]
[1 15] -> [2 1]
[18 14 11] -> [1 2 3]
[11 16 14 8] -> [3 1 2 4]
[15 15 15 15 15] -> [1 1 1 1 1]
[10 2 5 4 15 5] -> [2 6 3 5 1 3]
[5 5 10 10 5 11 18] -> [5 5 3 3 5 2 1]
[2 4 9 4 17 9 17 16] -> [8 6 4 6 1 4 1 3]
[11 17 19 17 10 10 15 3 18] -> [6 3 1 3 7 7 5 9 2]
[2 11 4 8 3 3 12 20 4 18] -> [10 4 6 5 8 8 3 1 6 2]
[12 6 10 2 19 19 6 19 8 6 18] -> [5 8 6 11 1 1 8 1 7 8 4]
[5 6 14 19 13 5 19 9 19 9 9 19] -> [11 10 5 1 6 11 1 7 1 7 7 1]
[9 2 12 3 7 11 15 11 6 8 11 17 11] -> [8 13 3 12 10 4 2 4 11 9 4 1 4]
[3 5 15 7 18 5 3 9 11 2 18 1 10 19] -> [11 9 4 8 2 9 11 7 5 13 2 14 6 1]
[6 11 4 19 14 7 13 16 10 12 7 9 7 10 10] -> [14 6 15 1 3 11 4 2 7 5 11 10 11 7 7]
[11 20 11 1 20 16 11 11 4 8 9 7 11 14 10 14] -> [6 1 6 16 1 3 6 6 15 13 12 14 6 4 11 4]
[4 7 15 2 3 2 3 1 14 2 10 4 7 6 11 2 18] -> [9 6 2 13 11 13 11 17 3 13 5 9 6 8 4 13 1]
[5 1 17 7 1 9 3 6 9 7 6 3 2 18 14 4 18 16] -> [12 17 3 8 17 6 14 10 6 8 10 14 16 1 5 13 1 4]
[5 6 8 10 18 13 20 10 7 1 8 19 20 10 10 18 7 2 1] -> [16 15 11 7 4 6 1 7 13 18 11 3 1 7 7 4 13 17 18]
[12 17 8 2 9 7 15 6 19 5 13 16 14 20 10 11 18 4 3 1] -> [9 4 13 19 12 14 6 15 2 16 8 5 7 1 11 10 3 17 18 20]

```

# Answer
> 14 votes
# Workaround in Excel for silly Rules Regarding Mouse Inputs on Code Golf Stack Exchange: (WESRRMICGSE) 28 bytes

`rank(RC[1],r1c1:r1024:c1024)`

Input list as csv (`10,23,34,2,`) into the compiler after entering the source. no quotes, no brackets, trailing comma.

WESRRMICGSE is exactly like programming in excel, except you can omit the initial '=' sign to save a byte. The difference in functionality comes from the fact that WESRRMICGSE will either drag the formula down to copy the code automatically and provide different outputs provided with a single integer input. provided a list as input, that list goes into the B column (input column), and the formula is drug down automatically to match the number of inputs. (eg: the input 34,21,45, would 'drag' the formula down 2 cells, for a total of 3 cells with the formula).

Edit: I never expected this answer to be popular. Wow!

# Answer
> 11 votes
# MATL, 4 bytes

```
&<sQ

```

Try it online! Or verify all test cases.

### Explanation

```
&<   % Input array implicitly. Matrix of all pairwise "less than" comparisons
s    % Sum of each column
Q    % Add 1. Display implicitly

```

# Answer
> 9 votes
## Python 2, 41 bytes

```
lambda l:map(sorted(l+[l])[::-1].index,l)

```

For each value, find its index in the list sorted by decreasing order. To make the largest value give 1 instead of 0, we use an extra "infinity" element of the list itself, since Python 2 treats lists as bigger than numbers.

A more direct solution is 42 bytes and also works in Python 3.

```
lambda l:[1+sum(y<x for x in l)for y in l]

```

For each element, counts the number of smaller elements, adding 1 to shift to 1-indexed.

# Answer
> 8 votes
# Jelly, 5 bytes

```
ṢṚiÐ€

```

Try it online!

### How it works

```
ṢṚiÐ€  Main link. Argument: A (array)

ṢṚ     Sort and reverse A.
  iÐ€  Find the index of each n in A in the previous result.

```

# Answer
> 7 votes
# R, 24 ~~25~~ ~~20~~ bytes

Uses the standard rank function with the "min" ties method over the negated vector. `cat` added to output it to STDOUT. Saved one thanks to @Guiseppe

```
cat(rank(-scan(),,"mi"))

```

Example

```
> cat(rank(-scan(),,"mi"))
1: 9 2 12 3 7 11 15 11 6 8 11 17 11
14:
Read 13 items
8 13 3 12 10 4 2 4 11 9 4 1 4
>

```

# Answer
> 4 votes
## PowerShell v2+, ~~43~~ 41 bytes

```
($a=$args)|%{@($a|sort -d).indexof($_)+1}

```

Developed independently, but I see that this is the same algorithm as @xnor's Python solution, so /shrug.

Takes input as individual command-line arguments (i.e., a space separated list). Output (default formatting) is a newline between elements.

For each element in the input list, it `sort`s the input list in `-d`escending order, takes the `.indexOf()` the current element, and adds `1`. Note the explicit array cast `@(...)` in order to account for a single-digit input. The resulting numbers are left on the pipeline and output is implicit.

Saved 2 bytes thanks to @Matt!

### Example

```
PS C:\Tools\Scripts\golfing> .\rank-the-integers.ps1 6 2 9 7 2 6 5 3 3 4
3
9
1
2
9
3
5
7
7
6

```

# Answer
> 3 votes
# Octave, 15 bytes

```
@(x)sum(x<x')+1

```

Port of my MATL answer to Octave. It also works in Matlab R2016b.

The code defines an anonymous function. To call it, assign it to a variable. Try it at Ideone.

# Answer
> 3 votes
## JavaScript (ES6), ~~38~~ 36 bytes

```
a=>a.map(e=>a.map(d=>r+=e<d,r=1)&&r)

```

Edit: Saved 2 bytes thanks to @ETHproductions.

# Answer
> 2 votes
# Jelly, 5 bytes

```
<S‘ð€

```

**TryItOnline!**

### How?

```
<S‘ð€ - Main link: listOfValues
   ð  - dyadic chain separation
    € - for each
<     - less than (vectorises) - yields a list of 1s and 0s
 S    - sum - yields number of values the current value is less than (those that beat it)
  ‘   - increment - the place of a value is the number that beat it plus 1.

```

# Answer
> 2 votes
# Perl 6,  ~~42~~  26 bytes

Find the first index `:k` in a reversed `[R,]` sorted list

```
{map {[R,](.sort).first(*==$^a,:k)+1},@$_}

```

Count the values that are larger, and add one

```
{map {1+.grep(*>$^a)},@$_}

```

# Answer
> 2 votes
# JavaScript, ~~87~~ 49 bytes

~~`f=a=>a.slice().map(function(v){return a.sort(function(a,b){return b-a}).indexOf(v)+1 })`~~

`a=>[...a].map(v=>a.sort((a,b)=>b-a).indexOf(v)+1)`

Thanks Conor O'Brien and ETHproductions!

# Answer
> 2 votes
# , ~~14~~ 8 bytes

```
1+1#.</~

```

### How?

```
1+1#.</~ - Consumes and returns a list of integers
       ~ - Use the same list for both inputs
     </  - Create a table of less-than comparisons
  1#.    - Treat each row like digits of a base-one number, returning a list of integers
1+       - Increment the results

```

### Previous solution

```
1+(+/@:<)"0 1~

```

# Answer
> 2 votes
## Mathematica, 44 bytes 42 bytes 40 bytes

```
xPosition[SortBy[x,-#&],#][[1,1]]&/@x

```

is the 3 byte private use character `U+F4A1` (Wolfram docs page)

Edit: Thanks to JHM for the byte savings.

# Answer
> 2 votes
## Pyke, 6 bytes

```
FQS_@h

```

Try it here!

```
F      - for i in input():
 QS    -     sorted(input())
   _   -    reversed(^)
    @  -   i.find(^)
     h -  ^+1 (not required if allowed to start from 0)

```

# Answer
> 1 votes
## Haskell, 28 bytes

```
f l=[1+sum[1|y<-l,y>x]|x<-l]

```

Just some list comprehensions.

# Answer
> 1 votes
# Wonder, 28 bytes

```
@(->@+1:0iO#0rev sort#I#1)#0

```

Usage:

```
(@(->@+1:0iO#0rev sort#I#1)#0)[6 2 9 7 2 6 5 3 3 4]

```

Map over input array with a function that adds 1 to the first index of the item in a descending-sorted version of the input.

# Answer
> 1 votes
# Dyalog APL, 7 bytes

```
⊢⍳⍨⍒⊃¨⊂

```

arguments'

`⍳⍨` indices in

the indices which would sort the argument descending

`⊃¨` each picked from

the entire argument

TryAPL online!

# Answer
> 1 votes
# Mathematica, 37 bytes

```
Min@Position[-Sort@-#,i]~Table~{i,#}&

```

A pure function which will rank it's input, as per the rules of the problem. Ex:

```
Min@Position[-Sort@-#, i]~Table~{i, #} &[{6, 2, 9, 7, 2, 6, 5, 3, 3, 4}]
(*{3, 9, 1, 2, 9, 3, 5, 7, 7, 6}*)

```

# Answer
> 1 votes
## Jellyfish, 15 bytes

```
p`&& ~i
  >/+`<

```

Try it online!

### Explanation

There doesn't seem to be a good way to find the index of a value in a list in Jellyfish yet, so this uses the approach of counting how many values are bigger than current one and incrementing the result. This is largely done by constructing a unary function which computes this value for a given element.

```
     `<

```

This creates a threaded version of the comparison operator, so if you give this an integer and a list, it will return a list of comparison results between that integer and each element in the list.

```
     ~i
     `<

```

This curries the right-hand argument of the previous function with the input list. So the result is a unary function which takes an integer and gives you the list of comparison results with the input of the program.

```
   & ~i
   /+`<

```

Here, `/+` is reduction by addition, which means it's simply a "sum this list" function. `&` composes this onto the previous function, so we now have a unary function which *counts* how many values in the input are bigger than that integer.

```
  && ~i
  >/+`<

```

We also compose the increment function onto this.

```
 `&& ~i
  >/+`<

```

Finally, we thread this function as well, so that it's automatically applied to each integer of a list passed to it. Due to the layout of the code, `i` happens to be taken as the input of this function as well, so that this computes the desired output.

```
p`&& ~i
  >/+`<

```

Finally, this prints the result.

# Answer
> 1 votes
## brainfuck, 124 bytes

```
->,[>>>+>,]<[-<+]+[-->[<[<<<<]>>>+>[>[>>]<[[<<+<<]>+>[->>>>]]<+>>>]+[-<<+]->]<[<
<<<]>+.,>>[>[>->+>>]<<[-<<<<]>-]+[->+]+>>>>]

```

Formatted:

```
->
,[>>>+>,]
<[-<+]
+
[
  -->
  [
    <[<<<<]
    >>>+>
    [
      >[>>]
      <
      [
        [<<+<<]
        >+>[->>>>]
      ]
      <+> >>
    ]
    +[-<<+]
    ->
  ]
  <[<<<<]
  >+.,>>
  [
    >[>->+>>]
    <<[-<<<<]
    >-
  ]
  +[->+]
  +>>>>
]

```

This is designed for 8-bit brainfuck implementations. Input and output are via byte values.

Try it online.

For each element, this counts the number of elements greater than it, then prints the result plus one. This is accomplished by incrementing all elements until the current element equals zero, updating the result whenever another element becomes zero before the current element.

The tape is broken into 4-cell nodes,

`b c 0 0`

where `c` is the element and `b` is a navigation flag that is negative one for the current element, otherwise one.

The result and a copy of the current element are kept to the left of the array.

# Answer
> 1 votes
# Java, 215 bytes

```
public class G{public static void L(int[]A){int[]r=new int[A.length];for(int i=0;i<A.length;i++){int c=1;for(int j=0;j<A.length;j++){if(A[j]>A[i])c++;}r[i]=c;}for(int i=0;i<r.length;i++)System.out.print(r[i]+",");}}

```

Explanation:

Very self explanatory.

Basically for each integer in the array it checks how many are larger than it, then prints the new array with the rankings.

I'm sorry this isn't very concise but it's my first try at one of these and I didn't see an entry for java. I'm sure it can be golfed down more.

It can be run just by making reference to the static method and passing an array. I didn't think it was necessary to write the main function but if it is I'll do that in the future.

# Answer
> 1 votes
# Husk, 5 bytes

```
m€↔O¹

```

Try it online!

## Explanation

```
m€↔O¹
   O¹ sort the input in ascending order
  ↔   reverse it
m   ¹ map the input to:
 €    it's index in that list

```

# Answer
> 0 votes
# Ruby, ~~45~~ 40 bytes

```
->a{a.map{|x|a.sort.reverse.index(x)+1}}

```

# Answer
> 0 votes
# PHP, 101 bytes

There must be some shorter way.

```
function f(&$a){for($r=1;$v++<max($a);$r+=$n,$n=0)foreach($a as$k=>$w)if($w===$v){$a[$k]="$r";$n++;}}

```

function takes input as array of integers, overwrites input variable with ranks as numeric strings.

Usage: `$a=[1,2,4,2,2,3];f($a);print_r($a);`

# Answer
> 0 votes
# Clojure, ~~48~~ 44 bytes

Update: using `for` instead of `map`

```
#(for[i %](+(count(filter(partial < i)%))1))

```

Simply filters each value smaller than the current one, counts the length of the list and increments by one.

# Answer
> 0 votes
# Tcl, 54 bytes

```
proc R L {lmap x $L {lsearch .\ [lsort -r -de $L] $x}}

```

Try it online!

# Answer
> 0 votes
# PHP, 84 bytes

```
function r($l){$s=$l;rsort($s);foreach($l as$n)$r[]=array_search($n,$s)+1;return$r;}

```

Usage: Pass the function r your array of integers and it will return the corresponding array of ranked integers.

Passing tests here.

# Answer
> 0 votes
# Perl 5, 23 +2 (-ap)

```
s/\d+/1+grep$&<$_,@F/ge

```

Try it online

# Answer
> 0 votes
# K (oK), 11 bytes

**Solution:**

```
1+(x@>x)?x:

```

Try it online!

**Examples:**

```
1+(x@>x)?x:6 2 9 7 2 6 5 3 3 4
3 9 1 2 9 3 5 7 7 6
1+(x@>x)?x:5 6 14 19 13 5 19 9 19 9 9 19
11 10 5 1 6 11 1 7 1 7 7 1

```

**Explanation:**

Lookup position of original list in sorted list, then add one.

```
1+(x@>x)?x: / the solution
         x: / save input as x
  (  >x)    / return indices of x sorted in descending order
   x@       / apply these indices to x (thus sort x)
        ?   / lookup right in left
1+          / add one

```

---
Tags: code-golf, array, sorting
---


# Question
Title: Unscramble the letters by letter frequency analysis
You know those riddles where every letter is swapped for another letter?

E.g. you get a text like

```
JME JG EPP IFAPE EPJE CJPPPC BP,
      UIJCG JC EPP EFE GPJB EJIP EJ EJIP,
F EPJIG MPJEPPPP AJUC BJL UP
      GJP BL MICJIJMPPJUIP CJMI.

```

and are supposed to find out that it stands for

```
OUT OF THE NIGHT THAT COVERS ME,
      BLACK AS THE PIT FROM POLE TO POLE,
I THANK WHATEVER GODS MAY BE
      FOR MY UNCONQUERABLE SOUL.

```

This example was created by the following replacement matrix:

```
ABCDEFGHIJKLMNOPQRSTUVWXYZ
ODSXHKARFYGNBIQTJVCEWZMULP

```

Try to unscramble any given text by doing a letter frequency analysis. Assume that the most common letters in the given input are (left to right): `EARIOTNSLCUDPMHGBFYWKVXZJQ`

* Replace the most common letter in the input by E, the next most common by A, and so on
* Producing a correctly unscrambled text is actually outside the scope of this challenge. That is, we assume that you get a correct result if only the input is large enough. (Testcase 1)
* If there is insufficient data, your return value must be consistent with the data provided. (Testcase 2)
* You may expect uppercase text only. It can contain digits, punctuations etc., which are not scrambled and to be output as is.

This is a code golf, shortest answer in bytes wins. Standard loopholes apply.

## Testcase 1 - The shortest completely solvable one

```
CCCCCCCCCCCCCCCCCCCCCCCCCCPPPPPPPPPPPPPPPPPPPPPPPPPIIIIIIIIIIIIIIIIIIIIIIIIFFFFFFFFFFFFFFFFFFFFFFFEEEEEEEEEEEEEEEEEEEEEELLLLLLLLLLLLLLLLLLLLLPPPPPPPPPPPPPPPPPPPPFFFFFFFFFFFFFFFFFFFGGGGGGGGGGGGGGGGGGEEEEEEEEEEEEEEEEEIIIIIIIIIIIIIIIITTTTTTTTTTTTTTTMMMMMMMMMMMMMMJJJJJJJJJJJJJAAAAAAAAAAAAAAAAAAAAAAAWWWWWWWWWWDDDDDDDDDBBBBBBBBBBBBBBBFFFFFFTTTTTJJJJWWWIIP

```

must output

```
EEEEEEEEEEEEEEEEEEEEEEEEEEAAAAAAAAAAAAAAAAAAAAAAAAARRRRRRRRRRRRRRRRRRRRRRRRIIIIIIIIIIIIIIIIIIIIIIIOOOOOOOOOOOOOOOOOOOOOOTTTTTTTTTTTTTTTTTTTTTNNNNNNNNNNNNNNNNNNNNSSSSSSSSSSSSSSSSSSSLLLLLLLLLLLLLLLLLLCCCCCCCCCCCCCCCCCUUUUUUUUUUUUUUUUDDDDDDDDDDDDDDDPPPPPPPPPPPPPPMMMMMMMMMMMMMHHHHHHHHHHHHGGGGGGGGGGGBBBBBBBBBBFFFFFFFFFYYYYYYYYWWWWWWWKKKKKKVVVVVXXXXZZZJJQ

```

## Testcase 2

`HALLO WORLD` must output `??EEA<space>?A?E?`:

* The 3 Ls turn into E
* The 2 Os turn into A
* The remaining letters are each replaced by an undefined permutation of the letters "RIOTN", without any of these repeating.

# Answer
> 1 votes
# JavaScript (V8), 185 bytes

```
c=>(l={},[...c].map(i=>l[i]=(l[i]|0)+1),e=Object.entries(l).sort((a,b)=>b[1]-a[1]).map(i=>i[0]).filter(i=>parseInt(i,36)>9),[...c].map(i=>"EARIOTNSLCUDPMHGBFYWKVXZJQ"[e.indexOf(i)]||i))

```

Try it online!

Doesn't currently pass the second test case, but instead is based on OP's description of how the unscrambling works. The test case seems to be incorrect at the moment, as some groups of letters (like `F` or `P`) repeat letters.

**Explanation:**

```
c=>(                            // Define arrow function with argument c
l={},                           // Create an empty object l
[...c].map(i=>                  // For each character i in c...
  l[i]=(l[i]|0)+1),               // Increment l[i] (the number of times i appears)
e=Object.entries(l)             // Format l as an array ["x", <number of times "x" appears>] in variable e
.sort((a,b)=>b[1]-a[1])         // Sort e so most common characters are first
.map(i=>i[0])                   // Get rid of number of times appeared
.filter(i=>parseInt(i,36)>9),   // Filter out non-letters using base 36 conversion :)
[...c].map(i=>                  // For each character i in c...
  "EARIOTNSLCUDPMHGBFYWKVXZJQ"[   // Get the nth item from the frequency chart...
    e.indexOf(i)]                   // Where n is the index of i in e
    ||i))                         // Unless it isn't a letter, where i stays i

```

# Answer
> 1 votes
# Jelly, 35 bytes

```
“@u@Rṭ$3=ỊẈṘ’œ?ØA;0
QfØAċ@ÞðṚiⱮị¢ðo

```

Try it online!

Like Redwolf Programs' JS solution, this technically fails both given test cases, but seems to be consistent with the intent of the challenge.

---
Tags: code-golf, string, cipher
---