Missing number in array - javascript

I encountered a problem when I started searching for an element from an array by sorting:
function missingnumber(numbers) {
var missing = -1;
var sorted = numbers.sort(function(a, b) {
a - b
})
for (var i = sorted[0]; i < numbers.length - 1; i++) {
if (numbers(i) === -1) {
missing = i
}
}
return missing;
}
var numbers = [2,4,10,7,6,11,8,9,12]//5 without sorting
var numbers = [11,19,18,17,15]//i am getting -1 with sorting
console.log(missing - number(numbers))
I'm trying to get the the missing number by sorting and it gives me missing number -1. Where is hole in my logic?

There are numerous syntax and logic errors in your code; here are a few:
if (numbers(i) === -1) { has a syntax error (you probably mean numbers[i] as an array index) and a logic error (comparing an array index against -1 won't tell you whether it's the missing number or not, unless the missing number happens to be -1).
console.log(missing - number(numbers)) is where you're (rightfully, at least somewhere in the code) trying to calculate the missing number by subtraction. Unfortunately, this isn't syntactically or logically correct.
var i = sorted[0] should be simply var i = 0 rather than the value of the element at index 0 in sorted.
Here's a working version; if there are multiple missing numbers, it returns the first one, and it's assumed that the step size is always 1 in the sequence:
const missing = nums => {
nums.sort((a, b) => a - b);
for (var i = 1; i < nums.length; i++) {
if (nums[i] - nums[i-1] !== 1) {
return nums[i-1] + 1;
}
}
return -1;
};
console.log(missing([2,4,10,7,6,11,8,9,12]));
console.log(missing([11,19,18,17,15]));

Codility missing number in array solution 100% performance
func missingNumber( array: [Int]) -> Int {
let length = array.count+1
let totalSum = length * (length+1)/2
let actualSum = array.reduce(0, { x, y in
x + y
})
return totalSum - actualSum
}
Another solutions is
public func solution(_ array : inout [Int]) -> Int {
// write your code in Swift 4.2.1 (Linux)
var dict: [Int: Int] = [:]
array.map{
dict[$0] = $0
}
var missingNumber = 1
for (_, _) in dict {
if dict[missingNumber] == nil {
return missingNumber
}
missingNumber = missingNumber+1
}
return missingNumber
}

Related

Returning NULL from an empty array

I'm currently learning basic web development with JavaScript, taking an online course which corrects code using a bot. I'm trying to implement a function which calculates the average value of an array.
let numbers = [1,2,3]
function average(array){
var total = 0;
var count = 0;
array.forEach(function(item){
total += item;
count++;
})
if (numbers.length > 0){
return total / count;
} else if (numbers = ([])) {
return null
}
}
The code works fine, in practice, but I get an error returned saying 1) defines average such that average([]) returns null, as in if an empty array is sent in, average([]) is supposed to return null I can't figure out how to fix it...
I would make it way more simpler without the counter. You have the total in the length of the array.
I also added a version using array.reduce().
And please, don't use numbers variable inside the function. It makes no sense here. You pass the variable to the function and inside the function you should use the received variable or it will behave incorrectly. Inside the function numbers is called "arr", so use arr all the way.
function average(arr){
if (arr.length === 0) return null;
let total = 0;
arr.forEach(function(item){
total += item;
})
return total / arr.length;
}
// using array.reduce() which makes more sense here
function average2(arr){
if (arr.length === 0) return null;
const total = arr.reduce(function(prev,next){
return prev + next;
});
return total / arr.length;
}
console.log(average([]));
console.log(average([1,2,3]));
console.log(average2([]));
console.log(average2([1,2,3]));
You don't need to test for []. If the array has a length of zero, then it's empty:
let numbers = [1, 2, 3]
function average(array) {
var total = 0;
var count = 0;
// No need to iterate over array if it's empty
if (array.length > 0) {
array.forEach(function(item) {
total += item;
count++;
})
return total / count;
} else {
// If we got here, array.length === 0
return null
}
}
console.log(average(numbers));
numbers = [];
console.log(average(numbers));
In the second case, numbers = ([]) assigns the numbers to [] (which always return true) instead of comparing it. The right way would be using == as follows:
let numbers = [1,2,3]
function average(array){
var total = 0;
var count = 0;
array.forEach(function(item){
total += item;
count++;
})
if (array.length > 0){
return total / count;
} else if (array.length == 0) {
return null
}
}
console.log(average(numbers));
numbers = [];
console.log(average(numbers));
EDIT:
As mentioned in the comment, there is another mistake, where you are using numbers instead of array in the function.
The reason, why your test case fails, is that you define numbers at the top and then reuse it within the function. That way it always returns the same. You should use array within the function instead.
Here a short version of your script to see, what js is capable of.
function average(array){
let total = array.reduce((acc, value) => acc + value, 0);
return array.length > 0 ? total / array.length : null;
}
console.log(average([1,2,3]))
console.log(average([]))
You are using numbers instead of array inside average() method.
It could be possible that your array can be undefined. Try using this
function average(array) {
if (typeof array == "object" && array.length > 0) {
var total = 0;
var count = 0;
array.forEach(function(item) {
total += item;
count++;
});
return total / count;
} else {
return null;
}
}

How do I push arrays to array inside a recursive javascript function so that I can use it when it's done?

First question here (I think). Please let me know if additional information is needed in order for you guys to help me out.
So I'm trying to implement an algorithm in javascript that uses a recursive funtion.
The function is copied from Implementing Heap Algorithm of Permutation in JavaScript and looks like this:
let swap = function(array, index1, index2) {
let temp = array[index1]
array[index1] = array[index2]
array[index2] = temp
return array
}
let permutationHeap = (array, result, n) => {
n = n || array.length // set n default to array.length
if (n === 1) {
result(array)
} else {
for (let i = 1; i <= n; i++) {
permutationHeap(array, result, n - 1)
if (n % 2) {
swap(array, 0, n - 1) // when length is odd so n % 2 is 1, select the first number, then the second number, then the third number. . . to be swapped with the last number
} else {
swap(array, i - 1, n - 1) // when length is even so n % 2 is 0, always select the first number with the last number
}
}
}
}
let output = function(input) {
console.log(output)
}
permutationHeap([1,2,3,4,5], output)
The console.log in the output function (callback?) gives me the right output. If I move that console.log below the if statement in permutationHeap-function, I get the right output as well (console.log(array), in that case though).
What I want to do is to store every output as an array, inside an array that I can use later on down the road. I'm guessing that I'm struggling with Javascript 101 here. Dealing with asynchronus thinking. But can't for the life of me figure out how to get that array of arrays!
If I declare an empty array outside the permutationHeap-function and
.push(array) it only stores [1,2,3,4,5]. Same deal if I do the same
thing inside the output-function.
I've also tried passing in an empty array to the
permutationHeap-function and push that way. Still no luck.
Anyone who's willing to shine some light over a probably super nooby question? :) Much appriciated!
I actually broke the algorithm in my previous answer, because by duplicating the array ever iteration I broke the part of the algorithm that relies on the array changing as it goes.
I've made an answer that uses the code that you had originally more effectively:
var swap = function(array, index1, index2) {
var temp = array[index1];
array[index1] = array[index2];
array[index2] = temp;
return array;
};
var permutationHeap = function(array, result, n) {
n = n || array.length; // set n default to array.length
if (n === 1) {
result(array);
} else {
for (var i = 1; i <= n; i++) {
permutationHeap(array, result, n - 1);
if (n % 2) {
swap(array, 0, n - 1); // when length is odd so n % 2 is 1, select the first number, then the second number, then the third number. . . to be swapped with the last number
} else {
swap(array, i - 1, n - 1); // when length is even so n % 2 is 0, always select the first number with the last number
}
}
}
};
function getPermutations(array) {
var results = [];
var output = function(res) {
results.push(res.slice(0));
}
permutationHeap(array, output);
return results;
}
var permutations = getPermutations([1,2,3]);
console.log(permutations);
I think I've managed to fix your code by using generators and yield. I can't exactly explain it though...
var swap = function(array, index1, index2) {
let temp = array[index1]
array[index1] = array[index2]
array[index2] = temp
return array
}
var permutationHeap = function*(array, result, n) {
n = n || array.length // set n default to array.length
if (n === 1) {
yield (array.slice(0))
} else {
for (let i = 1; i <= n; i++) {
yield* permutationHeap(array, result, n - 1)
if (n % 2) {
swap(array, 0, n - 1) // when length is odd so n % 2 is 1, select the first number, then the second number, then the third number. . . to be swapped with the last number
} else {
swap(array, i - 1, n - 1) // when length is even so n % 2 is 0, always select the first number with the last number
}
}
}
}
var x = permutationHeap([1,2,3,4,5])
var results = Array.from(x);
console.log(results);

How do you most efficiently sort an integer variable? [duplicate]

I've seen versions of this question for other languages, but not for JS.
Is it possible to do this recursively in one function?
I understand that I need to take the first element in the string, and then append it to each solution to the recursion on the remainder of the string.
So logically, I understand how the recursion needs to go. I just don't understand how to append the first char onto each of the recursive solutions
var myString = "xyz";
function printPermut(inputString){
var outputString;
if(inputString.length === 0){
return inputString;
}
if(inputString.length === 1){
return inputString;
}
else{
for(int i = 0; i<inputString.length(); i++){
//something here like:
//outputString = outputString.concat(printPermut(inputString.slice(1))??
//maybe store each unique permutation to an array or something?
}
}
}
Let's write a function that returns all permutations of a string as an array. As you don't want any global variables, returning the permutations is crucial.
function permut(string) {
if (string.length < 2) return string; // This is our break condition
var permutations = []; // This array will hold our permutations
for (var i = 0; i < string.length; i++) {
var char = string[i];
// Cause we don't want any duplicates:
if (string.indexOf(char) != i) // if char was used already
continue; // skip it this time
var remainingString = string.slice(0, i) + string.slice(i + 1, string.length); //Note: you can concat Strings via '+' in JS
for (var subPermutation of permut(remainingString))
permutations.push(char + subPermutation)
}
return permutations;
}
To print them, just iterate over the array afterwards:
var myString = "xyz";
permutations = permut(myString);
for (permutation of permutations)
print(permutation) //Use the output method of your choice
Hope I could help you with your question.
The problem of permutations has been studied to death. Heap's algorithm is one well-known solution. Here is a version in JS, using a generator:
function *permute(a, n = a.length) {
if (n <= 1) yield a.slice();
else for (let i = 0; i < n; i++) {
yield *permute(a, n - 1);
const j = n % 2 ? 0 : i;
[a[n-1], a[j]] = [a[j], a[n-1]];
}
}
console.log(Array.from(permute("abcabad".split('')))
.map(perm => perm.join(''))
.filter((el, idx, self) => (self.indexOf(el) === idx)));
permute is designed to take and generate arrays, not strings, so we split the string into characters before calling it, and paste the characters back into strings before printing out the results.
Use Recursive Function to iterate through the string
function getPermutations(string) {
var results = [];
if (string.length === 1)
{
results.push(string);
return results;
}
for (var i = 0; i < string.length; i++)
{
var firstChar = string[i];
var otherChar = string.substring(0, i) + string.substring(i + 1);
var otherPermutations = getPermutations(otherChar);
for (var j = 0; j < otherPermutations.length; j++) {
results.push(firstChar + otherPermutations[j]);
}
}
return results;
}
var permutation = getPermutations('YES').filter((el, idx, self) => (self.indexOf(el) === idx));
console.log("Total permutation: "+permutation.length);
console.log(permutation);
Problem classification: You can look at this problem as an exploration problem, i.e., given a set of input characters explore the different ways you can arrange them.
Solution: Backtracking algorithm excels in solving exploratory problems, although it comes with high time complexity. To demonstrate a solution, imagine how you would solve this problem by hand for a small set of input characters: [a, b, c].
Here are the steps:
Take the left most character. This is the character at index 0 and swap it with target right character at index 0, i.e. with itself. This is because [a, b, c] is a valid permutation on its own therefore we want to keep it. Swapping characters normally requires two pointers which point to each of the characters. So let's say we will have a left and right pointer.
With the same left most character (at index 0) do the swapping with target right character at index 0 + 1 = 1, i.e. move the target right pointer with 1 step further. This will give you the output: [b, a, c]
With the same left most character (at index 0) do the swapping with the next next target right character (i.e. index 0 + 1 + 1 = 2). This will give you the output: [c, b, a]
Ok, now we need to stop as there are no more target right characters to be swapped with the left most character. So our right pointer needs to stay less than the max index in the input. Moving the right pointer with a step at a time we can do with a for loop which starts from the left index and ends with the input length - 1.
Now you need to do exact same steps from above but move the left pointer so that it points to the next left most character. However, keeping the input from step 2 and 3. Another way to imagine this situation is to say: 'Hey, I am done with the left most character. Now I do not want to work with it anymore but I would love to continue with the second left most from the results I have so far.'
When do we stop? When the left pointer has reached the length of the input string - 1, 'cause there is no more characters after this index. In recursive algorithms (such as the backtracking), the case where you need to stop is called base case. In our example the base case is: left === input.length - 1.
Here is a graphical visualisation:
left index| Input String:
-------------------------------------------------------------------------------
left = 0 | in=[a, b, c]
(swap in[0] with in[0]) (swap in[0] with in[1]) (swap in[0] with in[2])
left = 1 | in=[a, b, c] in=[b, a, c] in=[c, b, a]
(swap in[1] with in[1]) (swap in[1] with in[2]) (swap in[1] with in[1])(swap in[1] with in[2]) (swap in[1] with in[1])(swap in[1] with in[2])
left = 2 | [a, b, c] [a, c, b] [b, a, c] [b, c, a] [c, b, a] [c, a, b]
Summary:
To move the left pointer to the right we will use recursive increment
To move the right pointer to the right we will use a for loop, however we need to start always from the left pointer or else we will explore things we have already explored.
Backtracking:
A pseudo-code for backtracking algorithm takes the form of:
fun(input)
if(base_case_check(input)) {
//do final step
} else {
//choose
fun(reduce(input)) //explore
//un-choose
}
Our solution:
function permutate(string) {
if(!string || string.length === 0)
return new Set(['']);
let left = 0;
let result = new Set();
permutationHelper(string, result, left);
return result;
}
function permutationHelper(string, result, left) {
if(left === string.length-1) {
//base case
result.add(string);
} else {
//recursive case
for(let right=left; right < string.length; right++) {
string = swap(string, left, right); //choose
permutationHelper(string, result, left+1); // explore
string = swap(string, left, right); //unchoose
}
}
}
function swap(string, left, right) {
let tmpString = string.split('');
let tmp = tmpString[left];
tmpString[left] = tmpString[right];
tmpString[right] = tmp;
return tmpString.join('');
}
/* End of solution */
/* Tests */
let input = 'abc';
let result = permutate(input);
let expected = new Set(['abc', 'acb', 'bac', 'bca', 'cab', 'cba']);
if(setsEquality(result, expected)) {
console.log('Congrats, you generated all permuations');
} else {
console.log('Sorry, not all permuations are generated');
}
function setsEquality(actualResult, expectedResult) {
if (actualResult.size !== expectedResult.size) {
return false;
}
for (let permutation of actualResult) {
if (!expectedResult.has(permutation)) return false;
}
return true;
}
function assert(condition, desc) {
if (condition) {
console.log(`${desc} ... PASS`);
} else {
console.log(`${desc} ... FAIL`);
}
}
Summary & Time Complexity:
We make our choice by swapping characters in the existing input string
We explore what is left to be explored once we increment our left index with 1. This in fact means that we are reducing our input set for all subsequent recursions with 1. Therefore the work we need to do is: Nx(N-1)x(N-2)x(N-3)x...x1 = N!. However, as we needed a for loop to explore among the input we have, the total time complexity would be: 0(N*N!)
We revert our choice by swapping characters back in the modified input string
permutation=(str,prefix)=>{
if(str.length==0){
console.log(prefix);
}
else{
for(let i=0;i<str.length;i++){
let rem = str.substring(0,i)+str.substring(i+1);
permutation(rem,prefix+str[i]);
}
}
}
let str="ABC";
permutation(str,"");
Semi-Off topic:
random permutation of a given string is as simple as rndperm:
i = document.getElementById("word");
b = document.getElementById("butt");
rndperm = (z) => {
return z.split("").sort(() => ((Math.random() * 3) >> 0) - 1).join("")
}
function scramble() {
i.value = rndperm(i.value);
}
var z;
function sci() {
if (z != undefined) {
clearInterval(z);
b.innerText = "Scramble";
z=undefined;
} else {
z = setInterval(scramble, 100);
b.innerText = "Running...";
}
}
<center><input id="word" value="HelloWorld"></input><button id="butt" onclick=sci()>Scramble</button></center>
I had same question by my interviewer last day but I was not get the correct logic then I came to stackoverflow and I get here but now I have my solution and want to share with all
const str_Permutations = (str,ar = []) => {
str = `${str}`; // ensure type **String**
if(ar.indexOf(str)>-1 || str.length !== (ar.strlen || str.length)) return false; // Checking if value is alreay there or(||) on recursive call string length should not be provided string
ar.strlen = ar.strlen || str.length; // Setting str length of provided value(string)
ar.push(str); // Pushing to array
for(let i = 0; i<str.length;i++){
str_Permutations(str[i] + str.split('').filter(v=>v!==str[i]).join(''),ar);
}
return Array.from(ar); // Removing *strlen* from main result and return **Result** as array
}
str_Permutations("ABC")
//Result: (6) ["ABC", "BAC", "CBA", "BCA", "ACB", "CAB"]
There is used reference feature of Array to hold the values in same Array by passing. I hope you got my point!!!!
const permut = (str) => {
if (str.length <= 2) return str.length === 2 ? [str, str[1] + str[0]] : [str];
return str
.split("")
.reduce(
(acc, letter, i) =>
acc.concat(
permut(str.slice(0, i) + str.slice(i + 1)).map((val) => letter + val)
),
[]
);
};
found here
This does the job, recursively
function printPermutations(str, res='') {
if (!str.length){
console.log(res);
}
for (let i = 0; i < str.length; i++) {
let remStr = str.substr(0, i) + str.substr(i + 1);
printPermutations(remStr, res + str.substr(i, 1));
}
}
printPermutations("abc")
// result
// abc, acb, bac, bca, cab, cba
Simple and readable approach but only limited to 3 chars
const stringPermutation = (str) => {
let permutations = [];
for (let i in str) {
for (let j in str) {
for (let k in str) {
if (str[i] !== str[j] && str[j] !== str[k] && str[i] !== str[k]) {
permutations.push(str[i] + str[j] + str[k]);
}
}
}
}
return permutations;
};
console.log(stringPermutation("abc"));
var str = "abcdefgh";
for(let i = 0; i<str.length; i++){
for(let j = i; j<=str.length; j++){
if(i != j){
var out = str.slice(i,j);
console.log(out);
}
}
}

Multiplicative Persistence Codewars Challenge

I've been working on a kata from Codewars, the challenge is to write a function, persistence, that takes in a positive parameter num and returns its multiplicative persistence, which is the number of times you must multiply the digits in num until you reach a single digit.
Example:
persistence(39) === 3 // because 3*9 = 27, 2*7 = 14, 1*4=4
// and 4 has only one digit
persistence(999) === 4 // because 9*9*9 = 729, 7*2*9 = 126,
// 1*2*6 = 12, and finally 1*2 = 2
persistence(4) === 0 // because 4 is already a one-digit number
While trying to figure this out I came across a solution online (shown below) and after trying to understand its logic, I couldn't see why the code didn't work
var count = 0;
function persistence(num) {
if (num.toString().length === 1) {
return count;
}
count++;
var mult = 1;
var splitStr = num.toString().split("");
for (var i = 0; i <= splitStr; i++) {
mult *= parseFloat(splitStr[i])
}
return persistence(parseFloat(mult));
}
The output for any single digit number will be 0 which is correct however for any number that is multiple digits, the persistence always logs as 1 and I can't seem to figure out why, any help would be greatly appreciated.
The posted code has quite a few problems.
for (var i = 0; i <= splitStr; i++) {
But splitStr is an array, not a number; i <= splitStr doesn't make sense. It should check against splitStr.length instead of splitStr.
Another problem is that it should use i <, not i <=, else the final splitStr[i] will be undefined.
Another problem is that the count variable is global, so more than one call of persistence will result in inaccurate results. There's no need for a count variable at all. To fix it:
function persistence(num) {
if (num.toString().length === 1) {
return 0;
}
var mult = 1;
var splitStr = num.toString().split("");
for (var i = 0; i < splitStr.length; i++) {
mult *= parseFloat(splitStr[i])
}
return 1 + persistence(parseFloat(mult));
}
console.log(
persistence(999),
persistence(39),
persistence(4)
);
Or, one could avoid the for loop entirely, and use more appropriate array methods:
function persistence(num) {
const str = num.toString();
if (str.length === 1) {
return 0;
}
const nextNum = str.split('').reduce((a, b) => a * b, 1);
return 1 + persistence(nextNum);
}
console.log(
persistence(999),
persistence(39),
persistence(4)
);
or we can use while loop with reduce array method
const persistence=(num)=>{
let splitNumArr=num.toString().split('')
let newList
let count=0
while(splitNumArr.length>1){
newList=splitNumArr.reduce((acc,curr)=>{
return acc*=curr
})
splitNumArr=newList.toString().split('')
count++
}
return count
}
console.log(persistence(39))===3
console.log(persistence(999))===4
console.log(persistence(9))===0

Overlapping loops inside functions

In code wars, i am training on a project of multiplicative inverse. The goal is, for example -- if "39" is the input the output should be "4" [39 = 3*9 ==> 27 = 2*7 => 14 = 1*4 ==> (4)].
i wrote some code which just multiplies the input for only first level(39 ==> 27).
My code until now,
function persistence(num) {
var digits = new Array();
digits = num.toString().split("").map(Number);
var res = 1;
for (i = 0; i < digits.length; i++) { res = res * digits[i]; }
return res;
console.log(persistence(digits));
}
i am just learning javascript and i am stuck here. I need to loop this process till i get a single digit number.
CAN SOMEONE PLEASE HELP ME?
Sorry if my question is not clear...
Array methods are your friend. In this case, use map and reduce:
function multiplyDigits(num) {
if (num < 10) return num;
console.log(num);
const multiplied = String(num)
.split('')
.map(Number)
.reduce((a, n) => a * n, 1);
return multiplyDigits(multiplied);
}
console.log(multiplyDigits(39));
Aside from formatting this is very similar to your code. I commented the only two changes:
function persistence(num) {
var digits = new Array();
digits = num.toString().split("").map(Number);
// 1) Added this if statement to return the result
// immediately if there is only one digit.
if ( digits.length === 1 )
return digits[0];
var res = 1;
for (i = 0; i < digits.length; i++)
res = res * digits[i];
// 2) Changed from `return res;` so that the function you wrote
// is called again on the result (if there were more than one digit).
return persistence(res);
}
console.log(persistence('39'));
For a bit shorter of a solution you could use:
function persistence(num) {
return num < 10
? num
: persistence( (num+'').split('').reduce( (a,b) => a*b ) );
}
console.log(persistence('39'));

Categories

Resources