25

I need to create a program that checks the list in the array is sorted. I have three input data:

1,2,3,4,5

1,2,8,9,9

1,2,2,3,2

So here is my code:

let sorts = +gets(); // 3
let list = [];

for (let i = 0; i < sorts; i++) {
    list[i] = gets().split(',').map(Number); // The Array will be: [ [ 1, 2, 3, 4, 5 ], [ 1, 2, 8, 9, 9 ], [ 1, 2, 2, 3, 2 ] ]
}

for (let i = 0; i < list[i][i].length; i++){
    if (list[i][i] < list[i][i +1]) {
        print('true');
    } else {
        print('false');
    }
}

I need to print for all lists on new line true or false. For this example my output needs to be:

true

true

false

I have no idea how to resolve this.

0

9 Answers 9

33

You can use array#every to check if each value is greater than the previous value.

const isSorted = arr => arr.every((v,i,a) => !i || a[i-1] <= v);
console.log(isSorted([1,2,3,4,5]));
console.log(isSorted([1,2,8,9,9])); 
console.log(isSorted([1,2,2,3,2]));

Sign up to request clarification or add additional context in comments.

5 Comments

Make it shorter: arr.every((v,i,a) => !i || a[i-1] <= v)
@VisioN Updated the solution. Thanks for the input.
Is it really good practice to use tricks like !i for i<1? Otherwise, probably the right way to do this.
@JollyJoker I wouldn't call it a trick--it's equivalent to i === 0 (which might be more readable). This is the best solution on the thread because it combines early bailout with modern, functional syntax.
@ggorlen Some things are standard in Javascript that would be considered oddities to avoid in other languages
29

How about something like this:

!![1,2,3,4,5].reduce((n, item) => n !== false && item >= n && item)
// true

!![1,2,8,9,9].reduce((n, item) => n !== false && item >= n && item)
// true 

!![1,2,2,3,2].reduce((n, item) => n !== false && item >= n && item)
// false

Reduce will literally reduce the array down to a single value - a boolean in our case.

Here, we are calling a function per iteration, the (n, item) is our function signature, it's body being n !== false && item >- n && item - we are making sure that n exists (n is our accumulator - read up!), testing if item is greater than n, and making sure item exists.

This happens for every element in your array. We then use !! to force the result into a tru boolean.

10 Comments

That's a clever one, though it would be worth to give the user an explanation, unexperienced programmers would never understand what's happening here. For sake of testing, here is a fiddle: jsfiddle.net/briosheje/46r1jm03
Indeed. [0, 1, 2, 3, 4, 5] will return false.
@VisioN This is a very good point indeed.
Will this short circuit?
@BobBrinks Nope. It'll keep on chugging along over a list of 1,000,000 elements even if the first two aren't sorted. arr.every has my vote.
|
13

Simply try this way by using slice method : It will check if previous element is less than the next element.If the condition is true for every element then it will return true else false

arr.slice(1).every((item, i) => arr[i] <= item);

Checkout this below sample as Demo

var arr = [[1,2,3,4,5],[1,2,8,9,9],[1,2,2,3,2],[0,1,2,3,4,5]];

function isArrayIsSorted (arr) {
  return arr.slice(1).every((item, i) => arr[i] <= item)
}

var result= [];
for (var i = 0; i < arr.length; i++){
result.push(isArrayIsSorted(arr[i]))
}
console.log(result);

Comments

8

Sorted Number Lists

Including Negative Numbers, Zeros, and Adjacent Duplicates

Use every() method which will return true should all of the numbers be in order otherwise it will return false. The conditions are as follows:

(num <= arr[idx + 1]) || (idx === arr.length - 1)
  1. if the current number is less than or equal to the next number...

    OR...

  2. if the current index is equal to the last index...

     return 1 (truthy)
    

Demo

var arr0 = [1, 2, 3, 4, 5];
var arr1 = [1, 2, 8, 9, 9];
var arr2 = [1, 2, 2, 3, 2];
var arr3 = [0, 0, 0, 1, 3];
var arr4 = [-3, 0, 1, 3, 3];
var arr5 = [-4, -2, 0, 0, -4];

function sorted(array) {
  return array.every(function(num, idx, arr) {
    return (num <= arr[idx + 1]) || (idx === arr.length - 1);
  });
}

console.log(arr0 +' | '+sorted(arr0));
console.log(arr1 +' | '+sorted(arr1));
console.log(arr2 +' | '+sorted(arr2));
console.log(arr3 +' | '+sorted(arr3));
console.log(arr4 +' | '+sorted(arr4));
console.log(arr5 +' | '+sorted(arr5));

7 Comments

for [0, 1, 3, 4, 5] it returns false
See update, thanks @LucaRainone
The point is that the trick is dangerous. For example it does not works with negative numbers. [-2, 0, 3, 4, 5]. But also your solution does not work for [0, 0, 1, 4, 5]
The callback for every gets value, index and the array. Aren't you comparing value to index?
See update, thanks @LucaRainone
|
7

var str = ["1,2,3,4,5", "1,2,8,9,9", "1,2,2,3,2"];

for (var i in str){
    var list = str[i].split(',').map(Number);
    console.log(list);
    var isSorted = true;
    for(var j = 0 ; j < list.length - 1 ; j++){
        if(list[j] > list[j+1]) {
            isSorted = false;
            break;
        }
    }
    console.log(isSorted);
}

1 Comment

This is really easy, but did you know how to create my Array like your (str): pastebin.com/tBFd9Uft Edit: I get it, only need gets() without .split()
3

There are plenty of ways how to do that. Here is mine

const isArraySorted = array =>
  array
  .slice(0) // clone array
  .sort((a, b) => a - b) // sort it
  .every((el, i) => el === array[i]) // compare with initial value)

Comments

2

Maybe you can use this helping method that checks if is sorted correctly:

    var arr1 = [1, 2, 3, 4, 4];
    var arr2 = [3, 2, 1];

		console.log(checkList(arr1));
		console.log(checkList(arr2));
    
    function checkList(arr) {
        for (var i = 0; i < arr.length; i++) {
            if (arr[i + 1]) {
                if (arr[i] > arr[i + 1]) {
                    return false;
                }
            }

        }
        return true;
    }

1 Comment

[1, 0, 1] - true
1

You can check if stringified sorted copy of original array has same value as the original one. Might not be the most cool or performant one, but I like it's simplicity and clarity.

const arraysToCheck = [
  [1, 2, 3, 4, 5],
  [1, 2, 8, 9, 9],
  [1, 2, 2, 3, 2]
]

const isSorted = arraysToCheck.map(
  item => JSON.stringify([...item].sort((a, b) => a - b)) === JSON.stringify(item)
 );


console.log(isSorted);

Comments

-2

If i get what you mean, you want to know if an array is sorted or not. This is an example of such a solution, try it. I pasted some codes below.

var myArray=[1,4,3,6];

if(isSorted(myArray)){

    console.log("List is sorted");
}else{
    console.log("List is not sorted");
}

function isSorted(X){

var sorted=false;

for(var i=0;i<X.length;i++){

        var next=i+1;

    if (next<=X.length-1){

        if(X[i]>X[next]){
            sorted=false;
            break;
        }else{
            sorted=true;

        }
    }

}


return sorted;

}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.