Related
having a problem when running two tests using this code, test 1 returns the whole array, test2 returns the appropriate index. (the point in the array in which it stops decreasing or increasing and starts the reverse) if there is only one sequence it should return -1
the test cases are
Input: [-4, -2, 9, 10]
Output: -1
Input: [5, 4, 3, 2, 10, 11]
Output: 3
for (i = 0; i < arr.length; i++) {
while (arr[i] < arr[i + 1]) {
i++;
if (arr[i] < arr[i - 1]) {
return -1
}
else if (arr[i] > arr[i + 1]) {
return i
}
} while (arr[i] > arr[i + 1]) {
i++;
if (arr[i] > arr[i - 1]) {
return -1
} else if (arr[i] < arr[i + 1]) {
return i
}
}
}
return arr;
}
In the solution below, the isHomogeneous() method returns true if the content of the array is ever-increasing or ever-decreasing. The isIncreasing() method returns true if the array content is constantly decreasing. The isDecreasing() method returns true if the array content is ever-increasing. The getAscendingIndex() method returns the index at which the contents of the array begin to decrease. The getDescendingIndex() method returns the index at which the contents of the array begin to decrease. The application() method contains application code that executes other methods. If the content of the array is not homogeneous (continuously increasing or decreasing), the first index value at which the values start to increase in an array that starts with decreasing values is obtained using the getDescendingIndex() method.
/* Returns true if the array is descending to the elements (homogeneous). */
function isIncreasing(array) {
for(let i = 0 ; i < array.length ; ++i)
if(array[i] < array[i + 1])
return false;
return true;
}
/* Returns true if the array is incremental (homogeneous) to the elements. */
function isDecreasing(array) {
for(let i = 0 ; i < array.length ; ++i)
if(array[i] > array[i + 1])
return false;
return true;
}
/* Returns true if the array content is ever-increasing or ever-decreasing. */
function isHomogeneous(array) {
return isIncreasing(array) || isDecreasing(array);
}
/* return the descending index in the array starting with increasing. */
function getAscendingIndex(array) {
for(let i = 0 ; i < array.length ; ++i)
if(array[i] > array[i + 1])
return i;
return -1;
}
/* return increasing index in array starting with decreasing. */
function getDescendingIndex(array) {
for(let i = 0 ; i < array.length ; ++i)
if(array[i] < array[i + 1])
return i;
return -1;
}
/* demo */
function application() {
let firstArray = [-4, -2, 9, 10];
let secondArray = [5, 4, 3, 2, 10, 11];
console.log(`Increasing: ${(isIncreasing(firstArray) == true) ? "true" : "false"}`);
console.log(`Decreasing: ${(isDecreasing(firstArray) == true) ? "true" : "false"}`);
console.log(`First Array Index: ${getAscendingIndex(firstArray)}`);
if(!isHomogeneous(secondArray) && getAscendingIndex(secondArray) != -1) {
console.log(`Second Array Index: ${getDescendingIndex(secondArray)}`);
}
}
application();
Maybe this approach would be useful:
Find the index of the maximum and minimum element.
Check if this index is the beginning or the end of the array and retern -1 if it is.
And last return the maximal index out of the found ones.
const first = [-4, -2, 9, 10];
const second = [5, 4, 3, 2, 10, 11];
const getMyIndex = (arr) => {
const maxIndex = arr.indexOf(Math.max(...arr));
const minIndex = arr.indexOf(Math.min(...arr));
const getResult = (index) =>
(index === 0) || (index === arr.length - 1) ? -1 : index;
return Math.max(getResult(maxIndex), getResult(minIndex));
};
console.log('arr:', first, 'result:', getMyIndex(first));
console.log('arr:', second, 'result:', getMyIndex(second));
.as-console-wrapper{min-height: 100%!important; top: 0}
java solution that works!!!hope you will find it useful
public class MyClass {
public static void main(String args[]) {
int[] arr={1,2,3,4,5,6,7,1,2,3};
boolean asc=false;
boolean dsc=false;
int n=arr.length;
int x=0;
int y=0;
for(int i=1;i<n;i++){
if(arr[i]<arr[i-1]){
x=i;
break;
}
if(i==n-1){
if(arr[i]>arr[i-1])
asc=true;
}
}
for(int i=1;i<n;i++){
if(arr[i]>arr[i-1]){
y=i;
break;
}
if(i==n-1){
if(arr[i]<arr[i-1])
dsc=true;
}
}
if(asc||dsc)
System.out.println("-1");
else{
if(x>y)
System.out.println("asc"+(x-1));
else
System.out.println("dsc"+(y-1));
}
}
}
Trying to get this code to output -1 when value never occurs in an array.
function IndexOf (array,value) {
var index = [];
for (var i = 0; i < array.length; i++)
if (array[i] === value) {
index.push(i);
return index.pop();
} else if (value === undefined) {
return -1;
}
}
EDIT: not allowed to use .indexOf for this particular case.
EDIT 2: Sorry I wasn't more clear. I need to return the last matched element as opposed to first.
The trick to finding the last occurrence of an element is to start at the end (array.length-1) and iterate back towards the start using i--.
See return and for loop for more info.
// Index Of.
function indexOf(array, value) {
for (var i = array.length-1; i >= 0; i --) {
if (array[i] == value) return i
}
return -1
}
// Proof.
console.log(indexOf([ 0, 1, 3, 1, 2 ], 1))
console.log(indexOf([ 0, 1, 3, 1, 2 ], 2))
console.log(indexOf([ 0, 1, 3, 1, 2 ], 4))
console.log(indexOf([ 3, 3, 3 ], 3))
console.log(indexOf([], 5))
you can use indexOf function of Array object.
function checkArray(yourArray, value) {
if (yourArray.indexOf(value) > -1) {
// it means the value exists, so it has an index which is greater than -1.
// action
} else {
return -1;
}
}
You have
function IndexOf(array, value) {
// ...
} else if (value === undefined) {
return -1;
So when the second argument is ever provided, -1 will never be returned. There also isn't much point pushing to an array and then immediately popping it and returning it - just return the i itself.
Just wait until all iterations are finished instead, and then return -1.
function IndexOf(array, value) {
for (var i = 0; i < array.length; i++) {
if (array[i] === value) return i;
}
return -1;
}
console.log(IndexOf([0, 1, 3, 1, 2], 1));
console.log(IndexOf([0, 1, 3, 1, 2], 2));
console.log(IndexOf([0, 1, 3, 1, 2], 3));
console.log(IndexOf([3, 3, 3], 3));
console.log(IndexOf([], 5));
The below code works for your purpose, where returning -1 is the only other return option if the value isn't found in the array.
function IndexOf (array,value) {
var index = [];
for (var i = 0; i < array.length; i++)
if (array[i] === value) {
index.push(i);
return index.pop();
}
return -1
}
In your code, value will never equal undefined, rather value isn't located in the array and undefined is being returned due to lack of a return statement handling that condition.
Try this one. I hope this will work
function IndexOf(array, value) {
var index = [];
for (var i = 0; i < array.length; i++) {
if (array[i] === value) {
index.push(i);
}
}
if(index.length > 0){
return index.length;
} else{
return -1;
}
}
console.log(IndexOf([0, 1, 3, 1, 2], 1));
console.log(IndexOf([0, 1, 3, 1, 2], 2));
console.log(IndexOf([0, 1, 3, 1, 2], 3));
console.log(IndexOf([3, 3, 3], 3));
console.log(IndexOf([], 5));
Hopefully this snippet will be useful
function IndexOf(array, value) {
// creating an empty array
var index = [];
for (var i = 0; i < array.length; i++)
// if value matches return the index of the first matched element
if (array[i] === value) {
return i;
}
return -1
}
console.log(IndexOf([0, 1, 3, 1, 2], 1));
console.log(IndexOf([0, 1, 3, 1, 2], 2));
console.log(IndexOf([0, 1, 3, 1, 2], 3));
console.log(IndexOf([3, 3, 3], 3));
console.log(IndexOf([], 5));
function IndexOf(array, value) {
var match = -1;
for (var i = 0; i < array.length; i++)
if (array[i] === value)
match = i;
return match;
}
console.log(IndexOf([3, 3, 3], 3)); // will return 2 as the last match index is 2
console.log(IndexOf([1,2,4], 5)); // will return -1 as there is no match
I guess this is what you are looking for.
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);
}
}
}
Say I have a list [1,2,3,4,5,6,7]
and I would like to find the closest sum of numbers to a given number. Sorry for the crappy explanation but here's an example:
Say I have a list [1,2,3,4,5,6,7] I want to find the closest numbers to, say, 10.
Then the method should return 6 and 4 or 7 and 3 because its the closest he can get to 10. So 5 + 4 would be wrong because thats 9 and he can make a 10.
another example : you want the closest to 14 , so then he should return 7 and 6
If you got any questions plz ask because its difficult to explain what I want :P
Functions for combine, locationOf, are taken from different answers, written by different authors.
printClosest([0.5,2,4] , 5);
printClosest([1, 2, 3, 4, 5, 6, 7], 28);
printClosest([1, 2, 3, 4, 5, 6, 7], 10.9);
printClosest([1, 2, 3, 4, 5, 6, 7], 10, 2);
printClosest([1, 2, 3, 4, 5, 6, 7], 10, 3);
printClosest([1, 2, 3, 4, 5, 6, 7], 14, 2);
function printClosest(array, value, limit) {
var checkLength = function(array) {
return array.length === limit;
};
var combinations = combine(array); //get all combinations
combinations = limit ? combinations.filter(checkLength) : combinations;//limit length if required
var sum = combinations.map(function(c) { //create an array with sum of combinations
return c.reduce(function(p, c) {
return p + c;
}, 0)
});
var sumSorted = sum.slice(0).sort(function(a, b) {//sort sum array
return a - b;
});
index = locationOf(value, sumSorted);//find where the value fits in
//index = (Math.abs(value - sum[index]) <= Math.abs(value - sum[index + 1])) ? index : index + 1;
index = index >= sum.length ? sum.length - 1 : index;
index = sum.indexOf(sumSorted[index]);//get the respective combination
console.log(sum, combinations, index);
document.getElementById("result").innerHTML += "value : " + value + " combi: " + combinations[index].toString() + " (limit : " + (limit || "none") + ")<br>";
}
function combine(a) {
var fn = function(n, src, got, all) {
if (n == 0) {
if (got.length > 0) {
all[all.length] = got;
}
return;
}
for (var j = 0; j < src.length; j++) {
fn(n - 1, src.slice(j + 1), got.concat([src[j]]), all);
}
return;
}
var all = [];
for (var i = 0; i < a.length; i++) {
fn(i, a, [], all);
}
all.push(a);
return all;
}
function locationOf(element, array, start, end) {
start = start || 0;
end = end || array.length;
var pivot = parseInt(start + (end - start) / 2, 10);
if (end - start <= 1 || array[pivot] === element) return pivot;
if (array[pivot] < element) {
return locationOf(element, array, pivot, end);
} else {
return locationOf(element, array, start, pivot);
}
}
<pre id="result"><pre>
var data= [1, 2, 3,4,5,6,7];
var closest = 14;
for (var x = 0; x < data.length; x++) {
for (var y = x+1; y < data.length; y++) {
if(data[x] + data[y] == closet){
alert(data[x].toString() + " " + data[y].toString());
}
}
}
From what I understood from your question, I made this snippet. I assumed you did not wanted to have the same digit twice (e.g 14 => 7 + 7).
It is working with your examples.
var arr = [1, 2, 3, 4, 5, 6, 7];
var a = 0, b = 0;
var nb = 14;
for(var i in arr) {
for(var j in arr) {
if(i != j) {
var tmp = arr[i] + arr[j];
if(tmp <= nb && tmp > a + b) {
a = arr[i];
b = arr[j];
}
}
}
}
document.write("Closest to " + nb + " => " + a + " + " + b);
I have a little bit long winded solution to the problem just so it is easier to see what is done.
The main benefits with solution below:
The second loop will not start from beginning of the array again. What I mean that instead of having loop_boundary for second loop as 0 as you normally would, here it starts from next index. This helps if your numbers array is long. However, if it as short as in example, the impact in performance is minimal. Decreasing first loop's boundary by one will prevent errors from happening.
Works even when the wanted number is 1 or negative numbers.
Fiddle:
JSFiddle
The code:
var numbers = [1,2,3,4,5,6,7];
var wanted_number = 1;
var closest_range, closest1, closest2 = null;
var loop1_boundary = numbers.length-1;
for(var i=0; i<loop1_boundary; i++) {
var start_index = i+1;
var loop2_boundary = numbers.length;
for(var k=start_index; k<loop2_boundary; k++) {
var number1 = parseInt(numbers[i]);
var number2 = parseInt(numbers[k]);
var sum = number1 + number2;
var range = wanted_number - sum;
document.write( number1+' + '+number2 +' < '+closest_range+'<br/>' );
if(Math.abs(range) < Math.abs(closest_range) || closest_range == null ) {
closest_range = range;
closest1 = number1;
closest2 = number2;
}
}
if(range==0){
break;
}
}
document.write( 'closest to given number was '+closest1+' and '+closest2+'. The range from wanted number is '+closest_range );
This proposal generates all possible combinations, collects them in an object which takes the sum as key and filters then the closest sum to the given value.
function getSum(array, sum) {
function add(a, b) { return a + b; }
function c(left, right) {
var s = right.reduce(add, 0);
if (s > sum) {
return;
}
if (!result.length || s === result[0].reduce(add, 0)) {
result.push(right);
} else if (s > result[0].reduce(add, 0)) {
result = [right];
}
left.forEach(function (a, i) {
var x = left.slice();
x.splice(i);
c(left.slice(0, i), [a].concat(right));
});
}
var result = [];
c(array, [], 0);
return result;
}
function print(o) {
document.write('<pre>' + JSON.stringify(o, 0, 4) + '</pre>');
}
print(getSum([1, 2, 3, 4, 5, 6, 7], 10));
print(getSum([1, 2, 3, 4, 5, 6, 7], 14));
print(getSum([1, 2, 3, 4, 5, 6, 7], 19));
I have 2 arrays i want to sort those arrays and compare it
var A = [1,5,8,0,9];
var B = [5,9,0,1,8];
for(i=0;i<A.length;i++)
{
if(A[i] == B[i]){message}else{Fail}
I want to sort those arrays and then compare the values
You can just call the sort method on an array:
var A = [1, 5, 8, 0, 9];
var B = [5, 9, 0, 1, 8];
A.sort()
B.sort()
for (i = 0; i < A.length; i++) {
if (A[i] == B[i]) {
document.write(A[i] + ' and ' + B[i] + ' are identical' + '<br>')
} else {
document.write('fail')
}
}
You can use the sort() for this . Arary sort()
I cant properly understand whats the aim behind the comparison.SO make necessary changes.
var A = [1,5,8,0,9];
A.sort();
var B = [5,9,0,1,8];
B.sort();
for(i=0;i<A.length;i++)
{
if(A[i] == B[i])
{
message
}
else
{
Fail
}
}