In a set of strings, locate the two shortest ones, remove them, and then add them back to the end repeatedly until there is only one string

I've been struggling with a coding challenge for a couple of hours now and could really use some help. Here are the detailed instructions:

Take an array of strings and create a single string by following these steps:

Repeat the following steps as long as there is more than one string in the array:

Identify the shortest string in the array (if there are multiple strings of the same length, choose the leftmost one);

Find the shortest string among the remaining strings (if there are multiple strings of the same length, choose the rightmost one);

Remove the selected strings from the array;

Append the concatenated result of the chosen strings (the second string should be added to the end of the first string) to the right end of the array.

Once the algorithm is complete, there should be only one string left in the array. Return that string.

Here's my attempt at a solution:

function concatenationProcess(init) {
  var shortestString = init[0];
  var shorterString = init[0];
  var appendedString = "";
  while (init.length > 0) {
    for (i = init.length - 1; i >= 0; i--) {
      if (init[i].length <= shortestString.length) {
        shortestString = init[i];
      }
    }
    var newArray = init;
    newArray = init.splice(init.indexOf(shortestString), 1)
    for (i = 0; i < init.length; i++) {
      if (init[i].length <= shorterString.length) {
        shorterString = init[i];
      }
    }
    init.splice(init.indexOf(shorterString), 1)
    var newInit = init;
    console.log(shorterString, "shorter string")
    appendedString = shortestString + shorterString
    init.push(appendedString)
    console.log(init)
  }
}

Answer №1

This particular situation causes the loop to run endlessly:

while (init.length > 0) {

To avoid this issue, it is necessary to halt the loop when there is just one element remaining in the array. Therefore, adjust the comparison from 0 to 1.

In addition, there is a bug in the code. It is crucial to update the values of shortestString and shorterString at the conclusion of each iteration to prevent them from retaining outdated values. In the provided example input

["thinking", "whatface", "cantare", "wait", "jay", "cutler"]
, they would persist as jay and wait, failing to change and yielding an incorrect result.

Furthermore, it is likely you intend to include return init[0] at the end of the function.

Answer №2

Explore this interactive model showcasing the dynamic changes within an array. Give it a try and witness how the array evolves over time! The concept is quite straightforward: identify the shortest and shorter elements, remove them, and replace them with the appended string. Continue this process until the array's length exceeds 1.

By the way, if you're interested in the output, feel free to substitute alert with console.log or return.

function concatenationProcess(init) {
    while(init.length>1){
      var shortest = init[0];
      var appended = "";
      var p=0; // for storing the position of shortest/shorter
        for (i = init.length - 1; i >= 0; i--) {// find shortest
          if (init[i].length <= shortest.length) {
            shortest = init[i];
            p=i;
          }
        }
        init.splice(p,1); // remove shortest
        var shorter= init[0];
        for (i = 0; i <init.length; i++) { // find shorter
          if (init[i].length <= shorter.length) {
            shorter = init[i];
            p=i;
          }
        }
        init.splice(p,1); // remove shorter
       appended = shortest+shorter;
       init.push(appended); //append the appended string
       alert(init);
       }
    }
    var x = [ "thinking", "whatface", "cantare", "wait", "jay", "cutler"];
    concatenationProcess(x);

Answer №3

Upon analyzing the code you provided, it appears that there is a key issue with the way you handle the shortestString and shorterString variables when iterating through the array. While you correctly set them initially, failure to reset them before the second iteration causes the program to fail in identifying shorter or equal length strings, resulting in a crash.

To address this issue, I recommend storing the length of each string so that you can initialize both shortestString and shorterString to Number.MAX_SAFE_INTEGER (or alternatively, Infinity). Additionally, I noticed that your condition to stop the while loop is init.length > 0 rather than > 1. Furthermore, there are a few assignments such as newArray and newInit that seem unnecessary and remain unused in the function.

After rewriting the function from scratch, I have come up with the following improved version:

function concatenationProcess (init) {
    var shortestLength;
    while (init.length > 1) {
        shortestLength = Number.MAX_SAFE_INTEGER;
        var shortestString;
        for (var i = init.length-1; i >= 0; i--) {
            if (init[i].length <= shortestLength) {
                shortestString = init[i];
            }
        }
        init.splice(init.indexOf(shortestString), 1);

        shortestLength = Number.MAX_SAFE_INTEGER;
        var shorterString;
        for (var i = 0; i < init.length; i++) {
            if (init[i].length <= shortestLength) {
                shorterString = init[i];
            }
        }
        init.splice(init.indexOf(shorterString), 1);

        init.push(shortestString + shorterString);
    }
    return init[0];
}

Answer №4

This particular question practically screams for a recursive method to solve it.

Let's explore a different perspective on the issue, which often results in a succinct solution (as recursive functions tend to do):

function concatenateArray(arr) {
  if (arr.length === 1) return arr
  var idx = arr.reduce((acc, curr, i) => curr.length < arr[acc].length ? i : acc, 0)  
  var str = arr.splice(idx, 1) 

  idx = arr.reduce((acc, curr, i) => curr.length <= arr[acc].length ? i : acc, 0) 
  str = str + arr.splice(idx, 1)

  arr.push(str)
  return concatenateArray(arr)
}
concatenateArray(["a","abc","abcc","aaa","z","","qw"])
// [ 'abcaaaabccqwaz' ]

This function takes an array. If the array has only one element, it's done, so it simply returns that element. Otherwise, it identifies the shortest element from the left and the next shortest element from the right, combines them, and adds the result back into the array for further processing.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Are there any guidelines or rules outlining what is still considered valid JSONP?

I am looking for information on how to properly parse JSONP messages in .NET and extract the JSON data they contain. Is there a current specification that outlines what constitutes a valid JSONP message? During my research, I came across a blog post from ...

Prevent dragging events while clicking on a link

Recently, I encountered a drag event over an attached div.image element. Whenever I click and hold the mouse down on the div, the drag event initiates. In order to achieve this functionality, I utilized the nestable.js plugin. However, I am facing a chall ...

Ways to showcase corresponding information for an item contained within an array?

I'm working with a function that is designed to retrieve specific descriptions for objects nested within an array. The purpose of the function (findSettings()) is to take in an array (systemSettings) and a key (tab12) as arguments, then use a switch s ...

"Pressing the 'back' button on your browser takes

Is there a way to navigate back to the main page by clicking on an image? After selecting First, Picture1 will be shown. How can I go back to the selection page for further choices? <a href="picture1.jpg"> <h3>First</h3></a> <a ...

The error message "TypeError: Trying to access properties of an undefined object (reading '800')" is being displayed

Every time I launch my application, I encounter the error message: "TypeError: Cannot read properties of undefined (reading '800')". import React, { useState } from 'react'; import { Menu, MenuItem, Avatar, Box, ThemeProvider} ...

Place the second division beneath the first within a single navigation bar that adjusts accordingly to all screen sizes

I am experiencing an issue with the layout of my page that has 2 divs within one nav element. When the screen width is greater than 1024px, everything looks fine. However, when I reduce the width to less than 768px, the two divs merge into one line instead ...

What is the best way to transfer values from an AJAX script to the rest of the Javascript code?

Currently, I am diving into the world of a django 2.0 template along with a third-party jQuery script used for tagging photos and my own JavaScript code that acts as the "glue." Despite being new to JavaScript and JQuery, I managed to make a successful aja ...

Encountering a Problem with Image Rendering in Next.js

Issue: I am facing a problem while trying to display a react component using <Gallery images={images} />. The component itself is rendered, but the images from the array are not showing up initially. However, when I resize the screen by dragging the ...

Modify object rotation animation direction using keyboard controls in Three.js

Adjusting the object rotation direction with key controls is within my capability by utilizing the following code: case 37: scene.rotation.x -= 0.01; break case 38: scene.rotation.z -= 0.01 break Nevertheless, the rotation remai ...

Combining text output using JavaScript, HTML, and Vue

Can you help solve this challenge of outputting concatenated text from a javascript code? The script in question draws a quarter circle that is proportional to the size of the bar and showcases the value of pi accurate to three decimal places. To display ...

In what way can I decipher a section of the URL query string within my AngularJS application?

Here is a snippet of code that I am working with: var search = $location.search(); if (angular.isDefined(search.load) && search.load != null) { if (search.load = "confirmEmail") authService.confirmEmailUserId = search.userI ...

"Having trouble implementing sorting functionality on a click event in a React application with Material-UI table

Default behavior displays data in ascending order. Clicking on the table header should toggle between descending and ascending orders. Load Data in ascending order -> On click, change to descending order -> Again on click, change to ascending -> ...

Tips for effectively combining an array with jQuery.val

My goal is to have multiple form fields on a page, gather the input results into an array, and then store them in a database. This process was successful for me initially. However, when I introduced an autocomplete function which retrieves suggestions from ...

Having trouble implementing min and max date validation in Angular UI-Bootstrap datepicker with UI-Bootstrap version 1.3.3

My goal is to implement validation in my datepicker, preventing the user from selecting a date within 30 days before or after the current date. Here's the code snippet I'm currently using for the datepicker: <div class="form-group" ng-class=" ...

The Google Books API has reached its limit for requests

Encountering a rate limit exceeded error from the Google Books API while using this demo: To reproduce, open the developer console in Chrome and perform some searches. The rate limit errors will be displayed in the console. [],"lazyUpdate":null},"status" ...

Activate the function for items that are overlapping

Here is a scenario I am working on: HTML <body> <div> <p>Text</p> </div> <body> JQuery $('div').click(function(){ $(this).find('p').fadeToggle('fast'); }); $('bo ...

Bootstrap revamps dropdown menu code into a convoluted mess

I recently started working on a project with the Material Design theme from for a CodeIgniter application. However, I've encountered an issue with the dropdown functionality. It seems that Bootstrap is altering the original code, transforming it from ...

Doesn't the .stop(true) function completely clear the queue as it should?

My slideshow has a hover function to pause it using .stop(true). Upon mouse exit, it should resume playing from where it left off. However, currently, when I hover over it, the animation stops and then continues until it reaches its target, pausing there a ...

Steps to automatically launch a URL upon button click and executing PHP script

I have a Joomla website and I am facing a challenge in automatically triggering a modal window that displays a web page based on parameters passed through the URL. The scenario on my website is as follows: A trip leader selects a trip and schedules it by ...

Displaying one out of two elements when the button is clicked

Trying to implement two buttons on the parent component, each displaying a different component - one for itemlist and the other for itemlist2. Struggling to get it right, even after following an example at https://codepen.io/PiotrBerebecki/pen/yaVaLK. No ...