Second Greatlow Coderbyte Solution

0

 Have the function SecondGreatLow(arr) take the array of numbers stored in arr and return the second lowest and second greatest numbers, respectively, separated by a space.

For example: if arr contains [7, 7, 12, 98, 106] the output should be 12 98. The array will not be empty and will contain at least 2 numbers. It can get tricky if there's just two numbers!



Second Greatlow Coderbyte in Java


import java.util.Arrays;
import java.util.Scanner;


public class SecondGreatLow {
String SecondGreatLow(int[] arr) {
if (arr.length == 2) {
return arr[0] + " " + arr[1];
}

Arrays.sort(arr);

int lowest = Integer.MIN_VALUE,
highest = Integer.MAX_VALUE;

int lowestCount = 0, highestCount = 0;
for (int nr : arr) {
if (nr > lowest) {
lowestCount++;
lowest = nr;

if (lowestCount == 2) break;
}
}

for (int i = arr.length - 1; i >= 0; i--) {
if (arr[i] < highest) {
highestCount++;
highest = arr[i];

if (highestCount == 2) break;
}
}

return lowest + " " + highest;

}

public static void main (String[] args) {
// keep this function call here
Scanner s = new Scanner(System.in);
SecondGreatLow c = new SecondGreatLow();
System.out.print(c.SecondGreatLow(
new int[] {7, 7, 12, 98, 106}));
}
}


Second Greatlow Coderbyte in JavaScript

Using the JavaScript language, have the function SecondGreatLow(arr) take the array of numbers stored in arr and return the second lowest and second greatest numbers, respectively, separated by a space. 

For example: if arr contains [7, 7, 12, 98, 106] the output should be 12 98. The array will not be empty and will contain at least 2 numbers. It can get tricky if there's just two numbers!


function SecondGreatLow(arr) {

if (arr.length === 2) {
arr.sort(function(a,b) {return a - b});
return arr[1] + " " + arr[0];
}
var uniqueArray = arr.filter(function(item, pos) {
return arr.indexOf(item) == pos;
});
if (uniqueArray.length > 2) {
uniqueArray.sort(function(a, b){return a-b});
return uniqueArray[1] + " " + uniqueArray[uniqueArray.length - 2];
}
else {
return uniqueArray[1] + " " + uniqueArray[0];
}
}

Explanation

This challenge has one outlier and that is if there are only two elements in the array. In that case you sort the pair and return each entry as the second highest and second lowest. Outside of that I am going to sort the array in ascending order and remove duplicate values. Then return the second entry and the next to last entry.

Second Greatlow Coderbyte in Python


def SecondGreatLow(arr):
newArr = sorted(set(arr))
return "%d %d" %(newArr[1], newArr[-2])
# keep this function call here
# to see how to enter arguments in Python scroll down
print SecondGreatLow(raw_input())

Disclaimer: The above Problem is generated by Coderbyte but the Solution is provided by ShouterFolk.


Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.
Post a Comment (0)
Our website uses cookies to enhance your experience. Learn More
Accept !