Javascript Sherlock Array [closed] - javascript

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 7 years ago.
Improve this question
Problem Statement
Watson gives Sherlock an array A of length N. Then he asks him to determine if there exists an element in the array such that the sum of the elements on its left is equal to the sum of the elements on its right. If there are no elements to the left/right, then the sum is considered to be zero. Formally, find an i, such that,
A1+A2...Ai−1=Ai+1+Ai+2...AN.
Input Format
The first line contains T, the number of test cases. For each test case, the first line contains N, the number of elements in the array A. The second line for each test case contains N space-separated integers, denoting the array A.
Output Format
For each test case print YES if there exists an element in the array, such that the sum of the elements on its left is equal to the sum of the elements on its right; otherwise print NO.
Constraints
1≤T≤10
1≤N≤105
1≤Ai≤2×104
1≤i≤N
Sample Input
2
3
1 2 3
4
1 2 3 3
Sample Output
NO
YES
Explanation
For the first test case, no such index exists. For the second test case,
A[1]+A[2]=A[4]
therefore index 3 satisfies the given conditions.

This solution features Array.prototype.some
The some() method tests whether some element in the array passes the test implemented by the provided function.
with a callback like
function isSherlock(_, i, a) {
function sum(i, n) {
return i < n ? a[i] + sum(i + 1, n) : 0;
}
return sum(0, i) === sum(i + 1, a.length);
}
where just the comparison is returned between the left side and the right side of the index, as well as it's recursive function
function sum(i, n) {
return i < n ? a[i] + sum(i + 1, n) : 0;
}
for counting the array values with the index smaller than the given value.
Alltogether as working example:
function isSherlock(_, i, a) {
function sum(i, n) {
return i < n ? a[i] + sum(i + 1, n) : 0;
}
return sum(0, i) === sum(i + 1, a.length);
}
document.write([1, 2, 3].some(isSherlock) + '<br>');
document.write([1, 2, 3, 3].some(isSherlock) + '<br>');

Related

understanding square brackets in for loop- lesson

I'm currently learning Javascript and would love if someone could help me understand the for loops further. I want to see if someone can give me a bit of an in depth explanation as to how this loop works.
The idea is to return the first non consecutive number in the argument, which as you can see is 6.
Because I'm still learning I wanted to get a detailed yet easy understanding of how this works for example, what's the difference between arr[i]+1 and arr[i+1]?
function firstNonConsec(arr){
for(let i = 0; i < arr.length - 1; i++){
if(arr[i] + 1 !== arr[i+1]){
return arr[i + 1];
}
}
return null
};
console.log(firstNonConsec([1,2,3,4,6,7,8]));
what's the difference between arr[i]+1 and arr[i+1]?
This is not a question about the for loop, but about arrays.
if arr is an array, then you can get the value of one of its items by doing arr[item_number]
arr[i]+1 will therefore give you the value at the place i of the table (e.g. if i equals 0, that would be the first entry in the array), plus one*
arr[i+1] will give you the value at the place i+1 of the table (e.g. if i equals 0, that would be the second entry in the array)
note that +1 can do a lot of things in Javascript, depending on type auto conversion; in your case with only numbers it will increase the number by 1
You can get reference from this workflow of firstNonConsec([1,2,3,4,6,7,8])
i : 0 1 2 3 4 5 6
arr[i] : [ 1, 2, 3, 4, 6, 7, 8 ]
arr[i] + 1 : 2 3 4 5 7 8 9
arr[i+1] : 2 3 4 6 7 8 N
if-statement : T T T F T T F // T: true F: false
return : 2 3 4 N 7 8 N // N: null
arr[i]+1 returns the value of arr's ith array position, then adds one to that value.
arr = [2, 9, 5, 1]
i = 2
arr[2] + 1
Result: 6
So it 1) finds the item in that position 2) adds 1. An array's index starts at 0: arr[n] = [0+n]
You always get the value equal to the result within the bracket.
arr[i+1] would return the i+1th value.
arr = [2, 9, 5, 1]
i = 2
print(arr[i+1]) == print(arr[3])
Result: 1
So this one changes the position itself by 1. This is how a robocaller might complete a call then select the next phone number in a list.
In your case:
if(arr[i] + 1 !== arr[i+1]){
return arr[i + 1];
if the value of the next item in the list is not equal to the previous value + 1, return that value. The function prints you a list of every non consecutive number.
for loop is basically a special type of while loop
var i = 0;
while (i < 10) {
// < code >
i++
}
is the same as
for (let i = 0; i < 10; i++) {
//< code >
}
while loops are used for many different things, so remember them, but for loops are used most. Basically the first "segment" (I'm gonna call whatever's before a semicolon a segment) runs before whatever code you wrote. It usually declares a variable. The second segment runs every time, and stops the loop if the condition isn't met. The third segment also runs every time, but it just runs some code after all the code you wrote is written..
In a lot of languages, including JavaScript, you can also loop through arrays and HashMaps. In JavaScript, you use in and of words.
use for/in for objects
for (let x in < object >) {
//< code >
}
and for each iteration, x is the key of one of the object's properties
to loop through arrays and other iterable objects (you can use for/in, but it's bad practice to), use for/of
for (var x of < array >) {
//< code >
}
this loops through the values of an array, or other such iterable object
the difference between arr[i+1] and arr[i]+1 is that arr[i+1] will access the element after the index specified, but arr[i]+1 will take the value of the index, and return that + 1 (won't change the value, use += to change value). BTW you don't always have to use of for looping thru arrays, you can do it this way which takes i and increases it every time, then takes the value of the index of i.
the answer to your problem:
function firstNonConsec(arr) {
let temp = arr[0];
for (let i = 1; i < arr.length; i++) {
temp = arr[i - 1];
if (temp !== arr[i] - 1) return arr[i];
}
return null;
}
I'm not using for of because you didn't, but comment if you want me to write with for of
Note I used let most of the time because you don't want there to be a random variable that you don't need, and let is limited to the scope of the loop. Also, iterating variables are commonly named i, j, x, y, z and such so you might use i a lot.

replace number with string inside javascript array [closed]

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 4 years ago.
Improve this question
Is it possible to replace a numeric value in a javascript array with a string?
for example:
var a=[1,2,3,4,5]
I need to replace #3 with apple.
Is it even possible?
Use .indexOf(3) to find where 3 is in the array, and then just do a[index] = "apple"; to replace the value. I created a snipped for you below.
var a = [1, 2, 3, 4, 5];
var index = a.indexOf(3);
console.log("Before: " + a);
a[index] = "apple";
console.log("After: " + a);
Aniket G's solution works, but only replaces the first occurrence of a value.
// arr is the array we're acting on
// n is the value we want to replace
// str is the string that we want n replaced with
function replaceNumWithStringInArray(arr, n, str) {
for (let i = 0; i < arr.length; ++i) {
if (arr[i] === n) {
// we found a match, replace the former value (n) with a string (str)
arr[i] = str;
}
}
// we don't have to return anything here, because it modifies the array in place
}
var a = [1,2,3,4,5,3]; // added another 3 to illustrate that it replaces all occurences of n
console.log('before', a);
replaceNumWithStringInArray(a, 3, 'apple');
console.log('after', a);
Yes, of course it's possible! I suggest you read some documentation on javascript arrays to see just how powerful they are.
Basically, javascript arrays are high-level list objects that can be made up of many different data-types. If you would have actually tried what you were curious about before asking about it here, you would have found it to be quite simple.
var a = [1,2,3,4,5];
a[2] = "apple";
Replaces the third element of array a with "apple".
You can iterate over your array and check for the given value. Especially useful if the value occurs multiple times:
function stringifyValue(array, valueToStringify) {
for(let i = 0; i < array.length; i++) {
if(array[i] === valueToStringify){
array[i] = '' + array[i];
}
}
}
Or if you want to update a value at the given index:
const indexWithValue = 3;
array[indexWithValue] = '' + array[indexWithValue];

Javascript create an array with unique combination of values [duplicate]

This question already has answers here:
Find ith permutation in javascript
(3 answers)
Closed 4 years ago.
Despite reading a lot of Q/A about permutation/combination: Finding All Combinations of JavaScript array values + JavaScript - Generating combinations from n arrays with m elements I have not found the right way to get the kind of result I'm looking for.
I got a 10 values array:
var arr = [0,1,2,3,4,5,6,7,8,9];
If I'm right, the number of all possible permuted arrays of unique values (no duplicates):
[5,9,1,8,2,6,7,0,4,3] [4,8,0,2,1,9,7,3,6,5] ...
is 2x3x4x5x6x7x8x9x10 = 3628800
I'm trying to produce a function to dynamically create the 'n' array. For example:
function createArray(0) -> [0,1,2,3,4,5,6,7,8,9]
function createArray(45648) -> [0,1,5,3,2,8,7,9,6] (something like...)
function createArray(3628800) -> [9,8,7,6,5,4,3,2,1,0]
The way I'm figuring to achieve it is:
createArray(1) permutes the 2 last signs (8,9 -> 9,8)
createArray(2->6) permutes the 3 last signs (8,7,9 -> 9,8,7)
createArray(3628800) : all values are permuted (9->0)
Do you think it's possible/easy to do, and if yes how to proceed ?
[EDIT]
Thanks for helpfull answers
function permute(permutation, val) {
var length = permutation.length,
result = [permutation.slice()],
c = new Array(length).fill(0),
i = 1, k, p,
n = 0;
while (i < length) {
if (c[i] < i) {
if (n <= val) {
k = i % 2 && c[i];
p = permutation[i];
permutation[i] = permutation[k];
permutation[k] = p;
++c[i];
i = 1;
if (n == val) {
arr = permutation.slice();
console.log("n="+n+"\n"+arr);
console.log( 'Duration: '+((new Date() - t1)/1000)+'s' );
break;
}
else { n+=1; }
}
} else {
c[i] = 0;
++i;
}
}
}
let t1 = new Date();
permute([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 100000); // <- array requested
console : n=100000 + 0,5,8,1,7,2,3,6,4,9 + Duration: 0.004s
As this question doesn't decribe a specific programming problem but rather a task, and at that a rather complex one, you shoulnd't expect a full solution as an answer, but i'll try describing a possible method of doing this:
As you said, the number of permutations is 2x3x4x...
You could check if n > 2, if true, then check if n > 2x3, if true check if n > 2x3x4. That way you would know how many of the tailing array indexes you want to permutate. Then you would have to make sure to calculate the permutations in a sorted linear way that doesn't generate the same permutation twice. Thats a math problem, the coding itself should be rather easy (something along the lines of switch the position n times at changing indexes).
Not sure if this is the answer you're looking for, but making a unique permutation algorithm sounds rather complex (see for example this answer to another question https://stackoverflow.com/a/11425168/9521900) which links to this wikipedia article https://en.wikipedia.org/wiki/Permutation#Generation_in_lexicographic_order on generating in lexicographic order.
EDIT: From Raj Sharmas comment on your question, this answer on generating permutations seems valuable too:
https://stackoverflow.com/a/37580979/3090583

JS: Finding unpaired elements in an array

I have the following question (this is not school -- just code site practice questions) and I can't see what my solution is missing.
A non-empty array A consisting of N integers is given. The array contains an odd number of elements, and each element of the array can be paired with another element that has the same value, except for one element that is left unpaired.
Assume that:
*N is an odd integer within the range [1..1,000,000];
*each element of array A is an integer within the range [1..1,000,000,000];
*all but one of the values in A occur an even number of times.
EX: A = [9,3,9,3,9,7,9]
Result: 7
The official solution is using the bitwise XOR operator :
function solution(A) {
var agg = 0;
for(var i=0; i<A.length; i++) {
agg ^= A[i];
}
return agg;
}
My first instinct was to keep track of the occurrences of each value in a Map lookup table and returning the key whose only value appeared once.
function solution(A) {
if (A.length < 1) {return 0}
let map = new Map();
let res = A[0]
for (var x = 0; x < A.length; x++) {
if (map.has(A[x])) {
map.set(A[x], map.get(A[x]) + 1)
} else {
map.set(A[x], 1)
}
}
for ([key,value] of map.entries()) {
if (value===1) {
res = key
}
}
return res;
}
I feel like I handled any edge cases but I'm still failing some tests and it's coming back with a 66% correct by the automated scorer.
You could use a Set and check if deletion deletes an item or not. If not, then add the value to the set.
function check(array) {
var s = new Set;
array.forEach(v => s.delete(v) || s.add(v));
return s.values().next().value;
}
console.log(check([9, 3, 9, 7, 3, 9, 9])); // 7
You're not accounting for cases like this:
[ 1, 1, 2, 2, 2 ] => the last 2 is left unpaired
So your condition should be if ( value % 2 ) instead of if ( value === 1 ).
I think also there is not much benefit to using a Map rather than just a plain object.
The official solution works due to the properties of the bitwise XOR (^), namely the fact that a ^ a == 0, a ^ 0 == a, and that the operation is commutative and associative. This means that any two equal elements in the array will cancel each other out to become zero, so all numbers appearing an even amount of times will be removed and only the number with an odd frequency will remain. The solution can be simplified using Array#reduce.
function findOdd(arr) {
return arr.reduce((a,c)=>a ^ c, 0);
}
You need not to make a count of each and traverse again, if you are sure that there will be exactly one number which will occur odd number of times. you can sum the array and do + when odd entry and - when even entry (to dismiss it back) and in the hash (map or object) you can just toggle for subsequent entry of each number.
Here is an example:
let inputArray1 = [10,20,30,10,50,20,20,70,20,70,50, 30,50], //50 -> 3 times
inputArray2 = [10,20,30,20,10], //30 -> 1 time
inputArray3 = [7,7,7,7,3,2,7,2,3,5,7]; //5 -> 1 time
let getOddOccuence = arr => {
let hash = {};
return arr.reduce((sum, n) => sum + ((hash[n] = !hash[n]) ? n : -n), 0);
}
console.log('Input Array 1: ', getOddOccuence(inputArray1));
console.log('Input Array 2: ', getOddOccuence(inputArray2));
console.log('Input Array 3: ', getOddOccuence(inputArray3));
In case the input contains multiple or no numbers having odd number of occurance (if you are not sure there) then you have already the hash (and you can ignore performing sum) and return the keys of hash (where value is true (and not checking with %2 and then consider as truthy or false in case of you have count))
function solution(A) {
let result = 0;
for (let element of A) {
// Apply Bitwise XOR to the current and next element
result ^= element;
}
return result;
}
const unpaired = solution([9, 3, 9, 3, 9, 7, 9]);
console.log(unpaired);
Source: https://gist.github.com/k0ff33/3eb60cfb976dee0a0a969fc9f84ae145

Find out which of four variables contains the largest integer in javascript [closed]

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 years ago.
Improve this question
I have four variables, a, b, c, and d, which each contain a number between 0 and 100, and I don't know the code to determine which one of the four variable contains the largest number.
I need to know the name of the variable that holds the highest value, not the highest value itself!
let a=8, b=1, c=9, d=3
let obj={a,b,c,d},
greatest=Object.values(obj).sort().pop()
key = Object.keys(obj).find( k => obj[k] === greatest )
console.log(key) // Logs "c"
Check out this, worked for me...
Math.max(a, b, c, d);
You can use this code. This also works for the negative integers, in case you have negative values in future. It will be useful for you.
var a=10, b=20, c=15, d = 5;
var array = [a, b, c, d];
var largest=a;
for (i=1; i<=array.length;i++){
if (array[i]>largest) {
largest=array[i];
}
}
console.log(largest);
You can use recursive calls.
Store all the variables in an array. Initial call is by doing findMax(a, a.length-1).
function findMax(a, index) {
if (index > 0) {
return Math.max(a[index], findMax(a, index - 1));
} else {
return a[0];
}
}
var x = findMax([1, 4, 50, 3], 3);
console.log(x);
//In inital call pass array.length -1
Sort the array in descending order and get the first one.
[a, b, c, d].sort(function(num1, num2){return num2-num1;})[0]

Categories

Resources