- Related Questions & Answers
- Beautiful Arrangement in C++
- Beautiful Arrangement II in C++
- Determining beautiful number string in JavaScript
- Beautiful Array in C++
- Maximum height of triangular arrangement of array values in C++
- MySQL query to fetch records with arrangement in the form of numbers and letter like 99S, 50K, etc.?
- Program for printing array in Pendulum Arrangement.
- Arrangement of words without changing the relative position of vowel and consonants?
- Sum of consecutive numbers in JavaScript
- Primality test of numbers in JavaScript
- How to look beautiful in 15 days?
- How to look beautiful without makeup?
- Grouping of same kind of numbers in JavaScript
- Count groups of negatives numbers in JavaScript
- Special type of numbers (pronic) in JavaScript

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

Suppose we have num integers from 1 to num. We define a **beautiful arrangement** as an array that is constructed by these num numbers successfully if one of the following is true for the ith position (1 ≤ i ≤ N) in this array −

The number at the ith position is divisible by i.

i is divisible by the number at the ith position.

We are required to write a JavaScript function that takes in a number, num, and returns the count of beautiful arrangements we can construct for num.

For example, if the input to the function is −

const input = 2

Then the output should be −

const output = 2

The first beautiful arrangement is [1,2]:

The second beautiful arrangement is [2,1]:

The code for this will be −

const num = 4; const countArrangements = (num = 1) => { let ans = 0 const recur = (curr, vis) => { if (curr === 1){ ans++; }else{ for (let i = num; i; i--) { let possible = (i % curr === 0 || curr % i === 0); let visited = vis & 1 << i; if (possible && !visited){ recur(curr-1, vis | 1 << i); } } } }; recur(num, 0); return ans; }; console.log(countArrangements(num));

We define a result variable (**ans**) and then create a **recursive function** to navigate the multiple branching possibilities. This recursive function will only need two arguments: which number are we currently looking to place (curr) and which spots have already been visited (vis).

And the output in the console will be −

8

Advertisements