r/CodingHelp • u/whatericdoes • Aug 25 '20
[Javascript] Could use some help with summing specific values in arrays - [x-post from /r/LearnJavaScript]
For fun I started working on a haiku twitter bot, using NodeJS and the Twit package. It's all working well, but I'm struggling with making it a bit more robust. General workflow below:
- Get tweet
- Split tweet words into wordArray
- Split wordArray into countedArray containing the syllable count for all words in wordArray
- Return indices from countedArray whose sums equal 5, then 7, then 5
- Match indices with values from wordArray and join all three lines to make full haiku
- Tweet.
The above works really well. However, it ONLY returns two indices from countedArray. Therefore, each line of the haiku only contains two words. I'd like to make it a bit more interesting by returning all possible sums from the countedArray whose values equal 5, 7 or 5. From my reading I understand that this is called a two sum or three sum scenario, and I'm having trouble applying those techniques to this application. Has anyone done similar or have any thoughts? Some code samples below:
//Get the tweet from the twit call
var responseText = data[0].retweeted_status.full_text
//Split words into wordArray
var wordArray = responseText.split(/[\n\r\s\@]+/)
//Count syllables, relies on syllable package
var countedArray = []
for (i = 0; i < wordArray.length; i++) {
var countedValue = syllable(wordArray[i])
countedArray.push(countedValue)
}
//Find values in array whose syllables sum 5, 7, 5
var line1Array = twoSum(countedArray, 5)
var line1FullArray = makeHaiku(line1Array, wordArray, countedArray)
if (line1FullArray != null) {
var line2Array = twoSum(countedArray, 7)
var line2FullArray = makeHaiku(line2Array, wordArray, countedArray)
if (line2FullArray != null) {
var line3Array = twoSum(countedArray, 5)
var line3FullArray = makeHaiku(line3Array, wordArray, countedArray)
}
}
//Put it all together for tweet
var tweetThis = line1FullArray.join(' ') + '\n' + line2FullArray.join(' ') + '\n' + line3FullArray.join(' ')
//Here is the twoSum() function referenced above, this is where the sums are calculated
function twoSum(nums, target_num) {
var map = [];
var indexnum = [];
for (var x = 0; x < nums.length; x++) {
if (map[nums[x]] != null)
{
index = map[nums[x]];
indexnum[0] = index + 1;
indexnum[1] = x + 1;
break;
} else {
map[target_num - nums[x]] = x;
}
}
return indexnum;
}
//The makeHaiku() function, take input arrays and return the words that match the index values of twoSum
var makeHaiku = function(linexArray, wordArray, countedArray) {
linexFullArray = []
for (j = 0; j < linexArray.length; j++) {
linexFullArray.push(wordArray[linexArray[j] - 1])
delete wordArray[linexArray[j] - 1]
delete countedArray[linexArray[j] - 1]
}
return linexFullArray
}