I´m stuck in this task, is a lotto generation, and I have to use a for loop, a match and AND, but I don´t know where use the AND compound, and the code that I have wrote is not working, any help?
Use a For loop to step through each position in the winning numbers array and
to compare the customer number to each number the array contains.
To complete this, you will need to set up the following.
1. A counter variable (e.g. i) for the loop.
2. A boolean variable (e.g. match) to flag if a match has been found or not.
3. A compound AND condition that allows the loop to continue to iterate only
if a match is not found, and, the end of the array has not been reached.
4. An if statement nested inside the For loop which checks the customer
number against each winning number in the array, each time the loop
iterates, and sets the boolean, match, to true if a match is found.
This is my code
var customerNumbers = prompt ("Please enter your number");
var winningNumbers = ['12','17','24','37','38','43'];
var match = false;
//These are the messages that will be show
var winningMessage = "This Week's Winning Numbers are:\n" + winningNumbers + "\n";
var customerMessage = "The Customer's Number is:\n" + customerNumbers + "\n";
var winnerMessage = "We have a match and a winner";
var notWinnerMessage = "Sorry you are not a winner this week";
/* Adding a for loop with a conditional and a boolean
*/
for (i=0; i<winningNumbers.length; i++) {
if (!match){
alert( winningMessage + customerMessage + notWinnerMessage);
}
else {
alert( winningMessage + customerMessage + winnerMessage);
}
}
Many thanks
Try this (if customerNumbers are comma separated):
var customerNumbers = prompt("Please enter your number").split(/\s*,\s*/);
var winningNumbers = ['12','17','24','37','38','43'];
var match = true;
//These are the messages that will be show
var winningMessage = "This Week's Winning Numbers are:\n" + winningNumbers + "\n";
var customerMessage = "The Customer's Number is:\n" + customerNumbers + "\n";
var winnerMessage = "We have a match and a winner";
var notWinnerMessage = "Sorry you are not a winner this week";
/* Adding a for loop with a conditional and a boolean
*/
for (i=0; i<winningNumbers.length; i++) {
if (customerNumbers.indexOf(winningNumbers[i]) === -1) {
match = false;
break;
}
}
if (!match){
alert( winningMessage + customerMessage + notWinnerMessage);
} else {
alert( winningMessage + customerMessage + winnerMessage);
}
Related
I want to have it so the user is prompted to enter the second string, that will sort lower alphabetically than the first string. I don't understand how to make a string a number? Do I even need to do that?
function SortStringAlphabetically() {
// Declare variables
var stringOne = "";
var stringTwo = "";
var output;
// Get input from user
stringOne = prompt("Please enter a string");
stringTwo = prompt("Please enter enter a string that will sort lower alphabetically than the first string.");
// Convert input strings to numbers
stringOne = Number(stringOne);
stringTwo = Number(stringTwo);
if ( stringTwo > stringOne) {
output = "very good" + stringOne + "sorts lower than" + stringTwo + ".";
} else {
output = stringOne + "sorts higher than" + stringTwo + "try again";
}
document.write(output);
}
// Run the program
SortStringAlphabetically();
// END OF YOUR CODE
I am trying to set up a new Kata for CodeWars.
This code works in a browser (IE and Chrome).
When I run the test on a solution to my code in the CodeWars Kata setup page, I get an unexpected token error when I try to validate my solution to the Kata.
I am not familiar with Node JS; but, I think the error is a Node JS error.
This is my first try at writing/setting up a Kata. I did read a some of the tutorial pages.
The error appears to be pointing at either the end of the forEach statement or the end of the map statement. I checked all the brackets and parens. I think I have everything I need otherwise, it wouldn't run in a browser, right?
(Did I nest the forEach statement correctly inside the map statement?)
I have tried taking things out and running the code.
Here is
the error,
a list of my code with test data,
and an explanation of the Kata and how one should code a solution:
Here is the error I am getting:
[eval]:59
});
^ SyntaxError: Unexpected token )
at createScript (vm.js:56:10)
at Object.runInThisContext (vm.js:97:10)
at Object. ([eval]-wrapper:6:22)
at
at evalScript (bootstrap_node.js:353:27)
at run (bootstrap_node.js:122:11)
at run (bootstrap_node.js:389:7)
at startup (bootstrap_node.j
Here is my code with test data at the end:
<script>
function birdCode(arr){
var matchArr = [];
var str = "";
var arrReturn = arr.map(function(item){
str = "";
item = item.replace("-", " ").toUpperCase();
if(/ /.test(item) === false){ // Name with one word.
return item.slice(0, 4);
}
else if(item.match(/ /g).length === 1){ // Name with two words.
matchArr = item.match(/ [A-Z]{2}/);
str = matchArr.join("");
return item.slice(0, 2) + str.replace(" ", "");
}
else if(item.match(/ /g).length === 2){ // Name with three words.
var arrName = item.split(" ");
arrName.forEach(function(item, idx){
if(idx === 2){
str = str + item.slice(0, 2);
}
else{
str = str + item.slice(0, 1);
}
});
return str;
}
else if(item.match(/ /g).length === 3){ // Name with four words.
matchArr = item.match(/ [A-Z]{1}/g);
str = item.slice(0, 1) + matchArr.join("");
return str.replace(/ /g, "");
}
});
console.log("arrReturn: " + arrReturn);
return arrReturn;
}
birdCode(["American Redstart", "Northern Cardinal", "Pine Grosbeak", "Barred Owl", "Starling", "Cooper's Hawk", "Pigeon"]);
birdCode(["Great Crested Flycatcher", "Bobolink", "American White Pelican", "Red-Tailed Hawk", "Eastern Screech Owl", "Blue Jay"]);
birdCode(["Black-Crowned Night Heron", "Northern Mockingbird", "Eastern Meadowlark", "Dark-Eyed Junco", "Red-Bellied Woodpecker"]);
birdCode(["Scarlet Tanager", "Great Blue Heron", "Eastern Phoebe", "American Black Duck", "Mallard", "Canvasback", "Merlin", "Ovenbird"]);
birdCode(["Fox Sparrow", "White-Winged Crossbill", "Veery", "American Coot", "Sora", "Northern Rough-Winged Swallow", "Purple Martin"]);
You will be given an array of common American birds. You are to create
a function to convert these to the four-letter codes used by birders
and websites like eBird (created by the Cornell Lab of Ornithology and
the Audubon Society).
Rules:
If a given name in the input array is one word, return the first four
letters of the name as the code.
If the name is two words, return the first two letters of each word.
If the name is three words, return the first two letters of the first
two words and the first two letters of the third word.
If the name is four words long, return the first letters of all four
words.
(These are some of the rules of the actual process used to create
codes by the organizations mentioned above.)
The returned codes should be in an array. They should be in the order
in which they were given. The four letters in the returned codes
should all be in UPPER CASE.
Hyphen/dashes should be treated as spaces in a given bird name.
Note: No bad data will be given.
For example:
If you are given an array with these two values: "Herring Gull" and
"Black-Capped Chickadee"
You should return these two values: "HEGU" and "BCCH"
/////////////////////////////////////////////////////
Well, this probably means something...
I changed the code. I took out the forEach and the map. I used for loops instead.
And, I am still getting that error even though the code does not have "});" in it anywhere.
function birdCode(arr){
var matchArr = [];
var str = "";
var arrReturn = [];
for(var i = 0; i < arr.length; i++){
str = "";
arr[i] = arr[i].replace("-", " ").toUpperCase();
if(/\s/.test(arr[i]) === false){ // Name with one word.
arrReturn.push(arr[i].slice(0, 4));
}
else if(arr[i].match(/\s/g).length === 1){ // Name with two words.
matchArr = arr[i].match(/\s[A-Z]{2}/);
str = matchArr.join("");
arrReturn.push(arr[i].slice(0, 2) + str.replace(" ", ""));
}
else if(arr[i].match(/\s/g).length === 2){ // Name with three words.
var arrName = arr[i].split(" ");
var nameBuild = "";
for(var j = 0; j < arrName.length; j++){
if(j === 2){
str = str + arrName[j].slice(0, 2);
}
else{
str = str + arrName[j].slice(0, 1);
}
nameBuild = nameBuild + str;
str = "";
}
arrReturn.push(nameBuild);
}
else if(arr[i].match(/\s/g).length === 3){ // Name with four words.
matchArr = arr[i].match(/ [A-Z]{1}/g);
str = arr[i].slice(0, 1) + matchArr.join("");
arrReturn.push(str.replace(/\s/g, ""));
}
}
// console.log("arrReturn: " + arrReturn);
return arrReturn;
I have a bot which processes strings with given arguments. Here is what I've tried to get parameters of command:
parse: function (message, argLength) {
var words = message.split(" ");
words.shift(); // Don't return command name in array.
if (words.length < argLength) // If there is not enough parameters, return null
return null;
else if (words.length == argLength) { // If length is exact same, return
return words;
}
else { //Otherwise, concenate first ones till it is exact length.
var concenateString = "";
var length = words.length - argLength + 1;
for (var i = 0; i < length; i++) {
var element = words[0];
concenateString += " " + element;
words.shift();
}
words.unshift(concenateString);
return words;
}
}
If there are more parameters than required, it will automatically concenate first strings since it is split by spaces. a b c with two parameters to "a b" "c" for example. But if "'s are passed, I want to get words between "'s, not only conceding first ones.
Before doing any business logic you could use a regex to extract anything between " or words:
var str = 'one two "three is family"'
var re = /"([^"]+)"|([a-zA-Z0-9]+)/g
console.log(
str.match( re )
)
list of words that I want to convert to Swedish if they
happen to be present
var translate = {
"merry":"god",
"christmas":"jul",
"and":"och",
"happy":"gott",
"new":"nytt",
"year":"år"
};
// prompt for the text to be translated
var qu = prompt("what would you like to translate?");
// switching it into an array
var result = qu.split(" ");
// empty string to store my answer
var realResult = "";
// for loop to browse through the items in my array
for(i = 0 ; i < result.length ; i++){
/* place where im stuck, whatever I come up doesnt result in proper answer.
I tried to use for(asd in translate) loop to compare every element
but there is something im missing
*/
// if the item in the array is equal to the item in object replace
// that item
if( result[i] === translate[????] ){
realResult += translate.i + " ";
// else put the item from array into the string
} else {
realResult += result[i] + " ";
}
}
// print out the result
console.log(realResult);
I might be totally wrong here and the answer might lie somewhere else. thank you in advance
Just substitute this part:
if( result[i] === translate[????] ){
realResult += translate.i + " ";
// else put the item from array into the string
} else {
realResult += result[i] + " ";
}
With this line:
realResult += ( translate[result[i]] || result[i] ) + " ";
I have a friend who has an assignment on arrays and because I lack experience in Javascript and she just needs some real quick help understanding how to implement a Javascript loop to store data in an array which converts a letter grade to a number. Can someone just guide her in a general direction?
https://docs.google.com/fileview?id=16uNNiooLalkm1QlszrqEPr2qqMGLjhrtQx7qCLw-7d2ftygre8GM6hyceJHj&hl=en\
Update: She states that she doesn't understand how to make it prompt again after the first time while storing data. Can someone just write a translation for a C++ code for do {}?
Here's a more or less complete solution - but it doesn't output the results to the HTML page but outputs it with the alert boxes.
var done = false,
classes = [],
total_credits = 0,
avg = 0;
while(!done){
var class_name = prompt("Enter class name"),
letter_grade = prompt("Enter letter grade for "+class_name),
credit_hours = prompt("Enter credit hours for "+class_name),
number_grade = {"A":4,"B":3,"C":2,"D":1,"F":0}[letter_grade];
if(class_name && letter_grade && credit_hours){
classes.push({
class_name: class_name,
letter_grade: letter_grade,
number_grade: number_grade,
credit_hours: credit_hours
});
total_credits += parseInt(credit_hours,10);
avg += number_grade*credit_hours;
}else
done = true;
}
avg = avg/total_credits;
for(var i=0; i<classes.length; i++){
alert(classes[i].class_name + " | " +
classes[i].letter_grade + " | " +
classes[i].credit_hours);
}
alert("Total credits: " + total_credits);
alert("GPA: " + avg.toFixed(2));
Basically, she should use a while loop.
in (mostly) pseudocode:
more_entries = true;
while(more_entries)
{
response = prompt("Question for the user","");
if (response == null)
{
more_entries = false;
}
else
{
// store value somewhere
}
}
Of course, this needs to be expanded to multiple prompts.