How do I display the input parameter like this:
displayText("you and me");
expected output:
["you and me", "you and", "and me", "you", "and", "me"]
I have tried like the following code, but the results are still wrong. My code is like this now.
let displayText = (txt) => {
let output= []
for(let i = 0; i < txt.length; i++) {
for(j = i + 1; j < txt.length + 1; j++) {
output.push(txt.slice(i, j))
}
}
return output
}
First of all you can split the sentence:
const sentence = 'you and me'
const parts = sentence.split(' ')
The difficult part is to extract the elements by pairs. Use slice for this:
const numberOfPairs = parts.length - 1
for (let i=0; i<numberOfPairs ; i++) {
console.log(parts.slice(i, i+2).join(' '))
}
Then, print the individual parts:
parts.forEach(part => console.log(part))
first you have to split sentence
Example:-
var strArr = string.split(" ");
var output= []
var temp = "";
for (var i = 0; i < strArr.length; i++) {
temp = strArr[i];
output.push(temp)
for (var j = i + 1; j < strArr.length; j++) {
temp += strArr[j];
output.push(temp)
}
}
console.log(output)
You may do like this.
You will need to split() the string on the word breaks to have your function work as is (and also declare j).
let displayText = (txt) => {
txt = txt.split(' ');
let output = []
for (let i = 0; i < txt.length; i++) {
for (let j = i + 1; j < txt.length + 1; j++) {
output.push(txt.slice(i, j).join(' '))
}
}
return output
}
console.log(displayText("you and me"))
To return an array sorted by combination length, you can group each slice() by word count and flat() the output array before returning.
let displayText = (txt) => {
txt = txt.split(' ');
let
len = txt.length, output = [];
for (let i = 0; i < len; i++) {
for (let j = i + 1; j < len + 1; j++) {
(output[len - (j - i)] ??= []).push(txt.slice(i, j).join(' '))
}
}
// before flat() call
// [ [ 'you and me' ], [ 'you and', 'and me' ], [ 'you', 'and', 'me' ] ]
return output.flat()
}
console.log(displayText("you and me"));
Related
Is there another way to print right angled pyramid in javascript without adding a line at the end of the display?
let hashKey = "#",
str = "",
space = " ",
num = 5;
for (let i = 1; i <= num; i++) {
for (let j = 1; j <= num; j++) {
if (i + j > num) {
str = str.concat(hashKey);
} else {
str = str.concat(" ");
}
}
str = str.concat("\n");
}
console.log(str);
You could move the adding of new line with a condition by using a logical AND && with str.
If str is an empty string it adds the emtpty string to str,
If not empty, it takes the next expression with the new line.
let hashKey = "#",
str = "",
space = " ",
num = 5;
for (let i = 1; i <= num; i++) {
str += str && "\n";
for (let j = 1; j <= num; j++) {
str += i + j > num ? hashKey : " ";
}
}
console.log(str);
Use join:
const hashKey = "#",
space = " ",
num = 5;
let str = Array.from({length: num}, (_, i) =>
hashKey.repeat(i + 1).padStart(num, space)
).join("\n");
console.log(str);
for (var i = 1; i <= 4; i++) {
var str = "";
for (var j = 1; j <= i; j++) {
str = str + i;
}
console.log(str);
}
This is the code I Perform But its Wrong
1
23
456
78910
anybody please help?
var current_value = 1;
for (var i = 1; i <= 4; i++) {
var str = "";
for (var j = 1; j <= i; j++) {
str = str + current_value++;
}
console.log(str);
}
This is how I would solve your problem. You can use Array.prototype.map() in order to create loops easily. If we now create an empty array with 5 indexes we can use the Array.prototype.keys() to get an array of values from 0 to 4. Besides that my code follows the same concept with using an empty string (res) and adding values to it.
Also we mustn't forget to check if res is still empty.
let v = 1;
[...Array(5).keys()].map((i) => {
let res = "";
[...Array(i)].map(() => (res = res + v++));
res && console.log(res);
});
Edit:
I just realized the .keys() is not even needed because simply using the index has the same effect:
let v = 1;
[...Array(5)].map((_, i) => {
let res = "";
[...Array(i)].map(() => (res = res + v++));
res && console.log(res);
});
I have the following array as an example;
let arr = [['red','blue','pink],['dog','cat','bird'],['loud', 'quiet']]
I need to write a generalized function that prints all combinations of one word from the first vector, one word from the second vector, etc. I looked up some codes on here but they are all recursion or working only with the specific array. How can I write this code without recursion?
let allComb = function(arr) {
if (arr.length == 1) {
return arr[0];
} else {
let result = [];
let arrComb = allComb(arr.slice(1));
for (let i = 0; i < arrComb.length; i++) {
for (let j = 0; j < arr[0].length; j++) {
result.push(arr[0][j] + ' ' + arrComb[i]);
}
}
return result;
}
}
allComb(arr)
This version uses a single increment per cycle technique with no recursion.
let arr = [
['red', 'blue', 'pink'],
['dog', 'cat', 'bird'],
['loud', 'quiet']
];
function allComb(arr) {
var total = 1;
var current = [];
var result = [];
for (var j = 0; j < arr.length; j++) {
total *= arr[j].length;
current[j] = 0;
}
for (var i = 0; i < total; i++) {
var inc = 1;
result[i] = "";
for (var j = 0; j < arr.length; j++) {
result[i] += arr[j][current[j]] + ' ';
if ((current[j] += inc) == arr[j].length)
current[j] = 0;
else
inc = 0;
}
}
return (result);
}
console.log(allComb(arr));
You may do as follows;
var arr = [['red','blue','pink'],['dog','cat','bird'],['loud', 'quiet']],
res = arr.reduce((p,c) => p.reduce((r,x) => r.concat(c.map(y => x + " " + y)),[]));
console.log(res);
I have the following function to get all of the substrings from a string in JavaScript. I know it's not correct but I feel like I am going about it the right way. Any advice would be great.
var theString = 'somerandomword',
allSubstrings = [];
getAllSubstrings(theString);
function getAllSubstrings(str) {
var start = 1;
for ( var i = 0; i < str.length; i++ ) {
allSubstrings.push( str.substring(start,i) );
}
}
console.log(allSubstrings)
Edit: Apologies if my question is unclear. By substring I mean all combinations of letters from the string (do not have to be actual words) So if the string was 'abc' you could have [a, ab, abc, b, ba, bac etc...] Thank you for all the responses.
You need two nested loop for the sub strings.
function getAllSubstrings(str) {
var i, j, result = [];
for (i = 0; i < str.length; i++) {
for (j = i + 1; j < str.length + 1; j++) {
result.push(str.slice(i, j));
}
}
return result;
}
var theString = 'somerandomword';
console.log(getAllSubstrings(theString));
.as-console-wrapper { max-height: 100% !important; top: 0; }
A modified version of Accepted Answer. In order to give the minimum string length for permutation
function getAllSubstrings(str, size) {
var i, j, result = [];
size = (size || 0);
for (i = 0; i < str.length; i++) {
for (j = str.length; j - i >= size; j--) {
result.push(str.slice(i, j));
}
}
return result;
}
var theString = 'somerandomword';
console.log(getAllSubstrings(theString, 6));
Below is a recursive solution to the problem
let result = [];
function subsetsOfString(str, curr = '', index = 0) {
if (index == str.length) {
result.push(curr);
return result;
}
subsetsOfString(str, curr, index + 1);
subsetsOfString(str, curr + str[index], index + 1);
}
subsetsOfString("somerandomword");
console.log(result);
An answer with the use of substring function.
function getAllSubstrings(str) {
var res = [];
for (let i = 0; i < str.length; i++) {
for (let j = i + 1; j <= str.length; j++) {
res.push(str.substring(i, j));
}
}
return res;
}
var word = "randomword";
console.log(getAllSubstrings(word));
function generateALlSubstrings(N,str){
for(let i=0; i<N; i++){
for(let j=i+1; j<=N; j++){
console.log(str.substring(i, j));
}
}
}
Below is a simple approach to find all substrings
var arr = "abcde";
for(let i=0; i < arr.length; i++){
for(let j=i; j < arr.length; j++){
let bag ="";
for(let k=i; k<j; k++){
bag = bag + arr[k]
}
console.log(bag)
}
}
function getSubstrings(s){
//if string passed is null or undefined or empty string
if(!s) return [];
let substrings = [];
for(let length = 1 ; length <= s.length; length++){
for(let i = 0 ; (i + length) <= s.length ; i++){
substrings.push(s.substr(i, length));
}
}
return substrings;
}
Below I am trying to give string arrays to a function that adds unique words to a words array, and if the word is already in the array to increase the count of the corresponding element in the count array:
var words = [];
var counts = [];
calculate([a, b]);
calculate([a, c]);
function calculate(result) {
for (var i = 0; i < result.length; i++) {
var check = 0;
for (var j = 0; i < tags.length; i++) {
if (result[i] == tags[j]) {
check = 1;
counts[i] = counts[i] + 20;
}
}
if (check == 0) {
tags.push(result[i]);
counts.push(20);
}
check = 0;
}
}
However the output turns out like this:
words = a, b
count = 2, 1
When I expect it to be:
words = a,b,c
count = 2,1,1
Thanks for any help in advance
Breaking the problem down into methods with good names helps you to work out your logic.
Try this:
<script type="text/javascript">
var words = [];
var counts = [];
calculate(["a", "b"]);
calculate(["a", "c"]);
console.log(words);
console.log(counts);
function calculate(result) {
for (var i=0; i<result.length; i++) {
if (array_contains(words, result[i])) {
counts[result[i]]++;
} else {
words.push(result[i]);
counts[result[i]] = 1;
}
}
}
function array_contains(array, value) {
for (var i=0; i<array.length; i++)
if (array[i] == value)
return true;
return false;
}
</script>
Output:
["a", "b", "c"]
[]
a 2
b 1
c 1
Please check this :
you can test it on : http://jsfiddle.net/knqz6ftw/
var words = [];
var counts = [];
calculate(['a', 'b']);
calculate(['a', 'c']);
calculate(['a', 'b', 'c']);
function calculate(inputs) {
for (var i = 0; i < inputs.length; i++) {
var isExist = false;
for (var j = 0; j < words.length; j++) {
if (inputs[i] == words[j]) {
isExist = true
counts[i] = counts[i] + 1;
}
}
if (!isExist) {
words.push(inputs[i]);
counts.push(1);
}
isExist = false;
}
}
console.log(words);
console.log(counts);
Output is :
["a", "b", "c"] (index):46
[3, 2, 2]
A few things were wrong, here's working code:
var words = [];
var counts = [];
calculate(["a", "b"]);
calculate(["a", "c"]);
function calculate(result) {
for (var i = 0; i < result.length; i++) {
var check = 0;
for (var j = 0; j < words.length; j++) {
if (result[i] == words[j]) {
check = 1;
++counts[j];
}
}
if (check == 0) {
words.push(result[i]);
counts.push(1);
}
check = 0;
}
}
Jsbin : http://jsbin.com/hawaco/2/edit?js,console
Things I've changed:
Changed array literal to supply strings instead of variable names: [a,b] to ["a","b"]
Replaced instances of tags (presumably an old name) with words
Changed the 20s to 1s
Made the increment of counts[j] more clear
Fixed use of i/j indices
Things to consider:
Perhaps make this a dictionary rather than a pair of arrays: {"a":1, "b":2}, which would make for simpler code
Pass in the names of the arrays to permit other accumulators, or combine the method and arrays into a single object
Simplified:
var seen = {};
count(["a", "b"], seen);
count(["a", "c"], seen);
function count(words, accumulator) {
for (var i = 0; i < words.length; ++i) {
if(!accumulator.hasOwnProperty(words[i])) {
accumulator[words[i]] = 1;
} else {
++accumulator[words[i]];
}
}
}
Result:
>> seen
[object Object] {
a: 2,
b: 1,
c: 1
}
JSBin: http://jsbin.com/halak/1/edit?js,console
Here's my solution (using an object):
const checkWord = (str) => {
let collection = {};
// split the string into an array
let words = str.split(' ');
words.forEach((word) => {
collection[word] = word;
});
// loop again to check against the array and assign a count
for (let j = 0; j < words.length; j++) {
if (words[j] === collection[words[j]]) {
collection[words[j]] = 0;
}
collection[words[j]]++
}
console.log(collection);
};
You can also use reduce:
const checkWord = (str) => {
let collection = {};
let words = str.split(' ');
words.forEach((word) => {
collection[word] = word;
});
for (var i = 0; i < words.length; i++) {
if (words[i] === collection[words[i]]) {
collection[words[i]] = 0;
}
}
let total = words.reduce((occurrences, word) => {
collection[word]++
return collection;
}, 0);
console.log(total);
};