Hello I am working on a practice program for customers taking a position in line at a deli.
Except when I call the line() function it will end with the first name in the array.
// `The line is currently customer name
How would one allow that single string output to contain all the customers in my array?
//ex: `The line is currently customer1 customer2 customer3 etc...
I was thinking I could use the repeat function for this but am having trouble making it work.
Am I thinking about that wrong, or is there another method to do so? Thanks!
let deli = []
const line = (array) => {
if (array.length === 0) {
console.log(`The line is currently empty.`)
} else if (array.length > 0) {
let count = 0
for (let el in array) {
count++
let order = `${count}. ${array[el]}`
let greeting = console.log(`The line is currently: ${order}`)
return greeting
}
}
}
line(deli)
EDIT: Hello, sorry. People always get mad at me on here, I'm very new to programming and still figuring everything out.
Essentially I'm using this below function to push names into the array. And when you call line() it should show all the names added!
const takeANumber = (katzArr, customer) => {
let count = 0
katzArr.push(customer)
for (i = 0; i < katzArr.length; i++)
if (katzArr.length) {
count = katzArr.length
let greeting = console.log(
`Welcome ${customer}. You are number ${count} in line.`
)
return greeting
}
}
You can use .join() method. It works on arrays. So for example you have an array-
const customers = ['customer1', 'customer2', 'customer3']
customers.join(', ') would return customer1, customer2, customer3
Cheers
const animals = ['pigs', 'goats', 'sheep'];
const line = (array) => {
if (array.length === 0) {
console.log(`The line is currently empty.`)
} else if (array.length > 0) {
let count = [];
for(let i = 0; i < array.length; i++){
count.push(`${array[i]} ${i + 1}`)
}
console.log(`The line is currently ${count.join(',')}`)
}
}
line(animals)
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 months ago.
Improve this question
So I'm currently working my way through an algorithms course and this was provided as the answer for the leetcode problem "Palindrome Partitioning". I would like to be able to refactor the code so that it does not mutate the answer array and instead returns it. Preferably there would be no separate dfs function, just one recursive function called partition. I'm normally decent at this kind of thing but I'm struggling with this one:
function partition(s) {
const ans = [];
const n = s.length;
function dfs(start, part) {
if (start == n) {
ans.push([...part]);
return;
}
for (let i = start + 1; i < n + 1; i++) {
const prefix = s.substring(start, i);
if (isPalindrome(prefix)) {
part.push(prefix);
dfs(i, part);
part.pop();
}
}
}
dfs(0, []);
return ans;
}
This is my attempt so far:
function partition(str, start) {
const result = [];
if (start == str.length) {
result.push([str]);
} else {
for (let i = start + 1; i < str.length; i++) {
const prefix = s.substring(start, i);
if (isPalindrome(prefix)) {
const results = partition(str, start + 1);
if (results.length) {
for (const r of results) {
result.push([prefix, ...r]);
}
} else {
result.push([prefix, s.substring(i + 1)]);
}
}
}
}
return result;
}
Your attempt needs a few corrections:
Spelling of s and str is not consistent
The start parameter needs a default value of 0
The recursive call is made with a wrong index. Not start + 1, but i
The base case should not place the whole string in an array. On the contrary that newly pushed array should be empty: result.push([]) or why not return [[]] immediately.
results.length will never be zero when coming back from recursion; the else block will never execute -- it can be omitted.
The for loop is making one iteration too few. The end condition should be i <= s.length
Here is the corrected version:
function partition(s, start=0) {
if (start == s.length) {
return [[]];
}
let result = [];
for (let i = start + 1; i <= s.length; i++) {
const prefix = s.slice(start, i);
if (isPalindrome(prefix)) {
for (const part of partition(s, i)) {
result.push([prefix, ...part]);
}
}
}
return result;
}
Note that this makes the solution a tad slower.
If you appreciate single-exit functions, you might also appreciate a (mutation-free) single-expression version:
const isPalindrome = (s) => s .split ('') .reverse () .join ('') == s
const palindromePartition = (s, i = 1, p = s .slice (0, i)) =>
s .length == 0
? [[]]
: i > s .length
? []
: [
... (isPalindrome (p) ? palindromePartition (s .slice (i)) .map (pp => [p, ...pp]) : []),
... (palindromePartition (s, i + 1))
]
console .log (palindromePartition ('aab'))
console .log (palindromePartition ('levelalevel'))
.as-console-wrapper {max-height: 100% !important; top: 0}
Here the body of our main function (so too the body of the isPalindrome helper) is a single expression. Developed independently from the original or trincot's refactoring, it mostly still expresses the same logic, just structures it differently.
Here are Trincot's answers modified to be single entry, single exit. For anyone wondering why someone would want to do this, or for the inevitable downvoting it will get by the early return brigade, I've provided an analogy and a diagram at the bottom.
function partition(str, start = 0) {
const result = [];
if (start != str.length) {
for (let i = start + 1; i <= str.length; i++) {
const prefix = str.slice(start, i);
if (isPalindrome(prefix)) {
const partitions = partition(str, i);
if (partitions.length == 0) {
result.push([prefix]);
} else {
for (const part of partitions) {
result.push([prefix, ...part]);
}
}
}
}
}
return result;
}
function partition(str, start = 0) {
const result = [];
if (start != str.length) {
for (let i = start + 1; i <= str.length; i++) {
const prefix = str.slice(start, i);
if (isPalindrome(prefix)) {
const partitions = partition(str, i);
for (const part of partitions) {
result.push([prefix, ...part]);
}
}
}
}
return result.length
? result
: [[]];
}
function partition(str, memo = {}) {
const result = [];
if (str) {
if (memo[str]) {
result.push(...memo[str])
} else {
for (let i = 1; i <= str.length; i++) {
const prefix = str.slice(0, i);
if (isPalindrome(prefix)) {
for (const part of partition(str.slice(i), memo)) {
result.push([prefix, ...part]);
}
}
}
memo[str] = result;
}
}
return result.length
? result
: [[]];
}
function partition(str, memo = {}) {
const result = [];
if (str) {
if (memo[str]) {
result.push(...memo[str]);
} else {
for (let i = 1; i <= str.length; i++) {
const prefix = str.slice(0, i);
if (isPalindrome(prefix)) {
const partitions = partition(str.slice(i), memo);
if (partitions.length == 0) {
result.push([prefix]);
} else {
for (const part of partitions) {
result.push([prefix, ...part]);
}
}
}
}
memo[str] = result;
}
} else {
result.push([]);
}
return result;
}
Structured Programming Hallway Analogy
Imagine you’re given a key and sent into a hallway. All along the hallway are locked doors to rooms and right at the end of the hallway is the exit.
As you come to a door along the hallway, you put your key in it and see if it opens. If it does, you enter the room. Inside the room there might be more doors. You try your key to see if any open. If they do, you walk inside and take a look around. Once you are finished in a room and there are no more doors to try you calmly walk back out to the hallway and out of the exit. This is structured programming.
Now imagine the same scenario. This time you come to a room in the hallway and the door unlocks. Great, you think, and walk straight in. Upon entering the room the door locks behind you, the floor caves in and you find yourself falling into darkness. You are being ejected from the building via a trap door. Congratulations, you have encountered an early return.
If you are working on a large codebase, the code you write will be worked on by people many years after you've departed the company. Which building would you rather explore? Which building do you want to leave for them?
Visually:
Having trouble getting my code to log Scooby Doo! (as testing as I move forward in my code) Instead I always get the alert!
I have the user entering data of numbers in an array eg. [1 2 3 4] and I am trying to get the alert to pop up when someone puts extra spaces in the array to try again.
And if they haven't added extra spaces to log Scooby Doo!
document.getElementById("button").addEventListener("click", myExcelFuns);
function myExcelFuns() {
var userInputStr = document.getElementById("numbers").value;
if (userInputStr) {
console.log(userInputStr);
userInputStr = userInputStr.trim();
let userNumberArray = userInputStr.split(" ");
console.log(userNumberArray);
let result;
let newArray = [];
for (let i = 0; i < userNumberArray.length; i++) {
let newArrayValues = parseInt(userNumberArray[i]);
newArray.push(newArrayValues);
}
console.log(newArray);
//Here is the trouble
let finalArray = [];
if (newArray === Number && newArray != ""){
for (let i = 0; i < newArray.length; i++) {
console.log("Scooby Doo");
finalArray.push(newArray);
}
} else {
alert("Only one space between numbers please!")
}
}
This expression is wrong and it will never be true:
if (newArray === Number && newArray != ""){
if (newArray === Number && newArray != ""){
for (let i = 0; i < newArray.length; i++) {
console.log("Scooby Doo");
// Here you'll push whole newArray everytime it runs, I guess it's wrong as well
finalArray.push(newArray);
}
} else {
alert("Only one space between numbers please!")
}
I've wrote your code using some features from ES6 to show you how easy is our life using these features.
//Here you must pass a valid Id
document.getElementById("myButton").addEventListener("click", myExcelFuns);
function myExcelFuns() {
var userInputStr = document.getElementById("numbers").value;
if (userInputStr) {
userInputStr = userInputStr.trim();
let userNumberArray = userInputStr.split(" ");
//check if some value into arrya is not a number
const isThereSomeInvalidNumber = userNumberArray.some(x => isNaN(x))
if(isThereSomeInvalidNumber){
alert("Only one space between numbers and valid numbers please!");
//here if it's invalid you can clear the input
document.getElementById("numbers").value = "";
}
//map runs into your array and return a new array
const newArray = userNumberArray.map(x => {
return parseInt(x)
})
console.log(newArray);
}
}
<button id="myButton">
click me
</button>
<input type="text" id="numbers" />
I hope it can inspire you =)
function ranNum(value) {
return Math.ceil(Math.random() * value)
}
function createRanId(value) {
const alphabet = 'abcdefghijklmnopqrstuvwxyz'.split('')
const numbers = '0123456789'.split('')
const idLength = value || 6
let id = ''
for(let i = 0; i < idLength; i++) {
const numOrAlpha = ranNum(2)
numOrAlpha === 1 ? id += alphabet[ranNum(alphabet.length - 1)] : id += numbers[ranNum(numbers.length - 1)]
}
return id
}
function isAllNumbers(arr) {
return arr.every(value => Number.isInteger(value))
}
function allNumberId() {
let count = 0
let ranNum = createRanId(2).split("");
while(!isAllNumbers(ranNum)) {
ranNum = createRanId(2).split("")
count++
}
return [count, ranNum]
}
console.log(allNumberId())
So what im doing is generating a random string that consists of numbers and letters (for example: 3e3jjf). What i'm trying to achieve is to find a generated combination that only consists of numbers (for example: 235033). However, my code doesnt seem to work and ends up in an infinite loop. I'm making a thinking error somewhere in the function allNumberId
edit: this is obviously not production code or anything. I'm just practicing some javascript. It bugs me that I cant find what I do wrong here.
In your code you are checking for a number
Number.isInteger("6")
When it is a string it is false. So you need to alter your code to try to make it into a number or other option is isNaN()
function ranNum(value) {
return Math.ceil(Math.random() * value)
}
function createRanId(value) {
const alphabet = 'abcdefghijklmnopqrstuvwxyz'.split('')
const numbers = '0123456789'.split('')
const idLength = value || 6
let id = ''
for(let i = 0; i < idLength; i++) {
const numOrAlpha = ranNum(2)
numOrAlpha === 1 ? id += alphabet[ranNum(alphabet.length - 1)] : id += numbers[ranNum(numbers.length - 1)]
}
return id
}
function isAllNumbers(arr) {
return arr.every(value => Number.isInteger(+value))
}
function allNumberId() {
let count = 0
let ranNum = createRanId(2).split("");
while(!isAllNumbers(ranNum)) {
ranNum = createRanId(2).split("")
count++
}
return [count, ranNum]
}
console.log(allNumberId())
Your check could also be done as
const isInvalid = yourString.split("").map(Number).some(isNaN)
The problem is the usage of Number.isInteger. You're actually passing strings there (single-character strings consisting of a digit or a alphabet char), which is never a number (integer or not) so Number.isInteger always returns false and your isAllNumbers function doesn't recognice what it should.
Good day,
I am trying to create a dice poker browser game. The problem that I am having is that I can't seem to figure out how to check the results after a round efficiently.
So far I have come up with a switch statement which checks if there is a case of "five of a kind". If so, return something, if not continue.
const getResult = diceArr => {
// Create an array with only the numbers
let dice1 = diceArr[0].randomNum;
let dice2 = diceArr[1].randomNum;
let dice3 = diceArr[2].randomNum;
let dice4 = diceArr[3].randomNum;
let dice5 = diceArr[4].randomNum;
diceArray = [];
diceArray.push(dice1, dice2, dice3, dice4, dice5);
// Check the result using a switch statement. Start at the highest rank. If encountered, stop checking.
let result;
switch(result) {
case diceArray[0] === diceArray[1] === diceArray[2] === diceArray[3] === diceArray[4] :
console.log('5 of a kind!');
break;
// case ? -> No idea where to go from here
}
}
What would be an efficient way of checking if exactly 4 out of 5 items in the array are the same?(4 of a kind)
Also, is a switch statement a good way to solve a problem like this?
Any feedback would be greatly appreciated!
You could create a counter object which will have each randomNum as key and the number of times it appears as value. Then, check if the counter has 4 as value using Object.values() and includes
const counter = diceArr.reduce((acc, o) => {
acc[o.randomNum] = acc[o.randomNum] + 1 || 1;
return acc
}, {})
const isFourOfAKind = Object.values(counter).includes(4);
console.log(isFourOfAKind)
This function returns true if there are four cards with the same value:
function areThereFourSameCards(cards) {
const groups = cards.reduce((acc, card) => {
acc[card] = (acc[card] + 1) || 1;
return acc;
}, {});
Object.keys(groups).some(k => groups[k] === 4)
}
Can be generalised to match different values.
You can use Array.reduce() to create an object holding the number of occurrences of each element. Then iterate over it to check if an item is occurred 4 times.
var diceArr = new Array(5).fill(0).map((item) => Math.floor(6*Math.random())+1); // Fill array with random numbers
console.log(diceArr);
var repeatings = diceArr.reduce((acc, item) => {
if (!acc[item]){
acc[item] = 0;
}
acc[item]++
return acc
}, {} )
console.log(repeatings);
var repating4times = Object.keys(repeatings).find((key) => repeatings[key] == 4)
console.log(repating4times);
Hope this helps
If I understand you correctly, you want to confirm that an element appears exactly 4 times in an array. That is 4 elements of the same kind out of 5.
This particular case comes with some limitations that would make solution easier.
Because we need 4 elements out of 5 to be the same
- you can only have two different elements in the array
This means you don't even have to check all the items. Only the first two will suffice.
A naive approach you could go with that would work pretty well because you're working with such small datasets would be a simple greedy algorithm.
You want to take the first two elements and traverse the whole array to see if either one exists three more times in the array. Remember our limitations above. To make the job easier, having a nice function to help count how many times an element appears in an array would be nice.
function countEntries(item, array) {
let count = 0
for (let i = 0; i < array.length; i++){
if (item === array[i])
count++;
}
return count
}
That function does exactly that and is very easy to understand. Now for the main solution:
function oneOfAKind(results) {
let result
let isOneOfAKind = false
for (let i = 0; i < 2; i++) {
const item = results[i]
const itemCount = countEntries(item, results)
if (itemCount === 4) {
result = item
isOneOfAKind = true
break
}
}
return [isOneOfAKind, result]
}
So this function returns an array containing a boolean and a number. If the array contains a "one of a kind" element, it returns an array containing true, and the one of a kind element.
Let's test it:
const diceResults = [4, 3, 3, 3, 3]
oneOfAKind(diceResults)
// returns [true, 3]
I hope this helps!
Since you have already checked whether all items are equal or not hence I will give you a hint to check equality exactly for the four items in your case:
function checkEqualityForFour(){
var diceArray=new Array(2,2,1,2,2);
for(var i=0;i<=1;i++){ //we have to check equality of 4 among 5 values
var count=1;
for(var j=i+1;j<diceArray.length;j++){
if(diceArray[i]==diceArray[j])
count++;
}
if(count==4)
return true;
}
return false;
}
console.log(checkEqualityForFour());
}
Let arr=[1,1,1,1,2] be my array
Try
new Set(arr.map(x=>x.toString())).size
if(arr.toString().split(arr[0]).length==5 || arr.toString().split(arr[1]).length==5)
console.log('Exactly 4 matches')
Try something like below
const getResult = diceArr => {
// Create an array with only the numbers
let dice1 = diceArr[0].randomNum;
let dice2 = diceArr[1].randomNum;
let dice3 = diceArr[2].randomNum;
let dice4 = diceArr[3].randomNum;
let dice5 = diceArr[4].randomNum;
diceArray = [];
diceArray.push(dice1, dice2, dice3, dice4, dice5);
diceCheck = {}
diceArray.forEach((item)=>{
diceCheck[item] = diceCheck[item] || 0;
diceCheck[item] += 1;
});
if(Object.keys(diceCheck).length == 2){
console.log("Voila");
}
}
I have been playing around with a pokemon API for a couple of days.
I have an array with all pokemon listed and have a string that looks something like this '<#user_id pidgeotto>'
I would like to check this string, against an array and get that EXACT name
My issue is that I ALSO get things that would be included, like pidgeot.
How can I match the array exactly to the string and ONLY log the one name?
let pokemonArray = ["pidgeot", "pidgeotto", "charizard", "goldeen"];
let y = '<#user_id> pidgeotto';
function handleMessage(message) {
for (let i = 0; i <= message.length; i++) {
if (y.includes(message[i])) {
console.log(message[i])
}
}
}
handleMessage(pokemonArray);
No errors, just not getting the result I am looking for.
Split the y string at the space and see if second part is exact using === comparison
let pokemonArray = ["pidgeot", "pidgeotto", "charizard", "goldeen"];
let y = '<#user_id> pidgeotto';
let yName = y.split(' ')[1];
function handleMessage(message) {
for (let i = 0; i <= message.length; i++) {
if (message[i] === yName ) {
console.log(message[i])
}
}
}
handleMessage(pokemonArray);
you could do it by this way to avoid the first element in PokemonArray
let pokemonArray = ["pidgeot", "pidgeotto", "charizard", "goldeen"];
let y = '<#user_id> pidgeotto';
function handleMessage(message) {
for(let i = 0; i <= message.length; i++) {
let splitedY = y.split(message[i])
if(splitedY.length > 1 && splitedY[1] !== "") {
console.log(message[i])
}
}
}
handleMessage(pokemonArray);
Here is the one liner for this:
const match = pokemonArray.find(pokemon => new RegExp(`\\b${pokemon}\\b`, `i`).test(y));
Simply use array find method and match your string using regex.
Hope this helps :)