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

The construction of the Gatsby site encountered a major obstacle

I've been facing challenges while trying to build my Gatsby site. Whenever I run 'gatsby develop' in the console, my app starts without any issues. However, when I attempt to build it, I encounter errors like the ones shown below. Does anyon ...

In ES6, instantiate a fresh new instance of this

Can a new instance of self/this be generated using ES6 inside a static method? For instance; class myClass { static model() { return new this; } } Is there a standard approach for this situation? Thank you very much. ...

I can't seem to get my JavaScript to connect to my HTML file. What should I do next?

I'm facing a major issue at the moment. My HTML file doesn't seem to be linking properly with my JavaScript file, even though they are located in the same folder. The script link is correctly placed in the HTML file, but for some reason, it just ...

Discover the power of sorting outcomes in a Node.js-MongoDB query by utilizing a dynamic function call

Currently, I am working on a web application in Node.js that is connected to MongoDB using the Mongo native connector. In one of my JavaScript files, I have implemented a generic method to perform "find" or "findOne" operations to fetch data from a collec ...

Troubleshooting textarea resize events in Angular 6

In the development of my Angular 6 application, I have encountered an issue with a textarea element. When an error occurs, an asterisk should be displayed next to the textarea in the top-right corner. However, there is a gap between the textarea and the as ...

Tips for using a JavaScript function to navigate to a specific division (<div>) on an HTML page

I am facing an issue where I need to redirect within the same HTML page that includes a add-form div. What I want is that when I click on a button, my redirection should be to a specific div containing some code. Currently, I have code that redirects to a ...

Tips for utilizing XMLHttpRequest to instruct a website to take action

Although I have no prior experience with Ajax, I am in need of some guidance to create a simple Chrome extension. Despite searching online, I have not been able to find much information on this topic, which I believe should be straightforward. Request URL ...

Utilize an npm package to transform a CSS file into inline styles within an HTML document

I have an HTML file with an external CSS file and I would like to inline the styles from the external style sheet into one inline <style> tag at the top of the head. Any assistance would be greatly appreciated. Note: I do not want to use the style a ...

The conditional statement to check for an empty object does not trigger any actions

My goal is to display a success message once users successfully register without any errors. I have an errors reducer object in Redux that stores errors sent from the backend. The logic is set up so that if the errors object is empty, it shows the success ...

What is the best way to transmit two distinct sets of data from a child component to the v-model of a parent component?

Currently, I am working on a project using vuejs 2 and typescript. In this project, I need to pass two different sets of data - data and attachments - within the parent component. I am utilizing vue-property-decorator for this purpose. However, I am facing ...

Errors encountered when using Puppeteer on Kubernetes: "Detached navigation frame" and "Attempting to access main frame too soon"

I have been attempting to execute a nodejs based Docker container on a k8s cluster, but I am encountering persistent errors: Navigation frame was detached Requesting main frame too early In an effort to resolve this issue, I have condensed the code to ...

Custom directives are designed to receive arrays as string inputs

I've encountered an issue with my custom directive that has an isolated scope. When I pass an Array variable to the directive, it is being treated as a String inside the directive. This is how my directive looks: angular.module('my.directives& ...

injecting a variable from the configuration service into a TypeScript decorator

I am interested in setting up a scheduled task for my NestJs application to run at regular intervals. I found information on how to use intervals in the NestJs documentation. Since my application uses configuration files, I want to keep the interval value ...

Warning message regarding unhandled promise rejection in NestJS websockets

I've encountered a puzzling issue while attempting to integrate an 'events' module into my application to utilize websockets. Upon adding the module, an unexpected error surfaced: (node:59905) UnhandledPromiseRejectionWarning: Unhandled pro ...

A warning has been issued: CommonsChunkPlugin will now only accept one argument

I am currently working on building my Angular application using webpack. To help me with this process, I found a useful link here. In order to configure webpack, I created a webpack.config.js file at the package.json level and added the line "bundle": "web ...

Execute CSS within jQuery code only when the body class is present

I am attempting to use CSS (display: none;) within a script to hide elements from my menu only if a specific language is active. When the body class changes from one language to another, I want the script to check if the body class of a certain language ...

Customizing the `toString()` method in Node.js exports

I'm having trouble overriding a toString() method in my code. I've already checked here and here, but haven't been able to solve the issue. This is what my code looks like: var Foo = function(arg) { // some code here... return fun ...

Having trouble passing multiple associative array values from JavaScript/AJAX to PHP

We have been encountering an issue when trying to pass multiple associative array values from JavaScript/AJAX to PHP, as the PHP file is receiving an empty object/array. Could someone kindly assist us in retrieving the values of an associative array from ...

Best practice for updating Form.Control text using a custom onChange method

Today, I observed a unique behavior while utilizing a custom onChange in a Form.Control. The text in the field no longer updates when a file is selected. I thoroughly checked the Git documentation HERE, but unfortunately, it does not provide information on ...

How to clear a 24-hour-old template from the Angular 1 cache?

I have implemented the following rule to clear template cache in my AngularJS application: myApp.run(function ($rootScope, $templateCache) { $rootScope.$on('$viewContentLoaded', function() { $templateCache.removeAll(); }); }); Howe ...