Filling in undefined value in javascript object - javascript

I'm working on a problem where the task is to write a program which reconstructs each sentence out of a set of words and prints out the original sentences.
INPUT SAMPLE:
2000 and was not However, implemented 1998 it until;9 8 3 4 1 5 7 2
And the answer is:
However, it was not implemented until 1998 and 2000
So far I got to the point where I have combined the words and number hints together as a pair value in an object. The only problem I am running into is that there is actually a missing number hint, thus one of the words has an undefined value.
How can I fill in this value?
I have tried to use .HasOwnProperty() and for-looping through to see if one of the values equals to undefined, but neither has worked. Any input would be greatly appreciated!
function encyrption(str){
var string = str.split(";");
var words = string[0].split(" ");
var hints = string[1].split(" ");
var object = {};
for(var i = 0; i < words.length; i++){
if(object[hints[i]] === undefined){
/////???
}else
object[hints[i]] = words[i];
}
return object;
}
console.info(encyrption("2000 and was not However, implemented 1998 it until;9 8 3 4 1 5 7 2"));

I'd do something like that, just guessing that the missing hint is the last word, and that will always be the sixth position. If that's not the case I'd need more information about the problem test cases to solve it.
function encyrption(str){
var string = str.split(";");
var words = string[0].split(" ");
var hints = string[1].split(" ");
var hints_sorted = hints.concat().sort();
var missing_hint;
var object = {};
for(var i = 0; i < words.length; i++) {
if(hints_sorted[i] != i+1) {
missing_hint = (i+1).toString();
break;
}
}
hints.push(missing_hint);
for(var i = 0; i < words.length; i++){
object[hints[i]] = words[i];
}
return object;
}
console.info(encyrption("2000 and was not However, implemented 1998 it until;9 8 3 4 1 5 7 2"));
//Result: However, it was not implemented until 1998 and 2000
There you have a small explanation:
I created the hints_sorted array, which is a copy of the hints one, but sorted, so, in our example:
hints = ['9','8','3','4','1','5','7','2'];
hints_sorted = ['1','2','3','4','5','7','8','9'];
Then, inside the for, I'm comparing the value with the index + 1 (since the index inside the loop starts at zero):
1 -> 1
2 -> 2
3 -> 3
4 -> 4
5 -> 5
7 -> 6
On the sixth element, we have 7 on our array and we are expecting 6, so it goes inside the if, we set 6 as our missing hint, and we break; the loop so it doesn't continue checking values.

Related

I'm trying to create a function that follows the Luhn's Algorithm [duplicate]

This question already has answers here:
Implementation of Luhn algorithm
(14 answers)
Closed 9 months ago.
This post was edited and submitted for review 9 months ago and failed to reopen the post:
Original close reason(s) were not resolved
I tried to multiply each number whose index number is an even number by two, and that worked fine. Still, the problem lies here: If any of the results is greater than or equal to 10, then add up the two numbers, for example, if one of the results is 12, then add up 1 and 2, which should be equal to 3. So this is what I tried:
var num = 122345643345673;
var convNum = num.toString();
var aftertoString = convNum.split("");
for(let i = 1; i < aftertoString.length; i++){
if (i % 2 == 0) {
var multi = aftertoString[i] * 2;
if(multi > 10){
var multiStringed = multi.toString();
var aftermutliStringed = multiStringed.split("");
var first = parseInt(aftermutliStringed[2])
var multi = first + first;
}
console.log(multi);
}
}
Since any index of the "aftermultiSringed" array is not a number, I tried to convert it to a number using the "parseInt()" method, but the result is NaN, please why am I getting this.
The method parseInt usage is incorrect.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt
// var first = aftermultiStringed[1].parseInt();
var first = parseInt(aftermultiStringed[1]);

How to edit a characters in a string, and remove characters that editing conditions apply to

I'm trying to take in a number from a user, display the number as a range,and then replace instances of the number 3 with a string, instances of the number 2 with a string, and instances of the number 1 with a string. If the function detects a 3, I want it to replace it with the string, remove the instance of 3, and ignore the conditions for replacing 2 & 1. The same goes for when it sees a 2 (but not a 2).
I have the function taking in the number from the user, converting it to a string, and then displaying it as a range using a for loop.
In the for loop I use .includes to look for a '3.' When it sees one it is pushing the string "I'm sorry Dave, I can't do that" to the same list that displays the range.
I've tried an if/else if statement to have the loop ignore the conditions for 2 and 1 if it first sees a three, however it is applying all conditions to all instances of 3,2, or 1.
function numTranslate(inputNumber){
var numList = [];
var num = inputNumber
for (i = 0; i<= num; i++){
var numString = i.toString();
if (numString.includes('3')) {
numList.push("I'm sorry Dave, I can't do that")
}
else if (numString.includes('2')) {
numList.push("boop!")
}
else if (numString.includes('1')) {
numList.push("beep!")
}
numList.push(i)
}
return numList;
}
What I'm getting
input: 9
Output: 0,beep!,1,boop!,2,I'm sorry Dave, I can't do that,3,4,5,6,7,8,9,
What I want:
input: 9
Output: 1,2, I'm sorry Dave, I can't do that, 4, 5, 6, 7, 8, 9
If you want that output then remove the if clauses for 1 and 2. Your code is working fine except for those 2 if clauses. Also, start at 1 if you want to ignore 0.
Another thing, why in the world are you converting this to a string and then checking if the string includes the char? These are numbers, do number operations on them. You are adding unnecessary overhead by converting them and checking against the conversion.
function numTranslate(inputNumber){
var numList = [];
var num = inputNumber
for (i = 1; i<= num; i++){
if(i === 3){
numList.push("I'm sorry Dave, I can't do that");
}else{
numList.push(i);
}
}
return numList;
}
console.log(numTranslate(9));
Here is simple way of doing it.
function numTranslate(inputNumber){
return Array.from(Array(inputNumber), function (value, index) {
var i = index+1;
if (i== 1 || i==2){
return "beep!";
}
if (i== 3){
return "I'm sorry Dave, I can't do that";
}
return i.toString()
});
}
console.log(numTranslate(9))

Separating while loop output in JavaScript

I currently have this small script that outputs a value after each iteration of a while loop:
var i = 0;
var number = "";
while (i < 10) {
number += console.log(i);
i++;
}
Which creates this output:
0
1
2
3
4
5
6
7
8
9
However, I am testing some API calls and using the while loop in JavaScript to see if I can send values consistently, so my values are coming from the script below:
var i = 0;
var number = "";
while (i < 10) {
number += (i);
i++;
}
I do not need console.log() because I do not need the output in the terminal. My issue is when looking at the output on the receiving end when using the API, it looks something like this:
0
01
012
0123
01234
012345
0123456
01234567
012345678
0123456789
The API calls are in the while loop as well, I did not include them because I feel this is a JavaScript syntax related issue. So what will happen is that the while loop begins, number is iterated, that value is sent to a website using an API call, and the the while loop begins again. Something like the code below:
var i = 0;
var number = "";
while (i < 10) {
number += (i);
API_Send(number)
i++;
}
What can I do to so that the output of each iteration is its own separate variable similar to the output using console.log(), so first iteration is 0, second iteration is 1, and so on.
I feel this is something that would be necessary when outputting values to be used by a function. So perhaps it is best to create a function that has a while loop outputting integer values?
The problem is that you have declared number as string, don't do that just assign 0 to number variable.
Because of string variable javascript is concatenating the numbers.
Change as following:
var i = 0;
var number = 0;
while (i < 10) {
number += (i);
console.log(number)
i++;
}

Check lines A and count it until it changes to lines B javascript

I am sorry in advance if my title is somehow misleading and I am really sorry for my English if you wouldn't understand me, it's just not my native language!
I will try to explain as better as I can about what I try to achieve. I try to do this for past two entire days and I really need your help!
Let's say I have array with the following numbers:
2 4 6 8 10 1 3 5 2 4
I am trying to count how many even and odd numbers are here in a row, and when even/odd changes - count it again. So my answer from the array above should be:
5 (5 even numbers in a row) 3 (3 odd lines in a row) (2 even lines in a row)
Also when the counting isn't stopped it should post "<br>" instead of counted evens/odds, so it could show me results one time near to each line.
Check this example image:
I have this script which is counting, but it has a few issues: when number is even, it shows counting twice. Next, I can't figure it out how to add <br> to these lines where counting and add result only at the last line of counting. Also my counting result should be at the top, so the script should count from the end as I guess, and when I try i-- it starts the infinite loop...
var digits = ["2, 4, 6, 8, 10, 1, 3, 5, 2, 4"]
var evenCount=1, oddCount=1;
for(var i =0; i < digits.length; i++){
if(digits[i] % 2 ==0){
var oddCount=1;
$("#res").append(evenCount + " (l) <br>");
evenCount++;
}
else
var evenCount=1;
$("#res").append(oddCount + " (n) <br>");
oddCount++;
}
Check my fiddle to see it in action:
https://jsfiddle.net/xk861vf9/8/
First, I think your code show counting twice because you misses two '{' after "for loop" and "else". After I fix the code format, I don't see it counting twice anymore.
$(document).ready(function() {
$("#sub").bind("click", function() {
$("#res").html("");
var digits = $('#content').find("span").map(function() {
return $(this).text();
});
var evenCount = 1;
var oddCount = 1;
for(var i =0; i < digits.length; i++) {
if (digits[i] % 2 ==0) {
oddCount = 1;
$("#res").append(evenCount + " (l) <br>");
evenCount++;
} else {
evenCount=1;
$("#res").append(oddCount + " (n) <br>");
oddCount++;
}
}
});
});
Second, they are many ways to implement that. Take a look at this jsfiddle code as an example.
https://jsfiddle.net/xk861vf9/11/
The concept is to print the counted number after even/odd number changes. Then use for loop to print <br> x times (counted number - 1) so if counted number is 4, there will be 3 <br> tags followed.We also have to check if current number is the last number in array and print the counted number or else the last counted number will be skipped.
Hope this help! :)
Ps. Sorry for my bad English, not my native language too.

Concatenating string with number in Javascript

I'm trying to create a simple calculator in Javascript. I have an array named expression
chunk[0] = 12
chunk[1] = + (the "+" sign)
chunk[1] = 5
I used a for loop to loop through the chunks (chunk[]) and join then into a single expression as follows:-
equation = ""; // To make var equation a string
for(i = 0; i <= length; i++)
{
equation = equation + expression[i];
alert(expression[i]);
}
alert(equation);
alert(expression[i]) showed values 12, + and 5.
But alert(equation) showed 125 (instead of "12+5"). I need the variable equation to be "12+5" so that I can later call eval(equation) and get the value of 12+5.
What am I doing wrong here?
if you have chunk = [ 12, '+', 5]; then you can do var eq = chunk.join(""); and then pass it to eval
What are you doing wrong? You have a small typo.
Amend the code on the question from
chunk[0] = 12
chunk[1] = '+'
chunk[1] = 5
to
chunk[0] = 12
chunk[1] = '+'
chunk[2] = 5
And everything should work.
Why this works:
Both the + and the 5 are being assigned to chunk[1], with the 5 over-writing the previous assignment ( to chunk[1]) of +. This also explains why the concatenated value displayed is 125
In order, the first assignment results in a collection with
a member chunk[0] and a content of 12
The second assignment adds a new member, and results in a collection with
a member chunk[0] whose content is 12
a member chunk[1] whose content is +
The third assignment overwrites the 2nd member, and results in a collection with
a member chunk[0] whose content is 12
a member chunk[1] whose content is 5
The concatenation of all the chunks == 125
Desired concatenation == 12+5

Categories