previously i've do some technical test with hackerrank. For the simple testing i need to make two different array so i can check it the difference both of them. the first array will be unsorted, and the second will be sorted.
Here's my code:
function dataSort(thedata) {
// Write your code here
var unsorted = thedata
var sorted = thedata
console.log("not sorted", unsorted) // first log
for(let i = 0; i < sorted.length; i++)
{
for(let j = i; j < sorted.length; j++)
{
if(sorted[i] > sorted[j])
{
let temp = sorted[i]
sorted[i] = sorted[j]
sorted[j] = temp
}
}
}
console.log("sorted",sorted) // second log
}
dataSort([1,3,4,2,1])
above code given the result below
not sorted [ 1, 3, 4, 2, 1 ]
sorted [ 1, 1, 2, 3, 4 ]
Okay, that's seems have no problem. but when i move the first console after the bubble sort near with second console, the data also sorted
function dataSort(thedata) {
// Write your code here
var unsorted = thedata
var sorted = thedata
for(let i = 0; i < sorted.length; i++)
{
for(let j = i; j < sorted.length; j++)
{
if(sorted[i] > sorted[j])
{
let temp = sorted[i]
sorted[i] = sorted[j]
sorted[j] = temp
}
}
}
console.log("not sorted", unsorted) // first log
console.log("sorted",sorted) // second log
}
dataSort([1,3,4,2,1])
result
not sorted [ 1, 1, 2, 3, 4 ]
sorted [ 1, 1, 2, 3, 4 ]
Can you tell me what happened?
GrafiCode gave you the correct explanation about why this happens.
Here is a possible solution:
function dataSort(thedata) {
// Write your code here
var unsorted = new Array(...thedata)
var sorted = new Array(...thedata)
for(let i = 0; i < sorted.length; i++)
{
for(let j = i; j < sorted.length; j++)
{
if(sorted[i] > sorted[j])
{
let temp = sorted[i]
sorted[i] = sorted[j]
sorted[j] = temp
}
}
}
console.log("not sorted", unsorted) // first log
console.log("sorted",sorted) // second log
}
dataSort([1,3,4,2,1])
Related
I wonder if there's an easy to implement equivalent to python's array.pop() which returns the deleted element while deleting it from the array in parallel in javascript.
let nums = [2, 1, 3, 4, 5, 6];
function sortArray(nums) {
let arr = new Array();
let smallest_index;
for (let j = 0; j < nums.length; j++) {
smallest_index = find_smallest(nums);
console.log("smallest", smallest_index);
arr.push(nums.splice(smallest_index, 1).join(""));
}
return arr;
}
function find_smallest(arr) {
let smallest = arr[0];
let smallest_index = 0;
for (let i = 1; i < arr.length; i++) {
if (arr[i] < smallest) {
// console.log("this");
smallest = arr[i];
smallest_index = i;
}
}
return smallest_index;
}
it seems that if I replace javascript's (nums.splice(smallest_index, 1).join()) with python's (arr.append(nums.pop(smallest_index)) I would get a perfectly sorted array. is there a similar straightforward solution in javascript as well ?
OK, you use splice. Here's an example of the implementation below:
Array.prototype.pythonPop = function (index) {
return this.splice(index, 1)[0];
}
Now, I found the issue, you'll love the answer. So you were using num.length but your methods were augmenting the length of num array. Which is why your answer had only half the needed numbers. See code below. I cached the length prop of nums array
let nums = [2, 1, 3, 4, 5, 6];
function sortArray(nums) {
let arr = new Array();
let smallest_index;
console.log(nums)
for (let j = 0, length = nums.length; j < length; j++) {
smallest_index = find_smallest(nums);
console.log("smallest", smallest_index);
console.log(nums)
arr[j] = nums.splice(smallest_index, 1).join("");
}
return arr;
}
function find_smallest(arr) {
let smallest = arr[0];
let smallest_index = 0;
for (let i = 1; i < arr.length; i++) {
if (arr[i] < smallest) {
// console.log("this");
smallest = arr[i];
smallest_index = i;
}
}
return smallest_index;
}
console.log(sortArray(nums))
I'm trying to implement selection sort with javascript, but it seems that either i'm missing something or doing something absolutely wrong.
as you may understand from a first look, sortArray() seems to return arr with only one value 5 while it should return an array with as such [5,5,5,5,5,5].
worth mentioning is that when I comment line smallest_index = find_smallest(nums)
I get the supposed input; [5,5,5,5,5,5].
let nums = [2, 1, 3, 4, 5, 6];
function sortArray(nums) {
let arr = new Array();
let smallest_index;
for (i = 0; i < nums.length; i++) {
smallest_index = find_smallest(nums);
arr.push("5");
}
return arr;
}
function find_smallest(arr) {
let smallest = arr[0];
let smallest_index = 0;
for (i = 1; i < arr.length; i++) {
if (arr[i] < smallest) {
console.log("this");
smallest = arr[i];
smallest_index = i;
}
}
return smallest_index;
}
console.log(sortArray(nums));
any help or thoughts as to what i may be not be realizing or doing ?
The problem is within your for loops. More specifically, you need to declare the variable i before using it. If you alter your code like the below snippet, then your code works just as expected:
let nums = [2, 1, 3, 4, 5, 6];
function sortArray(nums) {
let arr = new Array();
let smallest_index;
for (let i = 0; i < nums.length; i++) {
smallest_index = find_smallest(nums);
arr.push("5");
}
return arr;
}
function find_smallest(arr) {
let smallest = arr[0];
let smallest_index = 0;
for (let i = 1; i < arr.length; i++) {
if (arr[i] < smallest) {
console.log("this");
smallest = arr[i];
smallest_index = i;
}
}
return smallest_index;
}
console.log(sortArray(nums));
The only difference is using
for (let i = 1; ...
instead of
for (i = 1; ...
I'm trying to create this script: https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/seek-and-destroy
After the comment "Verify and delete" is where I have the problem.
I try to check all the elements form the array 'theCheck' with the elements from 'destroyers' and if the elements dont match then the script will push that value to the output array.
But it pushes every element regardless.
Expected output value: [1,1]
Current output value value: [1,2,3,1,2,3]
function destroyer(arr) {
let theCheck = [];
let destroyers = [];
let output = [];
for (let i = 1; i < arguments.length; i++) {
destroyers.push(arguments[i]);
}
for (let i = 0; i < arguments[0].length; i++) {
theCheck.push(arguments[0][i])
}
//Verify and delete
var j = 0
for (let i = 0; i < theCheck.length; i++) {
for (j = 0; j < destroyers.length; j++) {
if (theCheck[i] !== destroyers[j]) {
output.push(theCheck[i])
break;
}
}
}
console.log(theCheck)
console.log(destroyers)
console.log(output)
return arr;
}
destroyer([1, 2, 3, 1, 2, 3], 2, 3);
With the current code you're looping through the destroyers and anytime you find a destroyer that doesn't match the item you're checking you're adding it to the output. But because you've got two items in the destroyers array it is guaranteed that one of the two is not going to match the particular item that you're checking.
Below is a version where we work out whether any of the destroyers are found to match the item that we're checking, and only if it doesn't we're adding it to the output:
function destroyer(arr) {
let theCheck = [];
let destroyers = [];
let output = [];
for (let i = 1; i < arguments.length; i++) {
destroyers.push(arguments[i]);
}
for (let i = 0; i < arguments[0].length; i++) {
theCheck.push(arguments[0][i])
}
//Verify and delete
var j = 0
for (let i = 0; i < theCheck.length; i++) {
let found = false;
for (j = 0; j < destroyers.length; j++) {
if (theCheck[i] === destroyers[j]) {
found = true;
}
}
if(!found) output.push(theCheck[i]);
}
console.log(theCheck)
console.log(destroyers)
console.log(output)
return arr;
}
destroyer([1, 2, 3, 1, 2, 3], 2, 3);
You could use the includes function to tidy this up a little:
function destroyer(arr) {
let theCheck = [];
let destroyers = [];
let output = [];
for (let i = 1; i < arguments.length; i++) {
destroyers.push(arguments[i]);
}
for (let i = 0; i < arguments[0].length; i++) {
theCheck.push(arguments[0][i])
}
//Verify and delete
var j = 0
for (let i = 0; i < theCheck.length; i++) {
if(!destroyers.includes(theCheck[i]))
output.push(theCheck[i]);
}
console.log(theCheck)
console.log(destroyers)
console.log(output)
return arr;
}
destroyer([1, 2, 3, 1, 2, 3], 2, 3);
function destroyer(input, ...arr) {
return input.filter(element => !arr.includes(element));
}
console.log(destroyer([1, 2, 3, 1, 2, 3], 2, 3));
I've been trying to implement a function where given with two arrays,
array1's elements is used as conditions to filter out elements in array2.
For instance:
array1= [apple, grapes, oranges]
array2= [potato, pears, grapes, berries, apples, oranges]
After feeding into a function, array2 should have elements as such:
filter_twoArrays(array1,array2)
array2= [grapes, apples, oranges]
I've tried the following code, using for loops and array.splice(), but the problem I am seeing is that when I use the splice method, it seems that it changes the lengths of array2 in the for loop:
function filter_twoArrays(filter,result){
for(i=0; i< filter.length; i++){
for(j=0; j< result.length; j++){
if(filter[i] !== result[j]){
result.splice(j,1)
}
}
}
Any inputs will be greatly appreciated on how to refine the filter function
cheers!
You can use filter as follow
var array1 = ['apples', 'grapes', 'oranges', 'banana'],
array2 = ['potato', 'pears', 'grapes', 'berries', 'apples', 'oranges'];
var intersection = array1.filter(function(e) {
return array2.indexOf(e) > -1;
});
console.log(intersection);
You can also add this method on Array prototype and call it directly on array
Array.prototype.intersection = function(arr) {
return this.filter(function(e) {
return arr.indexOf(e) > -1;
});
};
var array1 = ['apples', 'grapes', 'oranges', 'banana'],
array2 = ['potato', 'pears', 'grapes', 'berries', 'apples', 'oranges'];
var intersection = array1.intersection(array2);
console.log(intersection);
You can use some, like this:
let newArray = array2.filter(
(array22) => !array1.some((array11) => array11.id === array22._id));
Hi this is a porting of the function array_intersect php. Should be good for you
http://phpjs.org/functions/array_intersect/
function array_intersect(arr1) {
// discuss at: http://phpjs.org/functions/array_intersect/
// original by: Brett Zamir (http://brett-zamir.me)
// note: These only output associative arrays (would need to be
// note: all numeric and counting from zero to be numeric)
// example 1: $array1 = {'a' : 'green', 0:'red', 1: 'blue'};
// example 1: $array2 = {'b' : 'green', 0:'yellow', 1:'red'};
// example 1: $array3 = ['green', 'red'];
// example 1: $result = array_intersect($array1, $array2, $array3);
// returns 1: {0: 'red', a: 'green'}
var retArr = {},
argl = arguments.length,
arglm1 = argl - 1,
k1 = '',
arr = {},
i = 0,
k = '';
arr1keys: for (k1 in arr1) {
arrs: for (i = 1; i < argl; i++) {
arr = arguments[i];
for (k in arr) {
if (arr[k] === arr1[k1]) {
if (i === arglm1) {
retArr[k1] = arr1[k1];
}
// If the innermost loop always leads at least once to an equal value, continue the loop until done
continue arrs;
}
}
// If it reaches here, it wasn't found in at least one array, so try next value
continue arr1keys;
}
}
return retArr;
}
You can use
const arr1 = [1, 2, 3];
const arr2 = [2, 3];
arr1.filter(e => arr2.indexOf(e) > -1 ? false : true); // [1]
Came here some week back to find a solution to a problem like this but its a pity I couldn't get what I wanted, but now I figured it out in a more simple way. using the arrow function, .filter() method and .includes() method.
Declare an arrow function that takes in two arguments:
const filterTwoArrays = (string1, string2) => string1.filter(item => string2.includes(item));
console.log(filterTwoArrays(array1, array2)).
Here is one simple way based on your code
function array_filter(filter, result) {
var filterLen = filter.length;
var resultLen = result.length;
for (i = 0; i < resultLen; i++) {
for (j = 0; j < filterLen; j++) {
if (!contains(filter, result[i]))
result.splice(i, 1);
}
}
}
//Return boolean depending if array 'a' contains item 'obj'
function contains(array, value) {
for (var i = 0; i < array.length; i++) {
if (array[i] == value) {
return true;
}
}
return false;
}
Since you have tagged javascript here is the solution.
function f1(x, y) {
var t = y.slice(0);
var r = [];
for (var i = 0; i < x.length; i++) {
for (var j = 0; j < y.length; j++) {
if (x[i] === y[j]) {
[].push.apply(r, t.splice(j, 1));
}
}
}
console.log(r)
y.length = 0;
[].push.apply(y, r);
}
Mark the items which are to be filtered out via delete result[index] manipulate them as needed.
JavaScript
window.onload = runs;
function runs() {
var array1 = ["apples", "grapes", "oranges"];
var array2 = ["potato", "pears", "grapes", "berries", "apples", "oranges"];
var result = filter_twoArrays(array1, array2);
function filter_twoArrays(filter, result) {
var i = 0,
j = 0;
for (i = 0; i < result.length; i++) {
var FLAG = 0;
for (j = 0; j < filter.length; j++) {
if (filter[j] == result[i]) {
FLAG = 1;
}
}
if (FLAG == 0) delete result[i];
}
return result;
}
var body = document.getElementsByTagName("body")[0];
var i = 0;
for (i = 0; i < result.length; i++) {
if (result[i] !== undefined)
body.innerHTML = body.innerHTML + result[i] + " ";
}
}
const func = array1.filter(item => array2.includes(item));
So, I'm working on a javascript application that can solve any size matrix. I'm running into a SUPER weird problem, where my main array only has the value of 0 after a certain point. The input should be a data set, like this
1, 8
2, 10
3, 13
4, 17
5, 22
But I'm having trouble with it. When I run the code, the console.log prints out a pretty derpy array
[[1, 1, 1, 8],
[0, 0, 0, 0],
[0, 0, 0, 0]]
It gets even weirder. If I move the console.log to before I call the rref function, I get the same thing.
Anybody ever seen this before? Anyone know how to fix it? Thanks!
//Matrix object
var matrix = {
startingDataSet: [],
degree: 0,
M: []
}
//splits up user input into a more readable format
function getDataFromString(data) {
var points = data.split("\n");
for (var i=0; i<points.length; i++) {
points[i] = points[i].split(", ");
points[i][0] = parseInt(points[i][0]);
points[i][1] = parseInt(points[i][1]);
}
return points;
}
//finds the degree of the polynomail from the matrix object's data
function setPolynomialDegree(original) {
var data = original;
console.log(original);
//temporary data set to hold numbers in
var tempNumbers = [];
var degree = 1;
//move the original set of Y values into the temporary data set
for (var i = 0; i < data.length; i++) {
tempNumbers.push(data[i][1]);
}
//while the numbers in tempdata are not the same, execute subtraction
while (tempNumbers[0] != tempNumbers[1]) {
var newnums = []
var l = tempNumbers.length;
//find the difference for every set of numbers (0 & 1, 1 & 2, 2 & 3, etc.), and push those into the new data set
for (var i = 0; i < l - 1; i++) {
newnums.push(tempNumbers[i + 1] - tempNumbers[i]);
}
//replace old data set with new one
tempNumbers = newnums;
//increase polynomial degree by one
degree += 1;
}
return degree;
}
//add 2 arrays together
function addrows(r1, r2) {
var temprow = [];
for (var i = 0; i < r1.length; i++) {
temprow.push(r1[i] + r2[i]);
}
return temprow;
}
//multiply array by constant
function multrow(r1, num) {
var temprow = [];
for (var i = 0; i < r1.length; i++) {
temprow.push(r1[i] * num);
}
return temprow;
}
//rref function
function rref(mtrx, deg) {
var temp1 = [];
var temp2 = [];
for (var row = 0; row < mtrx.length; row++) {
for (var j = 0; j < mtrx.length-1; j++) {
temp1 = multrow(mtrx[row], mtrx[j+1][row]);
temp2 = multrow(mtrx[j+1], mtrx[row][row]);
temp1 = multrow(temp1, -1);
mtrx[j+1] = addrows(temp1, temp2);
}
}
return mtrx;
}
//Main function that will solve the matrix
function solveFromDataSet(data) {
data = getDataFromString(data);
for (var i=0; i<data.length; i++) {
matrix['startingDataSet'].push(data[i]);
}
matrix.degree = setPolynomialDegree(matrix.startingDataSet);
matrix.M = [];
for (var i = 0; i < matrix.degree; i++) {
var row = [];
for (var j = matrix.degree; j > 0; j--) {
row.push(Math.pow(data[i][0], j - 1));
}
row.push(data[i][1]);
matrix['M'][i] = row;
}
var var_array = rref(matrix['M']);
console.log(matrix.M);
return matrix.M;
}