简体   繁体   English

Javascript内部数组长度中的双循环

[英]Double for loop in Javascript inner array length

I am trying to create a function that takes in a string and changes each letters value to a "(" if the character is not duplicated in the string, and a ")" if the character does have a duplicate present in the string.我正在尝试创建一个函数,该函数接受一个字符串并将每个字母值更改为 "(" 如果字符在字符串中没有重复,如果字符在字符串中存在重复,则更改为 ")"。 I have decided to go an unconventional route to solve this problem but I am running in to an issue with a double for loop.我决定走一条非常规的路线来解决这个问题,但我遇到了一个双重 for 循环的问题。 From what I understand, the inner for loop in javascript does not have access to the variables outside of the loop.据我了解,javascript 中的内部 for 循环无法访问循环外的变量。 I want to loop through every item in an array twice but I'm not sure what to set the inner loops length as.我想遍历数组中的每个项目两次,但我不确定将内部循环长度设置为什么。

Here is my code:这是我的代码:

function sortAndChange(word) {
const splitter = word.toLowerCase().split("");
//let jSplitter = word.toLowerCase().split("").length;
let endResult = "";
let truthArray = [];

for(i = 0; i < splitter.length; i++){
    for(j = 0; j < splitter.length; j++){
        console.log(j);
        if(splitter[i] == splitter[j]){
            truthArray.push(true);
        } else {
            truthArray.push(false);
        }
    }
    console.log(truthArray);
    truthArray.every(item => item === false) ? endResult += "(" : endResult += ")";
    truthArray = [];
}
console.log(endResult);
}

Expected Result:预期结果:

sortAndChange("Success") //expected output: ")())())"
sortAndChange("easy") //expected output: "(((("

You can do that in following steps:您可以按以下步骤执行此操作:

  • Convert string to array using split and use map() on it.使用split将字符串转换为数组并在其上使用map()
  • Compare the indexOf() and lastIndexOf() to check if its duplicate or not.比较indexOf()lastIndexOf()以检查其是否重复。
  • Return the ) or ( based on ur condition. And then at last join the array根据您的条件返回)( 。然后最后join数组

 function sortAndChange(str){ let arr = str.toLowerCase().split('') return arr.map(x => { //if its not duplicated if(arr.indexOf(x) === arr.lastIndexOf(x)){ return '(' } //If its duplicated else{ return ')' } }).join(''); } console.log(sortAndChange("Success")) //expected output: ")())())" console.log(sortAndChange("easy")) //expected output: "(((("

You could take a object and keep a boolean value for later mapping the values.您可以获取一个对象并保留一个布尔值,以便稍后映射这些值。

This approach has two loops with O(2n)这种方法有两个O(2n) 的循环

 function sortAndChange(word) { word = word.toLowerCase(); var map = [...word].reduce((m, c) => (m[c] = c in m, m), {}); return Array .from(word, c => '()'[+map[c]]) .join(''); } console.log(sortAndChange("Success")); // )())()) console.log(sortAndChange("easy")); // ((((

Look at the following snippet and comments看看下面的片段和评论

 function sortAndChange(str) { // we create an array containing the characters on the string // so we can use Array.reduce return str.split('').reduce((tmp, x, xi) => { // we look if the character is duplicate in the string // by looking for instance of the character if (str.slice(xi + 1).includes(x.toLowerCase())) { // Duplicate - we replace every occurence of the character tmp = tmp.replace(new RegExp(x, 'gi'), ')'); } else { // Not duplicate tmp = tmp.replace(new RegExp(x, 'gi'), '('); } return tmp; }, str); } console.log(sortAndChange('Success')); //expected output: ")())())" console.log(sortAndChange('Easy')); //expected output: "(((("

This can easily be achieved using a combination of regex and the map construct in javascript:这可以使用regex和 javascript 中的map结构的组合轻松实现:

 const input = "this is a test"; const characters = input.toLowerCase().split(''); const transformed = characters.map(currentCharacter => { const regexpression = new RegExp(currentCharacter, "g"); if (input.toLowerCase().match(regexpression || []).length > 1) return ')' return '('; }).join(""); console.log(transformed);

1) use Array.from to convert to array of chars 1) 使用Array.from转换为字符数组
2) use reduce to build object with key-value pairs as char in string and ( or ) as value based on repetition . 2)使用reduce来构建对象,键值对作为字符串中的字符和(或)作为基于重复的值。
3) Now convert original string to result string using the chars from above object. 3)现在使用来自上述对象的字符将原始字符串转换为结果字符串。

 function sortAndChange(str) { const str_arr = Array.from(str.toLowerCase()); const obj = str_arr.reduce( (acc, char) => ((acc[char] = char in acc ? ")" : "("), acc), {} ); return str_arr.reduce((acc, char) => `${acc}${obj[char]}`, ""); } console.log(sortAndChange("Success")); // ")())())" console.log(sortAndChange("easy")); // ((((

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM