What could be the reason behind the for loop not incrementing and the splice not being modified in my code?

Encountered a seemingly simple problem while coding, but the expected returns started deviating as I progressed.

Your assistance would be greatly appreciated. If you do provide help, please elaborate on your approach and where I hit a roadblock.

The Challenge:

We are presented with a string and tasked with determining if it can be broken down into words from an array of words. For instance:

const str = "applecomputer";
const dictArr = ["apple", "computer"];
stringBreakdown(str, dictArr);
// true

Considering no duplicates in the dictionary array, can you write a method to return true if the string can be segmented into words from the array, or false otherwise?

The Two Test Cases:

Expect stringBreakdown('crazyrichasians', [ 'crazy', 'rich', 'asians' ]) // to return true

Expect stringBreakdown('lockcombination', [ 'lock', 'combo' ]) // to return false

My Code and Strategy:

  • Generate a hash map of all characters in the string
  • Create a helper function to remove characters from each word in the array
  • Reduce the count for each seen character in the hash map while removing characters from the word
  • If all letters are accounted for, remove the word from the array
  • Finally, return true if the array length is less than zero, indicating successful segmentation, or false if more words remain untouched
const stringBreakdown = (str, dictArr)=> {
  let hashDictionary = {};
  let shouldRemoveWord

  for(let x = 0; x <= str.length-1;x++){
    !hashDictionary[str[x]]  ? hashDictionary[str[x]] =1 : hashDictionary[str[x]]+=1
  }

for(let y = 0; y < dictArr.length;y++ ){
  shouldRemoveWord = removeLetters(hashDictionary,dictArr[y]) 
    if(shouldRemoveWord === true){
      dictArr.splice(y,1)
    }
  }
  console.log('dictArr',dictArr)
  return dictArr.length > 0 ? true : false;
}

const removeLetters = (hash,word) =>{
let modifiedWord = word.split('')

for(let k = 0; k < modifiedWord.length;k++){
    if(hash[word[k]]){
     modifiedWord.splice(k,1)
     hash[word[k]]-=1
   }
}
 return modifiedWord.join('').length < 0  ? true : false;
}

Answer №1

If you iterate over each word in the array, you can follow these steps:

Firstly, confirm if the total length of all the words combined equals the length of the string being tested. If not, return false.

Secondly, if the lengths match, then verify if every word is included as a sub-string within the given string:

function analyzeString(str, dictArr){
  return dictArr.join("").length === str.length
         && 
         dictArr.every(word => str.includes(word)); 
}
//tests
console.log(analyzeString('crazyrichasians', [ 'crazy', 'rich', 'asians' ]));
console.log(analyzeString('lockcombination', [ 'lock', 'combo' ]));
console.log(analyzeString('applecomputer', [ 'apple', 'computer']));
console.log(analyzeString('appelcomputer', [ 'apple', 'computer']));
console.log(analyzeString('appcolemputer', [ 'apple', 'computer']));
console.log(analyzeString('applecomputer', [ 'app', 'le', 'computer']));

Your methodology may lead to faulty results since it doesn't evaluate the entire word but rather checks individual characters. For instance, if the string is applecomputer and the array contains ['appel', 'comterpu'], your algorithm would incorrectly return true in this scenario.

This is because you are creating a character map from the input string str, and then examining each word's characters separately without considering the word as a whole.

const analyzeString = (str, dictArr)=> {
  let charMap = {};
  let shouldRemoveWord;

  for(let x = 0; x <= str.length-1;x++){
    !charMap[str[x]]  ? charMap[str[x]] =1 : charMap[str[x]]+=1
  }

for(let y = 0; y < dictArr.length;y++ ){
  shouldRemoveWord = removeLetters(charMap,dictArr[y]) 
    if(shouldRemoveWord === true){
      dictArr.splice(y,1)
    }
  }
  return dictArr.length > 0 ? true : false;
}

const removeLetters = (map,word) =>{
let modifiedWord = word.split('')

for(let k = 0; k < modifiedWord.length;k++){
    if(map[word[k]]){
     modifiedWord.splice(k,1)
     map[word[k]]-=1
   }
}
 return modifiedWord.join('').length < 0  ? true : false;
}
//this test will output true
console.log(analyzeString('applecomputer', ['appel', 'computer']));

Answer №2

One way to handle this is by iterating through the dictionary.

const dictArr = ["lock", "combo"];
function checkInDic(val){
    var len = 0;
    dictArr.forEach(element => {
        if(val.includes(element)){
            len += element.length;
        }else{
            return false;
        }
    });
    if(len == val.length){
        return true;
    }else{
        return false;
    }
}

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

Uncover hidden content by clicking a button with JavaScript

I need help with creating a function that hides additional content until a button is clicked. Currently, my script displays the content by default. How can I modify it to hide the content by default and only reveal it when the button is clicked? functi ...

Having trouble implementing server-side rendering with Styled-Components in Next JS

I attempted to resolve my issue by reviewing the code and debugging, but unfortunately, I couldn't identify the root cause. Therefore, I have posted a question and included _document.js, _app.js, and babel contents for reference. Additionally, I disa ...

React: Remember to always retain the initial four characters when making changes

I have implemented an input component for phone numbers using the react native phone input library, which automatically adds the international code. However, I am facing an issue where the international code +234 is deleted when the user presses the back b ...

Transform pixel padding into percentage ratios

I've been searching through various discussions to find a solution, but none of them seem to fit my particular scenario. My issue involves a hyperlink with absolute positioning inside a div with relative positioning. The padding and margins are curre ...

"Implementing a dynamic way to assign values to different item types in React

There is an object with multiple values inside: const [sort, setSort] = useState({ "city": [], "price": [], "year": [] }); When the "add" button is clicked, the "city" value should be updated to include certain va ...

Tips for validating forms using jQuery

Upon form submission, an alert is displayed before redirecting to a new page. I have implemented a function that triggers on button click. The alert will appear first, followed by the form submission. I would appreciate ideas on how to validate the form. ...

Issues with implementing Rails 4 with jQuery, javascript, and coffee scripts causing functionality to malfunction

Although I have nearly two decades of experience in C/C++ for control systems and firmware, as well as proficiency in shell and perl scripting, I am new to rails and web development. Despite including jquery in the application.js manifest, I am unable to ...

The callback function in AngularJS' $http is failing to trigger

$scope.submitNewUser = function() { $http({ method: 'POST', url: 'api/user/signup', data: {'user': $scope.user}, headers: {'Content-Type': ...

Get started with adding a Typescript callback function to the Facebook Login Button

I am in the process of implementing Facebook login into my Angular7 application using Typescript. Although I have successfully integrated Facebook's Login Button plugin for logging in, I am facing issues with providing a callback method to the button& ...

Check to see if it is possible to click an HTML div

Currently, I am engaged in Selenium and Robot Framework automated testing and in search of a method to automatically locate div tags that are capable of being clicked. The keyword Click Element works well when provided with a specific CSS selector, but ho ...

Ensure that the modal remains open in the event of a triggered keydown action, preventing it from automatically closing

I am currently toggling the visibility of some modals by adjusting their CSS properties. I would like them to remain displayed until there is no user interaction for a period of 3 seconds. Is there a way to achieve this using JavaScript? Preferably with Vu ...

Having a slight hiccup with pixel alignment and browser compatibility in my jQuery animation

To emphasize a specific paragraph element, I developed a JavaScript function that displays it above a darkened background. My approach involved using jQuery to generate an overlay and then duplicating the targeted paragraph element while positioning it ab ...

Modules failing to load in the System JS framework

Encountering a puzzling issue with System JS while experimenting with Angular 2. Initially, everything runs smoothly, but at random times, System JS struggles to locate modules... An error message pops up: GET http://localhost:9000/angular2/platform/bro ...

Using Input Mask with TextField Component in Material-UI with React Hook Form

Currently, I am trying to utilize the MUI's TextInput component alongside the MaskInput component from react-input-mask and react-hook-form. Despite everything appearing to be functioning correctly, an error message related to using refs keeps popping ...

Issue with process.env.NODE_ENV not functioning appropriately in NodeJS when utilizing package.json scripts

I currently have three separate databases configured for testing, development, and production purposes. My goal now is to make my express app switch between these databases based on the script that is being executed. These are the scripts I am using: "s ...

Explore in MegaMenu Pop-up

At my workplace, the internal web portal features a MegaMenu with a popup menu that includes a Search input field. The issue I am encountering is that when a user starts typing in the search bar and moves the mouse off of the megamenu, it disappears. It ...

Reactivity in Vue not responding when listening from a different object

Can someone help me understand why my Vue object is not reactive to changes in another object? See the code snippet below. exampleObject = { exampleProperty: null } exampleObject.update = function () { this.exampleProperty = 'updated data&apo ...

Resolving the Table Issue with 'onclick' in Javascript

Apologies for the lack of creativity in the title, I struggled to come up with something fitting. Currently, I am engaged in the development of a user-friendly WYSIWYG site builder. However, I have encountered an obstacle along the way. I've devised ...

Visual Studio Code encounters a Node.js error stating "Module not found"

I have been struggling to run my Node.js program in VSCode. Despite trying various solutions found on StackOverflow, none of them seem to be working for me. I even attempted the Json file method, but unfortunately, that didn't work either. internal/mo ...

Editing JSON files - Substitute the $scope object with a new value

I am facing an issue with extracting data from an external JSON file for my application. Although most of the data loads into a DataTables table successfully, I am encountering problems with the $scope variable since it is referencing external data. Specif ...