const [counter, setCounter] = useState(0);
function sortPeople() {
const sortedPeople = [...peopleList];
let sortCount = counter;
if (sortCount === 2) {
sortCount = 1;
setCounter(1);
} else {
sortCount += 1;
setCounter(sortCount);
}
if (sortCount < 3) {
sortedPeople.sort(function (x, y) {
if (sortCount === 1) {
return x.eaten === y.eaten
? 0
: x.eaten === "No"
? -1
: 1;
} else if (sortCount === 2) {
return x.eaten === y.eaten
? 0
: x.eaten === "No"
? 1
: -1;
}
});
setPeopleList(sortedPeople);
}
}
const [counterCount, setCounterCount] = useState(0);
function sortCountPeople() {
const sortedCountPeople = [...customerList];
let sortCountVisit = counterCount;
if (sortCountVisit === 2) {
sortCountVisit = 1;
setCounterCount(1);
} else {
sortCountVisit += 1;
setCounterCount(sortCountVisit);
}
sortedCountPeople.sort(function (x, y) {
if (sortCountVisit === 1) {
return x.number - y.number;
} else if (sortCountVisit === 2) {
return y.number - x.number;
}
});
setPeopleList(sortedCountPeople);
}
I have trouble understanding : the sort logic from the if sort count is < 3, then theres like ? : 0 -1 1 and also for sorting count theres like y-x and x-y so can someone explain this code to mean that would be great thank you in advance very much
!
Snippet 1
if (sortCount < 3) {
sortedPeople.sort(function (x, y) {
if (sortCount === 1) {
return x.eaten === y.eaten
? 0
: x.eaten === "No"
? -1
: 1;
} else if (sortCount === 2) {
return x.eaten === y.eaten
? 0
: x.eaten === "No"
? 1
: -1;
}
});
}
If sortCount is 0(?), 1, or 2 (i.e. less than 3) then the sortedPeople array will be sorted.
Using a compare function:
function compare(a, b) {
if (a is less than b by some ordering criterion) {
return -1;
}
if (a is greater than b by the ordering criterion) {
return 1;
}
// a must be equal to b
return 0;
}
In other words, if -1 is returned then a comes before b and should move forward in the array, if 1 is returned then a comes after b and should move back in the array, and if 0 is returned a and b are considered "equal" and a stays where it's at.
In your callback if x.eaten is equal to y.eaten then 0 is returned and x doesn't move. If sortCount equals 1 and x isn't eaten yet then -1 is returned and x moves back in the array, otherwise it moves forward. If sortCount equals 2 then this is reversed, if x isn't eaten yet then 1 is returned and it moves forward, otherwise it moves back.
Update
Since there seems to be confusion over the ternary syntax I'll rewrite it using if-else statements.
function (x, y) {
if (sortCount === 1) {
if (x.eaten === y.eaten) {
return 0;
} else if (x.eaten === "No") {
return -1;
} else {
return 1;
}
} else if (sortCount === 2) {
if (x.eaten === y.eaten) {
return 0;
} else if (x.eaten === "No") {
return 1;
} else {
return -1;
}
}
}
Snippet 2
sortedCountPeople.sort(function (x, y) {
if (sortCountVisit === 1) {
return x.number - y.number;
} else if (sortCountVisit === 2) {
return y.number - x.number;
}
});
When comparing numbers the compare function can be much simpler:
function compareNumbers(a, b) {
return a - b;
}
If the result is negative, or less than zero, then a comes before b and should move forward in the array, if the result is positive, or greater than zero, then a comes after b and should move back in the array, and if the result is 0 they were equal and a stays where it's at.
In the callback if sortCountVisit equals 1 then the result will move x forward if it is less than y and back if it is greater than y. If sortCountVisit equals 2 then this is reversed, x moves back if less than y and forward if greater than y.
Related
I am a newbie to algorithm, I tried using recursion in binary search, I do get the result and it is correct, but the index of the result is wrong, I've tried over and over but just cannot the problem causing this. Here is my code:
function binarySearch(arr, num, pivot) {
const center = Math.round(arr.length / 2);
if (arr.length == 1 && arr[0] == num) {
return `num is :${arr} pivot is : ${pivot}`;
} else if (arr.length == 1 && arr[0] !== num) {
return -1;
}
if (pivot == undefined) {
pivot = center;
}
// console.log(`center is :${center}, pivot is ${pivot}`);
if (arr[center] == num) {
return `num is :${arr[center]} pivot is : ${[pivot - 1]}`;
} else if (arr[center] < num) {
return binarySearch(arr.slice(center, arr.length), num, pivot + 1);
} else {
return binarySearch(arr.slice(0, center), num, pivot - 1);
}
}
thank you for the response in advance!
Given a string, find the first non-repeating character in it and return its index. If it doesn't exist, return -1.
leetcode question
"cc" // -1
"ccdd" // -1
"leetcode" // 1
"loveleetcode" // 2
"abcabd" // 2
"thedailybyte" // 1
"developer" // 0
My approach passed all the test cases except the 2nd test case "ccdd". I am expecting -1 but receiving 4. Not sure why.
var firstUniqChar = function(s) {
if(!s || s.length === 0 ) return -1
else if(s.length === 1) return 0
let pointer1 = 0
let pointer2 = pointer1 + 1
if(s.length > 2){
while(pointer2 <= s.length - 1){
if(s[pointer1] !== s[pointer2])
pointer2++
else if(s[pointer1] === s[pointer2])
pointer1++
}
return pointer1
}
return -1
};
this is too old, but still can be too much shorter:
const firstUniqChar = (_str) => {
for (let i= 0; i < _str.length; i+= 1) {
if (_str.indexOf(_str[i]) === _str.lastIndexOf(_str[i])) return i+1;
}
return -1;
}
Below is my code, it works for some strings but not for all.
Ex: "()()()()()((" expected is false, my code returns true.
function validParentheses(parens){
var stack = [];
parens.split('').map((cur, index) =>{
if(stack.length === 0 || stack[index-1] === cur) stack.push(cur);
else stack.pop();
});
return stack.length > 0 ? false : true;
}
stack[index - 1] will be valid so long as you push every iteration. In the case that you pop an element, the incrementing index will always be out of bounds.
Change it to stack.length - 1 to always get the last element, regardless of what is pushed or popped.
For every '(' there must be a exactly one ')'. So you need a counter to see that there is an exact match
function validParentheses(parens){
const chars = parens.split('');
const numChars = chars.length;
let ii;
let numOpenParens = 0;
for (ii = 0; ii < numChars; ii += 1) {
curChar = chars[ii];
numOpenParens += curChar == '(' ? 1 : -1;
// return false if there is one too many closed parens
if (numOpenParens < 0) {
return false;
}
}
// return true only if all parens have been closed
return numOpenParens === 0;
}
For case when stack's length is greater than 0:
if top of the stack is equal to current iterated parenthesis, push that to stack
else pop the stack
function validParentheses(parens) {
var stack = []
parens.split("").forEach((cur) => {
if (stack.length > 0) {
if (stack[stack.length - 1] === cur) {
stack.push(cur)
} else {
stack.pop()
}
} else {
stack.push(cur)
}
})
return stack.length > 0 ? false : true
}
console.log(validParentheses("()()()()()(("))
console.log(validParentheses("()()()()()()"))
console.log(validParentheses("((()))"))
console.log(validParentheses("((())))"))
in stack[index-1] === cur
you are comparing if the char isn't the same like the one stored in the stack, so )( opposite parens will be valid
you can try do something like this
function validParentheses(parens) {
if (parens % 2 == 1) return false;
for (let i = 0; i < parens.length; i++) {
const char = parens[i];
if (char == "(") {
if (parens[i + 1] == ")") {
i++;
} else {
return false
}
} else {
return false
}
}
return true;
}
You need to check the last added value as well, because an unresolves closing bracket should remain in he stack.
BTW, Array#forEach is the method of choice, because Array#map returns a new array, which is not used here.
function validParentheses(parens) {
var stack = [];
parens.split('').forEach((cur, index) => {
if (cur === ')' && stack[stack.length - 1] === '(') stack.pop();
else stack.push(cur);
});
return !stack.length;
}
console.log(validParentheses("(())()"));
console.log(validParentheses("()()()()()(("));
console.log(validParentheses("))(())"));
I have written this piece of code that returns an array of odd numbers or even numbers depending on which of the arguments are greater than each other.
const number_game = (x, y) => {
// Code here
let numbersArray = [];
if (typeof x === 'number' && typeof y === 'number') {
if (x > y) {
for (let i = y + 1; i < x; i++) {
if (i % 2 === 0) {
numbersArray.push(i);
}
}
}
if (y > x) {
for (let i = x + 1; i < y; i++) {
if (i % 2 === 1) {
numbersArray.push(i);
}
}
}
if (y === x) {
return numbersArray;
}
return numbersArray;
}
else {
return `${x} and ${y} should be numbers`
}
}
console.log(number_game(3,13));
I have tested it with possible cases and it works but it keeps failing a hidden test online saying "expected [ Array(9) ] to deeply equal [ Array(11) ] or expected [ Array(10) ] to deeply equal [ Array(11) ]". I have tried to tweak my solution in different ways but it still didn't work. I want to know what I am doing wrong and how I can correct it.
P.S: A search on deepEquality reveals that "The assert.deepEqual() method tests if two objects, and their child objects, are equal, using the == operator".
I just can't seem to point where the error is specifically.
Only thing I could do was simplify it a bit.
const number_game = (x, y) => {
var isOdd = x > y;
let numbersArray = [];
if (typeof x != "number" || typeof y != "number") {
return "${x} and ${y} should be numbers";
}
for (let i = (isOdd ? y : x) + 1; i < (isOdd ? x : y); i++) {
if (i % 2 === (isOdd ? 0 : 1)) {
numbersArray.push(i);
}
}
return numbersArray;
};
console.log(number_game(13, 3));
So after much inquisitiveness and research, I discovered that the problem specs and the test cases are in conflict. An input of (12, 0) should yield => [2,4,6,8,10] according to the problem specs but that result will return this error as a failed test "expected [ Array(9) ] to deeply equal [ Array(11) ] or expected [ Array(10) ] to deeply equal [ Array(11) ]". However, I observed that when I remove the + 1 from let i = x + 1 and y = x + 1 and I add the equal to sign to i <=x and i <=y termination conditions, the test passes. The adjustment, however, returns this result [ 0, 2, 4, 6, 8, 10 ] which is not correct with the problem specs. This is the code that passed the test:
const number_game = (x, y) => {
// Code here
let numbersArray = [];
if (typeof x === 'number' && typeof y === 'number') {
if (x > y) {
for (let i = y; i <= x; i++) {
if (i % 2 === 0) {
numbersArray.push(i);
}
}
}
else {
for (let i = x; i <= y; i++) {
if (i % 2 === 1) {
numbersArray.push(i);
}
}
}
return numbersArray;
}
else {
return `${x} and ${y} should be numbers`
}
}
This probably has an easy solution, but I simply don't see it at the moment.
I have three if-clauses that ashould be activated based on the length of an array. The first two ones seem to work fine, but for some odd reason I can't activate the third one (arr.length === 3). Right before the if clauses I have tried an alert to test whether it gives the right length of the array and it does.
function calculateDistances() {
var arr = [];
arr.push(posM, posL, posR);
alert(arr[1])
for (var i = 0; i < arr.length; i++) {
if (!arr[i]) {
arr.splice(i,1)
}
}
alert(arr.length)
if (arr.length === 0 || 1) {
return true;
}
else if (arr.length === 2 ) {
var diameter = calculateDiameter(arr[0], arr[1])
if (diameter > minDistance) {
return false;
}
else {
return true;
}
}
else if (arr.length === 3) {
alert("hello")
var diameter1 = calculateDiameter(arr[0], arr[1]);
var diameter2 = calculateDiameter(arr[0], arr[2]);
var diameter3 = calculateDiameter(arr[1], arr[3]);
if (diameter1 && diameter2 && diameter3 < minDistance) {
return true
}
else{
return false
}
}
}
Nor can you activate the second.
There's a bug here: if (arr.length === 0 || 1) {
The 1 casts to true.
Perhaps you meant: if (arr.length === 0 || arr.length === 1) {
You need this:
if (arr.length === 0 || arr.length === 1) {
The way you put it, it is equal to
if ((arr.length === 0) || true) {
which is always true.
I think what you are looking for is below condition in the first if condition
if (arr.length === 0 || arr.length === 1) {
return true;
}
this checks whether the length of the array is 1 or it's 0. Your first if condition is always true as it has 1 which is true.
(arr.length === 0 || 1)
is always true.
You could usethis instead
if (arr.length <= 1)
{
return true;
}