Generation

generate functionThu, 15 Jun 2023

In JavaScript Given an array X of positive integers, its elements are to be transformed by running the following operation on them as many times as required: if X[i] > X[j] then X[i] = X[i] - X[j] When no more transformations are possible, return its sum ("smallest possible sum"). For instance, the successive transformation of the elements of input X = [6, 9, 21] is detailed below: X_1 = [6, 9, 12] # -> X_1[2] = X[2] - X[1] = 21 - 9 X_2 = [6, 9, 6] # -> X_2[2] = X_1[2] - X_1[0] = 12 - 6 X_3 = [6, 3, 6] # -> X_3[1] = X_2[1] - X_2[0] = 9 - 6 X_4 = [6, 3, 3] # -> X_4[2] = X_3[2] - X_3[1] = 6 - 3 X_5 = [3, 3, 3] # -> X_5[1] = X_4[0] - X_4[1] = 6 - 3 The returning output is the sum of the final transformation (here 9). Example solution([6, 9, 21]) #-> 9 Solution steps: [6, 9, 12] #-> X[2] = 21 - 9 [6, 9, 6] #-> X[2] = 12 - 6 [6, 3, 6] #-> X[1] = 9 - 6 [6, 3, 3] #-> X[2] = 6 - 3 [3, 3, 3] #-> X[1] = 6 - 3

function solution(numbers) { // place to store the working array let workingArray = numbers; // place to store the previous array let previousArray = numbers; // while the previous array is not equal to the working array while (JSON.stringify(previousArray) !== JSON.stringify(workingArray)) { // store the previous array previousArray = workingArray; // loop through the array for (let i = 0; i < workingArray.length; i++) { // place to store the current number let currentNumber = workingArray[i]; // loop through the array again for (let j = i + 1; j < workingArray.length; j++) { // if the current number is greater than the other number if (currentNumber > workingArray[j]) { // subtract the other number from the current number currentNumber -= workingArray[j]; // replace the current number in the array with the new number workingArray[i] = currentNumber; // replace the other number in

Javascript
Generate More

Questions about programming?Chat with your personal AI assistant