user3548898
user3548898

Reputation: 181

Make array consecutive

i got stucked in a chalenge in codeFights.my code pass the simple test and fail in just 2 from five of hidden tests her is the chalenge instruction:

Ratiorg got statues of different sizes as a present from CodeMaster for his birthday, each statue having an non-negative integer size. Since he likes to make things perfect, he wants to arrange them from smallest to largest so that each statue will be bigger than the previous one exactly by 1. He may need some additional statues to be able to accomplish that. Help him figure out the minimum number of additional statues needed.

Example

For statues = [6, 2, 3, 8], the output should be
makeArrayConsecutive2(statues) = 3.

Ratiorg needs statues of sizes 4, 5 and 7.

Input/Output

[time limit] 4000ms (js)
[input] array.integer statues

An array of distinct non-negative integers.

Constraints:
1 ≤ statues.length ≤ 10,
0 ≤ statues[i] ≤ 20.

[output] integer

The minimal number of statues that need to be added to existing statues such that it contains every integer size from an interval [L, R] (for some L, R) and no other sizes.

and here is my code :

function makeArrayConsecutive2(statues) {
 //range the table from min to max
 var rang=statues.sort();
 var some=0;
 //if the table is one element
 if(rang.length-1==0){
  return 0;

 }else{
  //if the table contain more then one element
  for(i=0;i<=rang.length-2;i++){
   //add the deference of two consecutive position -1 
   //to find the number of missing numbers
   some+=(rang[i+1]-rang[i]-1);
 }
  return some;
 }
}

Upvotes: 5

Views: 15703

Answers (19)

Seghaire Ameni
Seghaire Ameni

Reputation: 1

def solution(statues):
    sorted_statues = sorted(statues)
    s = 0
    for i in range(len(sorted_statues)-1):
        diff = sorted_statues[i + 1] - sorted_statues[i]
        if diff > 1:
            s+=diff-1
    return s

Upvotes: -1

Darragh Blake
Darragh Blake

Reputation: 248

PHP solution for question.

function solution($statues) {

sort($statues); 
$missing = 0;
$lowest = min($statues);
$highest = max($statues);

$numbers = range($lowest, $highest);

foreach($numbers as $number){
    if(!in_array($number, $statues)){
       $missing++; 
    }
}

return $missing;

}

Upvotes: 0

shakaran
shakaran

Reputation: 11122

Solution in PHP

function solution($statues) {
    return max($statues) - min($statues) - count($statues) + 1;
}

Upvotes: 0

Shreyansh_Jain
Shreyansh_Jain

Reputation: 1

here is code in python

def solution(statues):
   statues.sort()
   c = 0
   for i in range(len(statues)-1):
        if statues[i+1]-statues[i] > 1:
            c += statues[i+1]-statues[i] -1
   return (c)

Upvotes: -1

M.Adlane
M.Adlane

Reputation: 1

sort(statues.begin(), statues.end());
int count = 0;

for(int i = 1;i<statues.size(); i++){
    int diff = statues[i]-statues[i-1];
    if(diff>1){
        count+=diff-1; 
    }
}

return count;

Upvotes: 0

grey
grey

Reputation: 3

function makeArrayConsecutive2(statues) {
    s = statues.sort(function(a, b){return a - b});
    n = statues.length;
    val = 0;

    for (let i=0;i<n-1;i++) {
        val += (Math.abs(s[i]-s[i+1]))-1;
    }

    return val;
}

Upvotes: 0

ANUSHIYA ASOKAN
ANUSHIYA ASOKAN

Reputation: 1

you can try using for loop and ternary operation by the following code

def makeArrayConsecutive2(statues):
count=0
for i in range (min(statues),max(statues)):
    count=count+1 if i not in statues else count
return count

Upvotes: 0

Sardorek Aminjonov
Sardorek Aminjonov

Reputation: 834

function makeArrayConsecutive2(statues) {
  const nums = [];

  for (let i = Math.min(...statues); i <= Math.max(...statues); i++) {
    if (!statues.includes(i)) {
      nums.push(i);
    }
  }

  return nums.length;
}

console.log(makeArrayConsecutive2([6, 2, 3, 8]))

Upvotes: 2

Montassar Daimi
Montassar Daimi

Reputation: 1

function makeArrayConsecutive2(statues) {
    return Math.max(...statues) - Math.min(...statues) + 1 -(statues.length) 
}

I don't think we need a Looping there, that's my solution

Upvotes: 0

Rizwan
Rizwan

Reputation: 89

Just for fun in C#

static int makeArrayConsecutive2(int[] statues)
        {
            List<int> ConsecutiveNums = new List<int>();
            for(int i = statues.Min(); i != statues.Max() + 1; i++)
                ConsecutiveNums.Add(i);           
            return ConsecutiveNums.Count - statues.Length;         
        }

Upvotes: 0

Oleksii Sedliarov
Oleksii Sedliarov

Reputation: 1

function makeArrayConsecutive2(statues) {
  const n = statues.length;
  const min = Math.min(...statues);
  const max = Math.max(...statues);
  return max - min - n + 1;
}

If we subtract the minimum from the maximum element, then we get the number of elements that should be in the final array. Now subtract the already existing number of elements from this amount and add 1, then we get the result we need - the number of missing elements

Upvotes: 0

Niraj Kumar
Niraj Kumar

Reputation: 1

function makeArrayConsecutive2(statues) {
    var rang = statues.sort(function (a, b){
        return (a - b) 
    });
    var some=0;
 
    if(rang.length-1==0){
        return 0;
    }else{
    for(i=0;i<=rang.length-2;i++){
        some+=(rang[i+1]-rang[i]-1);
    }
    return some;
    }
}

Upvotes: 0

as8297
as8297

Reputation: 1139

SO THE LOGIC TO SOLVE THIS QUESTION IS:

  1. Find the Smallest and Largest Element in Array.

  2. Get the count of can say, difference of Largest and Smallest value of array in order to calculate, how many elements must be there to make it as a continuous array . Like from 5 to 9, count of total elements must be 5 ( i.e.5,6,7,8,9) and also add 1 to the result to make count inclusive.

  3. Find the Length of the Array

  4. Subtract the count i.e. "difference of largest and smallest value " with the length of array

PYTHON CODE (For explanation):

def makeArrayConsecutive2(statues):
    max_height = max(statues)
    min_height = min(statues)
    array_length  = len(statues)

    count_of_element = max_height - min_height + 1
    # '1 ' is added to make it inclusive
  
    return count_of_element-array_length

and Python one liner :

def makeArrayConsecutive2(statues):
    return max(statues)-min(statues)-len(statues)+1

Upvotes: 4

Alok Deshwal
Alok Deshwal

Reputation: 1126

Best solution goes here in just O(1) complexity:

let n = statues.length;
let max = Math.max.apply(null, statues);
let min = Math.min.apply(null, statues);
return max - min - n + 1;

Upvotes: 0

user8104070
user8104070

Reputation: 11

This Code works

var statues = [2, 3, 6, 8];  
var newStatues = [];

Function declaration

function makeArrayConsecutive2(statues) {
    statues.sort(function(a, b) { return a - b });
    for(var i = statues[0]; i <= statues[statues.length-1]; i++) {
        newStatues.push(i);
    }
    return console.log(newStatues.length - statues.length);
}

Function Calling

makeArrayConsecutive2(statues);

Upvotes: 0

Kyle Henry
Kyle Henry

Reputation: 19

Solution in typescript. Create a new array from the min and max from the status array using a for loop. Subtract new array length with status array length.

function makeArrayConsecutive2(statues: number[]): number {

    let min = Math.min(...statues);
    let max = Math.max(...statues);
    let arr = [];

    for (let i = min; i <= max; i++) {
        arr.push(i);
    }

    return arr.length - statues.length;
}

Upvotes: 1

Victoria
Victoria

Reputation: 11

I agree with Deepak's Solution. The question is ready not about sorting but helping to figure out the minimum number of additional statues needed. You only need to get the max and min values.

int makeArrayConsecutive2(int[] statues) 
{
    int min=Integer.MAX_VALUE,max=-1;
    for(int i=0;i<statues.length;i++)
    {
        if(statues[i] < min){ min = statues[i]; }
        if(statues[i] > max){ max = statues[i]; }
    }
     return (max-min)+1 - statues.length;
}

Upvotes: 1

Deepak Agrawal
Deepak Agrawal

Reputation: 288

Sorting (nlogn)is not required. Below is the solution in Java.

int makeArrayConsecutive2(int[] statues) {
        int max = Integer.MIN_VALUE;
        int min = Integer.MAX_VALUE;
        for (int i = 0; i < statues.length; i++) {
            max = Math.max(max, statues[i]);
            min = Math.min(min, statues[i]);
        }
        return (max - min) + 1 - statues.length;
}

Upvotes: 0

Sanchay Kumar
Sanchay Kumar

Reputation: 566

Everything is correct, except the sorting part.

You have used sort function to sort the array in increasing order

var rang = statues.sort();

But if sort function is not provided a compare function, it converts its elements in strings and then sort it in unicode order.

For eg: [2,1,11] will be sorted as [1,11,2] which will give undesired output.

Correct way is

var rang = statues.sort(function (a, b){
    return (a - b) 
});

Upvotes: 10

Related Questions