Related
I am trying to find the indexes of element in an array equal to a specified sum.
I only want 2 indexes.
function sumArrayHashTable(arr, sum) {
var result = [];
var hashTable = {};
for (var i = 0; i < arr.length; i++) {
var S = sum - arr[i];
if (hashTable[S] !== undefined) {
result.push([arr[i], S]);
} else {
hashTable[arr[i]] = arr[i]
}
}
return result;
}
console.log(sumArrayHashTable([5, 2, 6, 1, 3, 9, 0], 9));
//Result should be [[2,4], [5,6]]
I am able to print the numbers but not the indexes. Please advice
Use your hash table to store the indices instead of the values. Also, push the indices in your result array:
function sumArrayHashTable(arr, sum) {
const result = [];
const hashTable = {};
for (let i = 0; i < arr.length; i++) {
const S = sum - arr[i];
if (hashTable[S] !== undefined) {
result.push([i, hashTable[S]]);
} else {
hashTable[arr[i]] = i;
}
}
return result;
}
console.log(sumArrayHashTable([5, 2, 6, 1, 3, 9, 0], 9));
//Result should be [[2,4], [5,6]]
function sumArrayHashTable(arr, sum) {
var result = [];
for (var i = 0; i < arr.length; i++) {
var test = 0;
for (var j = 0; j < arr.length; j++) {
if (i === j) {
continue ;
}
test = arr[i] + arr[j];
if (test === sum) {
result.push([i, j]);
}
}
}
return result;
}
console.log(sumArrayHashTable([5, 2, 6, 1, 3, 9, 0], 9));
Result will be [[2,4], [5,6]] plus [[4,2], [6,5]] you can take it from now
alghorithm is simple, O(n^2) - loop over array once, then again and find sum that equals 9
Hello friends,
I wanna create function that return new Array with prime numbers only.
My function should return only prime numbers, but it return not only prime.
Would you be so kind to tell me how can I improve my function (or make corectly)?
Thank you in advanced!!
function getAllPrimeNumber(array, num) {
array = new Array();
for (var i = 2; i <= num; i++) {
for(var j = 2; j < i; j++){
if(i % j==0){break; }
array.push(i);
}
}
return array;
}
console.log(getAllPrimeNumber([], 5)); //[3, 5, 5, 5]
console.log(getAllPrimeNumber([], 9)); //[3, 5, 5, 5, 7, 7, 7, 7, 7, 9]
You need to check that i can't be fully divided by all numbers from 2 up to i / 2 not including itself (if the number is 2), and only then push i into the array:
function getAllPrimeNumber(num) {
var array = [];
var isPrime;
for (var i = 2; i <= num; i++) {
for (var j = 2; (isPrime = i === j || i % j !== 0) && j <= i / 2; j++) {}
isPrime && array.push(i);
}
return array;
}
console.log(getAllPrimeNumber(5));
console.log(getAllPrimeNumber(9));
Is this a good way or the best way to implement Counting Sort in Javascript?
Can't find a standard JS Counting Sort example.
function countingSort(arr){
var helper = []; // This helper will note how many times each number appeared in the arr
// Since JS arrary is an object and elements are not continuously stored, helper's Space Complexity minor that n
for(var i = 0; i<arr.length; i++){
if(!helper[arr[i]]){
helper[arr[i]] = 1;
}else{
helper[arr[i]] += 1;
}
}
var newArr = [];
for(i in helper){
while(helper[i]>0){
newArr.push(parseInt(i));
helper[i]--;
}
}
return newArr;
}
var arr = [5,4,3,2,1,0];
console.log(countingSort(arr)); // [0, 1, 2, 3, 4, 5]
The code is correct, with some comments:
In general, the use of for..in on arrays is discouraged, but unless you define enumerable properties on the Array prototype (which is a bad idea anyway), your use of it is fine to me
You could improve the part where you loop to push the same value several times. This can be done in "one" go by concatenating Array(helper[i]).fill(i) to the results.
You could also use reduce to make the function more functional programming style. In the extreme, it could look like this:
function countingSort(arr){
return arr.reduce( (acc, v) => (acc[v] = (acc[v] || 0) + 1, acc), [] )
.reduce( (acc, n, i) => acc.concat(Array(n).fill(i)), [] );
}
// Sample run:
var arr = [5,4,3,2,1,0];
console.log(countingSort(arr)); // [0, 1, 2, 3, 4, 5]
counting sort is to start by initializing an auxiliary array of length k, that will hold the count of each number. Each index has an initial value of 0. After that, you loop through the input array and increase the “count” for each value by 1 every time you encounter that number in the array. Now, the auxiliary array holds the number of times each element is in the input array. The last step is to loop from the minimum value to the maximum value. In this loop, you’ll loop through each corresponding value in the count array, and add the elements who’s count is greater than 0 to the array in sequential order. You add each item by using a secondary incrementing variable (e.g. if we’re using “i” to loop from the min to max values, then we’ll use “j” to loop through the array), then increasing that second incrementing variable so the next item is placed in the next highest array index, and finally you decrease the value of the current item in the count array so that you don’t add too many of elements that value.
const countingSort = (arr, min, max) => {
const count = {};
// First populate the count object
for (let i = min; i <= max; i++) {
count[i] = 0;
}
for (let i = 0; i < arr.length; i++) {
count[arr[i]] += 1;
}
/* Now, count is indexed by numbers, with values corresponding to occurrences, eg:
* {
* 3: 1,
* 4: 0,
* 5: 2,
* 6: 1,
* 7: 0,
* 8: 0,
* 9: 1
* }
*/
// Then, iterate over count's properties from min to max:
const sortedArr = [];
for (let i = min; i <= max; i++) {
while (count[i] > 0) {
sortedArr.push(i);
count[i]--;
}
}
return sortedArr;
};
console.log(countingSort([3, 6, 5, 5, 9], 3, 9));
const countingSort = (arr, min, max) => {
let counters = [...Array(max+1)].map(e => 0);
let result = []
for(let i = min; i < max; i++){
counters[arr[i]] += 1
}
for(let j = min; j <= max; j++){
while( counters[j] > 0){
result.push(j)
counters[j]--
}
}
return result
}
const countingSort = (arr, min, max) => {
const count = {};
// First populate the count object
for (let i = min; i <= max; i++) {
count[i] = 0;
}
for (let i = 0; i < arr.length; i++) {
count[arr[i]] += 1;
}
/* Now, count is indexed by numbers, with values corresponding to occurrences, eg:
* {
* 3: 1,
* 4: 0,
* 5: 2,
* 6: 1,
* 7: 0,
* 8: 0,
* 9: 1
* }
*/
// Then, iterate over count's properties from min to max:
const sortedArr = [];
for (let i = min; i <= max; i++) {
while (count[i] > 0) {
sortedArr.push(i);
count[i]--;
}
}
return sortedArr;
};
console.log(countingSort([3, 6, 5, 5, 9], 3, 9));
const countingSort = (arr, min, max) => {
const count = {};
// First populate the count object
for (let i = min; i <= max; i++) {
count[i] = 0;
}
for (let i = 0; i < arr.length; i++) {
count[arr[i]] += 1;
}
/* Now, count is indexed by numbers, with values corresponding to occurrences, eg:
* {
* 3: 1,
* 4: 0,
* 5: 2,
* 6: 1,
* 7: 0,
* 8: 0,
* 9: 1
* }
*/
// Then, iterate over count's properties from min to max:
const sortedArr = [];
for (let i = min; i <= max; i++) {
while (count[i] > 0) {
sortedArr.push(i);
count[i]--;
}
}
return sortedArr;
};
console.log(countingSort([3, 6, 5, 5, 9], 3, 9));
let a = [2, 1, 1, 0, 2, 5, 4, 0, 2, 8, 7, 7, 9, 2, 0, 1, 9];
let max = Math.max(...a);
let min = Math.min(...a);
function countingSort(arr) {
const count = [];
for (let i = min; i <= max; i++) {
count[i] = 0;
}
for (let i = 0; i < arr.length; i++) {
count[arr[i]]++;
}
const sortedArr = [];
for (let i = min; i <= max; i++) {
while (count[i] > 0) {
sortedArr.push(i);
count[i]--;
}
}
return sortedArr;
}
console.log(countingSort(a));
The simplest way to solve this problem you write like this:
const range = (start, stop, step) => {
if (typeof stop == "undefined") {
stop = start;
start = 0;
}
if (typeof step == "undefined") step = 1;
if ((step > 0 && start >= stop) || (step < 0 && start <= stop)) return [];
let result = [];
for (let i = start; step > 0 ? i < stop : i > stop; i += step)
result.push(i);
return result;
};
const numbers = [1, 2, 2, 2, 1, 3, 3, 1, 2, 4, 5];
const max = Math.max.apply(Math, numbers);
let count = Array.apply(null, Array(max + 1)).map(() => 0);
for (x of numbers)
count[x] += 1;
let arr = [];
for (x in range(max + 1))
for (i in range(count[x]))
arr.push(parseInt([x]));
console.log(arr);
I have made a bubble sort algorithm (sorta) using JS. It works sometimes, but the problem is that it only iterates through the array once. Here is my code:
function bubble(arr) {
for (var i = 0; i < arr.length; i++) {
if (arr[i] > arr[i + 1]) {
var a = arr[i]
var b = arr[i + 1]
arr[i] = b
arr[i + 1] = a
}
}
return arr;
}
Another bubble sort implementation:
const bubbleSort = array => {
const arr = Array.from(array); // avoid side effects
for (let i = 1; i < arr.length; i++) {
for (let j = 0; j < arr.length - i; j++) {
if (arr[j] > arr[j + 1]) {
[arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
}
}
}
return arr;
};
You need an inner loop to complete the sort correctly:
function bubble(arr) {
var len = arr.length;
for (var i = 0; i < len ; i++) {
for(var j = 0 ; j < len - i - 1; j++){ // this was missing
if (arr[j] > arr[j + 1]) {
// swap
var temp = arr[j];
arr[j] = arr[j+1];
arr[j + 1] = temp;
}
}
}
return arr;
}
document.write(bubble([1,9,2,3,7,6,4,5,5]));
Please look at the following sequence:
[5, 4, 3, 2, 1]
Now lets say you need to sort this in the ascending order using bubble sort.
So, you iterate the array and swap adjacent elements which are ordered otherwise.
Here is what you will get after the completion of the iteration
[4, 3, 2, 1, 5]
Now if you do this another time, you will get this:
[3, 2, 1, 4, 5]
Likewise, you need to repeat the iteration enough times to get it sorted fully. This means you need 2 nested loops. The inner loop is to iterate the array and the outer loop is to repeat the iteration.
Please see the step-by-step example of this article.
const bubbleSort = (array)=>{
let sorted = false;
let counter =0;
while(!sorted){
sorted = true;
for(let i =0; i < array.length -1 -counter; i++){
if(array[i] > array[i+1]){
helper(i,i+1,array);
sorted = false;
}
}
counter++;
}
return array;
}
//swap function
function helper(i,j, array){
return [array[i],array[j]] = [array[j],array[i]]
}
let array=[8,5,2,9,5,6,3];
console.log(bubbleSort(array))
var array = [6,2,3,7,5,4,1];
function bubbleSort(arr) {
for(let j=0;j<arr.length;j++) {
for(let i = 0; i < arr.length; i++) {
if(arr[i]>arr[i+1] && (i+1 < arr.length)) {
var temp = arr[i];
arr[i] = arr[i+1];
arr[i+1] = temp;
}
}
}
return arr;
}
console.log(bubbleSort(array));
My bubble sort with just a while loop :
function bubbleSort(arr){
var sorted = false
while (!sorted){
sorted = true;
arr.forEach(function (element, index, array){
if (element > array[index+1]) {
array[index] = array[index+1];
array[index+1] = element;
sorted = false;
}
});
}
}
function bubble(arr) {//You need Two Loops for Bubble sort
for (var i = 0; i < arr.length; i++) {//Outer Loop
for(var j=0; j < arr.length - 1; j++){//Inner Loop
if (arr[j] > arr[j + 1]) {
var a = arr[j]
var b = arr[j + 1]
arr[j] = b
arr[j + 1] = a
}
}
}
return arr;
}
Another form of bubble sort includes starting at the end of the array and placing the smallest element first and going till the largest. This is the code:
function bubbleSort(items) {
var length = items.length;
for (var i = (length - 1); i >= 0; i--) {
//Number of passes
for (var j = (length - i); j > 0; j--) {
//Compare the adjacent positions
if (items[j] < items[j - 1]) {
//Swap the numbers
var tmp = items[j];
items[j] = items[j - 1];
items[j - 1] = tmp;
}
}
}
}
Note Bubble sort is one of the slowest sorting algorithms.
It works for me. I commented the code for more understanding
bubbleSort = (numbersArray) => {
const arrayLenght = numbersArray.length;
for (let i = 0; i < arrayLenght; i++) {
for(let j = 0; j < arrayLenght; j++) {
// Print only to debug
// console.log(`i: ${i} - j: ${j}`);
// console.log(`numbersArray[i]: ${numbersArray[i]} | numbersArray[j]: ${numbersArray[j]}`);
// Check if current number is greater than the next number
if (numbersArray[j] > numbersArray[j + 1]) {
// Store current value to generate swap
const currentNumber = numbersArray[j];
// Now the current position get value of the next position
// And de next position get value of the current position
numbersArray[j] = numbersArray[j + 1];
numbersArray[j + 1] = currentNumber;
}
}
}
// Debug: Print the sorted array
console.log(`sorted array: ${numbersArray.toString()}`);
}
const numbers = [
[3, 10, 5, 7],
[8, 5, 2, 9, 5, 6, 3],
[4, 50, 28, 47, 9, 2097, 30, 41, 11, 3, 68],
[3, 10, 5, 7, 8, 5, 2, 9, 5, 6, 3]
];
numbers.forEach(element => {
bubbleSort(element);
});
Output:
sorted array: 3,5,7,10
sorted array: 2,3,5,5,6,8,9
sorted array: 3,4,9,11,28,30,41,47,50,68,2097
sorted array: 2,3,3,5,5,5,6,7,8,9,10
var arr = [5, 3, 4, 1, 2, 6];
function sort (arr) {
for(let i=0; i < arr.length - 1; i++) {
if(arr[i] > arr[i+1]) {
let b = arr[i+1];
arr[i+1] = arr[i];
arr[i] = b;
i = -1; // Resets the loop
}
}
return arr;
}
console.log(sort(arr));
Try this (performance upgrade):
function bubbleSort(inputArr, reverse = false) {
const len = inputArr.length;
for (let i = 0; i < len; i++) {
for (let j = i + 1; j < len; j++) {
let a = inputArr[i];
let b = inputArr[j];
if (reverse ? a < b : a > b) {
const tmp = inputArr[j];
inputArr[j] = inputArr[i];
inputArr[i] = tmp;
}
}
}
return inputArr;
}
Use:
arr = [234,2,4,100, 1,12,5,23,12];
console.log(bubbleSort(arr)); // or console.log(bubbleSort(arr, true));
You need another loop:
var arr = [2, 1]
for(let i = 0;i<arr.length;i++){
for(let b = 0; b<arr.length;i++){
if(arr[b] > arr[b+1]){
var first = arr[b]
var second = arr[b + 1]
arr[b] = second
arr[b + 1] = first
}
}
}
Hope this helps I would recommend using quick sort if you want a high efficiency though.
const bubbleSort = (inputArr) => {
const len = inputArr.length;
for (let i = 0; i < len; i++) {
for (let j = 0; j < len; j++) {
if (inputArr[j] > inputArr[j + 1]) {
let tmp = inputArr[j];
inputArr[j] = inputArr[j + 1];
inputArr[j + 1] = tmp;
}
}
}
return inputArr;
};
const numbers = [50, 30, 10, 40, 60];
console.log(bubbleSort(numbers));
// Output: [ 10, 30, 40, 50, 60 ]
function bubbleSort(array) {
var done = false;
while (!done) {
//alert(1)
done = true;
for (var i = 1; i < array.length; i += 1) {
if (array[i - 1] > array[i]) {
//alert(2)
done = false;
var tmp = array[i - 1];
array[i - 1] = array[i];
array[i] = tmp;
}
}
}
return array;
}
Another way would be like this:
function bubbleSort(arr) {
let swapped;
do {
swapped = false;
for (var i = 0; i < arr.length; i++) {
if (arr[i] > arr[i + 1]) {
swapped = true;
var tmp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = tmp;
}
}
} while (swapped);
return arr;
}
let myArray = [8, 1, 2, 5, 51, 13, 15, 33, 123, 100, 22];
console.log(bubbleSort(myArray));
Explanation:
In this function we are going to declare a swapped variable that is being set to false inside the DO WHILE loop, this is being done as a fail-safe not to end up with an infinite loop.
Inside the loop, we have another FOR loop which iterates through the given array and checks if the current value is greater than the next (which we don't want, we need ascending order).
When the IF the condition is true, we are going to swap the variables and assign true for the swapped variable, this is done because we want to keep on the DO WHILE loop untill everything is sorted.
package hasan;
public class hssd {
public static void main(String[] args) {
int t=9;
int g=20;
for (t=g;t>19;++t){
System.out.println(7);
int f=12;
int r=15;
for(r=f;r>5;++r)
System.out.println(r+1000000000+"*"+1000000000);
}
}
}
I need to sort an array of numbers, so that it returns its minumum and its maximum. The code I've written so far doesn't seem to do anything at all.
function sort(array) {
arrayNew = [];
maximum = array[0];
minimum = array[0];
for (i = 0; i < array.length; i++) {
if (maximum < array[i]) {
maximum = array[i];
}
}
arrayNew.push(maximum);
for (i = 0; i < array.length; i++) {
if (minimum > array[i]) {
minimum = array[i];
}
}
arrayNew.unshift(minumum);
return arrayNew;
}
var arr1 = [3, 8, 7, 6, 5, -4, 3, 2, 1];
alert(sort(arr1));
In case you didn't know there is a much simpler way to get the min and max values from an array - use Math.min and Math.min with apply:
var min = Math.min.apply(null, arr1);
var max = Math.max.apply(null, arr1);
DEMO
minumum is spelled incorrectly. It should have been minimum
Don't use your variables without declaring them with var keyword. Otherwise they will become global properties.
Also, you can have your minimum check also in the same loop as maximum. So, your code can be shortened like this
function sort(array) {
var maximum = array[0],
minimum = array[0],
i;
for (i = 0; i < array.length; i++) {
if (maximum < array[i]) {
maximum = array[i];
}
if (minimum > array[i]) {
minimum = array[i];
}
}
return [minimum, maximum];
}
Now that we know, we can do it like this, lets try to shorten it more with ternary operator
function sort(array) {
var maximum = array[0],
minimum = array[0],
i;
for (i = 0; i < array.length; i++) {
maximum = maximum < array[i] ? array[i] : maximum;
minimum = minimum > array[i] ? array[i] : minimum;
}
return [minimum, maximum];
}
var arr = [ 3, 8, 7, 6, 5, -4, 31, 2, 21, 20, 1 ].sort(function(a, b) { return a - b }), // [-4, 1, 2, 3, 5, 6, 7, 8, 20, 21, 31]
min = arr[0], // min
max = arr[arr.length-1]; //max
arrayNew.unshift(minumum); is wrong variable minimum
correct one : arrayNew.unshift(minimum);