I have a question about return the index position of the smallest number in the array. I picked out 3 answers from 5 answer were given that I provided below. I think one of them might possibly be correct. However, I quite don't understand the code very much, so I'm looking for an explanation how they work.
A
public int min(int[] a) {
int min = 0;
for (int i = 1; i < a.length; i++) {
if (a[i] < a[min]) {
min = i;
}
}
return a[i];
}
B
public int min(int[] a) {
int min = 0;
for (int i = 1; i < a.length; i++) {
if (a[i] < a[min]) {
min = i;
}
}
return i;
}
C
public int min(int[] a) {
int min = 0;
for (int i = 1; i < a.length; i++) {
if (a[i] < a[min]) {
min = i;
}
}
return min;
}
It is pretty straight forward.. you are looking for the smallest index.
Imagine array a has 3 elements.
A
public int min(int[] a) {
int min = 0;
for (int i = 1; i < a.length, i++) {
if (a[i] < a[min]) {
min = i;
}
}
return a[i]; //returning value. Wrong!
//you are searching for the index, not value isnt' it?
}
B
public int min(int[] a) {
int min = 0;
for (int i = 1; i < a.length, i++) {
if (a[i] < a[min]) {
min = i;
}
}
return i; //returning i which only exist in for-loop scope. Wrong!
}
C
public int min(int[] a) { //assume a has 3 elements
int min = 0; //for storing smallest index
for (int i = 1; i < a.length, i++) { //loop index 1,2
if (a[i] < a[min]) { //if current array value < current smallest value
min = i; //store new found smallest index
}
}
return min; //returning min, the smallest index
}
If min is not updated through the looping, it means index 0 (default value of min) holds the smallest value. Option C will be the correct answer.
The first code will give an error (Index out of bound exception)because at the end of for loop your " i " will be equal to the length of array and you are returning a[i] so this solution is completely wrong. The second code will return the length of array so it is also wrong solution. The third code that you have entered will return the index of smallest value. So the solution is correct.
Related
This is my code. I am using the bluej IDE.
public class practice
{
public int[] minMax(int[] num) {
int smallest = num[0];
int largest = num[0];
int countsmall = 0;
int countlarge = 0;
for (int i = 0; i <= num.length - 1; i++){
if (num[i] < smallest) smallest = num[i];
if (num[i] > largest) largest = num[i];
}
for (int i = 0; i <= num.length - 1; i++){
if (num[i] != smallest) countsmall++;
if (num[i] != largest) countlarge++;
}
int array[] = {countsmall,countlarge};
return array;
}
}
I am trying to find the minimum and maximum value in an array which I successfully did. After that,I am trying to find its index. I created a variable count, and then went through the array. If that item in the array does not equal the minimum or maximum value, count+= count. However, for some reason its not working. The code compiles but returns the wrong value. Keep in mind I am not allowed to use java libraries. Any help would be much appreciated, thanks.
If you want also indexes of biggest and smallest, why dont you do it in one loop? eg:
public class practice
{
public int[] minMax(int[] num) {
int smallest = num[0];
int largest = num[0];
int countsmall = 0;
int countlarge = 0;
for (int i = 0; i < num.length; i++){
if (num[i] < smallest) {
smallest = num[i];
countsmall=i;
}
if (num[i] > largest) {
largest = num[i];
countlarge=i;
}
}
int array[] = {countsmall,countlarge};
return array;
}
}
I'm practicing coding on HackerRank, and I have the following code, which gets a different outputs.
The task is the following:
Given an array of integers, find the longest subarray where the absolute difference between any two elements is less than or equal to.
Example:
a = [1,1,2,2,4,4,5,5,5];
There are two subarrays meeting the criterion: [1,1,2,2] and [4,4,5,5,5]. The maximum length subarray has 5 elements.
The following code gets the desired output:
public static int pickingNumbers(List<Integer> a) {
// Write your code here
int max = 0;
int counter = 0;
Collections.sort(a);
for(int i = 0; i < a.size(); i++){
for(int j = i+1; j< a.size(); j++){
if(Math.abs(a.get(i)-a.get(j)) <= 1){
counter++;
}
}
if(counter > max)
max = counter;
counter = 0;
}
return max+1;
}
While this one, gets a different output -
public static int pickingNumbers(List<Integer> a) {
// Write your code here
int max = 0;
int counter = 0;
Collections.sort(a);
for(int i = 0; i < a.size(); i++){
for(int j = i+1; j< a.size(); j++){
if(Math.abs(a.get(i)-a.get(j)) <= 1){
counter++;
}
}
if(counter > max){
max = counter;
counter = 0;
}
}
return max+1;
}
As you can see, the difference between the 2 codes are just the brackets after the if(counter > max) part. In the latter case, the counter is always 1 unit more than it should be.
Can anyone please explain it to me, why the code behaves different in this case?
It's because in the first snippet counter = 0; is not in the if block.
When if is not enclosed in brackets, it only evaluates the first instruction after it, so the counter = 0; is always executed.
Here's an example with better indentation:
public static int pickingNumbers(List<Integer> a)
{
int max = 0;
int counter = 0;
Collections.sort(a);
for(int i = 0; i < a.size(); i++)
{
for(int j = i+1; j< a.size(); j++)
{
if(Math.abs(a.get(i)-a.get(j)) <= 1)
{
counter++;
}
}
if(counter > max)
max = counter;
counter = 0; // Not in the if statement, so the counter is always reset!
}
return max+1;
}
const genObj = (ar) => {
let obj = {}
for(let i of ar) {
!(obj[i])? obj[i] = 1 : obj[i]++
}
return obj
}
function pickingNumbers(a) {
// Write your code here
let obj = genObj(a)
let k = Object.keys(genObj(a))
let i = 0
let max = 0
while (i <= k.length - 1) {
for(let j = i; j <= k.length - 1; j++){
if(i === j) continue
if(Math.abs(k[i] - k[j]) <= 1) {
if(obj[k[i]] + obj[k[j]] > max)
max = obj[k[i]] + obj[k[j]]
}
}
i++
}
return max > Math.max(...Object.values(obj)) ? max : Math.max(...Object.values(obj))
}
I tried to make method which inserts element at the specified position in this list.
Then Shifts the element & subsequent elements currently at that position to the
Right by adding one to their indices, i know there is shortcut for this method but I am suppose to do it, here what i tried to do but it's not working.
private T a[];
private int count;
private int size = 0;
public int size() { return size; }
public void add(int index,T t) throws Exception {
if (index < 0 || index > = a.length){
throw new IndexOutOfBoundsException();
}
Object[] temp = new Object[a.length + 1];
for (int k = 0, j = 0; j < temp.length; ++ k, ++ j){
if ( k == index ) {
temp[index] = t;
--k;
} else {
temp[j] = a[index]; //
}
}
a = (T[]) temp;
}
The trick to shifting is to start from the right, so:
for (int i = size; i > index; i--) {
a[i] = a[i - 1];
}
btw, when increasing size, normallyyou would double its size,rather than just growing by 1.
I corrected your 'for' block, try this:
for (int k = 0, j = 0; j < temp.length; ++k, ++j){
if ( k == index ) {
temp[index] = t;
--k;
index = -1;
} else {
temp[j] = a[k];
}
}
2 fixes i added:
index = -1; - In order to enter the if condition only 1 time, else it will constantly enter the condition
temp[j] = a[k]; - replaced to a[k], you was always taking value from a[index] means the same place, this is incorrect.
good luck :)
I have a selection sort implemented to sort an array of random integers. I would like the user to choose between ascending or descending order. The ascending sort works flawlessly, although descending does not. Here is what my selection sort looks like:
public String selection(int[] array,int num,String order) {
String output = "";
int min;
// This is the descending selection sort
if (order == "desc") {
for (int i = num - 1; i >= 0; i--) {
// Assume first element is min
min = i;
for (int j = i + 1; j < num; j++) {
if (array[j] < array[min]) {
min = j;
}
}
if (min != i) {
final int temp = array[i];
array[i] = array[min];
array[min] = temp;
}
output = output + Integer.toString(array[i]) + "\n";
}
} // This is the ascending selection sort
else {
for (int i = 0; i < num; i++) {
// Assume first element is min
min = i;
for (int j = i + 1; j < num; j++) {
if (array[j] < array[min]) {
min = j;
}
}
if (min != i) {
final int temp = array[i];
array[i] = array[min];
array[min] = temp;
}
output = output + Integer.toString(array[i]) + "\n";
}
}
return(output.trim());
}
I've seen a few questions similar to mine, although none of the questions I saw had their selection sort set up like this so I was unable to implement their solutions.
Firstly, the if blocks should compare to minPosition and maxPosition, not i. Secondly, if you are selecting both minimum and maximum, then your inner for loop should stop at a.length - i, not a.length (since the top i elements are also sorted). Doing both gives you this as the ascending order algorithm.
public static void SortAscending(int[] a){
for(int i = 0; i < a.length; i++){
int maxPosition=i;
int minPosition=i;
for(int j = i+1; j < a.length - i; j++){
if(a[j] < a[minPosition]){
minPosition = j;
}
if(a[j] > a[maxPosition]){
maxPosition = j;
}
}
/*
if(i < a.length/2-1)
*/
swap(a,maxPosition,i);
swap(a,minPosition,a.length-i-1);
}
}
To switch to descending order, simply add one line.
public static void SortDescending(int[] a){
for(int i = 0; i < a.length; i++){
int maxPosition=i;
int minPosition=i;
for(int j = i+1; j < a.length - i; j++){
if(a[j] < a[minPosition]){
minPosition = j;
}
if(a[j] > a[maxPosition]){
maxPosition = j;
}
}
/*
if(i < a.length/2-1)
*/
swap(a,minPosition,maxPosition); // <-- this line
swap(a,maxPosition,i);
swap(a,minPosition,a.length-i-1);
}
}
Use swap function https://www.geeksforgeeks.org/collections-swap-method-in-java-with-examples/
I was asked the below question in an interview:
Given an array of integers, write a method to find indices m and n such that
if you sorted elements m through n, the entire array would be sorted. Minimize
n-m. i.e. find smallest sequence.
find my answer below and please do comment on the solution. Thanks!!!
At last I have got a solution to the problem, please feel free to comment.
Lets take an example:
int a[] = {1,3,4,6,10,6,16,12,13,15,16,19,20,22,25}
Now if i will put this in to the graph (X-coordinate -> array index and Y-coordinate -> array's value) then the graph will look like as below:
Now if we see the graph there are two places where dip happens one is after 10 and another after 16. Now in the zig zag portion if we see the min value is 6 and max val is 16. So the portion which we should sort to make the whole array sorted is between (6,16). Please refer to the below image:
Now we can easily divide the array in to three part. And middle part the one which we want to sort so that the whole array will be sorted. Please provide your valuable inputs. I tried to explain to my label best, please let me know if i want to explain more. Waiting for valuable inputs.
The below code implements the above logic:
public void getMN(int[] a)
{
int min = Integer.MAX_VALUE; int max = Integer.MIN_VALUE;
for(int i=1; i<a.length; i++)
{
if(a[i]<a[i-1])
{
if(a[i-1] > max)
{
max = a[i-1];
}
if(a[i] < min)
{
min = a[i];
}
}
}
if(max == Integer.MIN_VALUE){System.out.println("Array already sorted!!!");}
int m =-1, n =-1;
for(int i=0; i<a.length; i++)
{
if(a[i]<=min)
{
m++;
}
else
{
m++;
break;
}
}
for(int i=a.length-1; i>=0; i--)
{
if(a[i]>=max)
{
n++;
}
else
{
n++;
break;
}
}
System.out.println(m +" : "+(a.length-1-n));
System.out.println(min +" : "+max);
}
It's easier to find the max value starting from the end of array:
public void FindMinSequenceToSort(int[] arr)
{
if(arr == null || arr.length == 0) return;
int m = 0, min = findMinVal(arr);
int n = arr.length - 1, max = findMaxVal(arr);
while(arr[m] < min)
{
m ++;
}
while(arr[n] > max)
{
n --;
}
System.out.println(m);
System.out.println(n);
}
private int findMinVal(int[] arr)
{
int min = Integer.MAX_VALUE;
for(int i = 1; i < arr.length; i++)
{
if(arr[i] < arr[i-1] && arr[i] < min)
{
min = arr[i];
}
}
return min;
}
private int findMaxVal(int[] arr)
{
int max = Integer.MIN_VALUE;
for(int i = arr.length - 2; i >= 0; i--)
{
if(arr[i] >= arr[i+1] && arr[i] > max)
{
max = arr[i];
}
}
return max;
}
Actually, I came up with something like that:
public static void sortMthroughN(int[] a)
{
int m = -1;
int n = -1;
int k = -1;
int l = -1;
int biggest;
int smallest;
// Loop through to find the start of the unsorted array.
for(int i = 0; i < a.length-1; i++)
if(a[i] > a[i+1]) {
m = i;
break;
}
// Loop back through to find the end of the unsorted array.
for(int i = a.length-2; i > 0; i--)
if(a[i] > a[i+1]) {
n = i;
break;
}
biggest = smallest = a[m];
// Find the biggest and the smallest integers in the unsorted array.
for(int i = m+1; i < n+1; i++) {
if(a[i] < smallest)
smallest = a[i];
if(a[i] > biggest)
biggest = a[i];
}
// Now, let's find the right places of the biggest and smallest integers.
for(int i = n; i < a.length-1; i++)
if(a[i+1] >= biggest) {
k = i+1; //1
break;
}
for(int i = m; i > 0; i--)
if(a[i-1] <= smallest) {
l = i-1; //2
break;
}
// After finding the right places of the biggest and the smallest integers
// in the unsorted array, these indices is going to be the m and n.
System.out.println("Start indice: " + l);
System.out.println("End indice: " + k);
}
But, I see that results are not the same with your solution #Trying, did i misunderstand the question? By the way, at the and of your code, it prints
4 : 9
6 : 16
What are these? Which ones are indices?
Thanks.
EDIT: by adding place marked as 1 this:
if(a[i+1] == biggest) {
k = i;
break;
}
and 2:
if(a[i+1] == smallest) {
l = i;
break;
}
it is better.
Actually, you can have two pointers and the last pointer moves backward to check start index of the shortest unsorted sequence. It's kind of O(N2) but it is more cleaner.
public static int[] findMinUnsortedSequence(int[] array) {
int firstStartIndex = 0;
int startIndex = 0;
int endIndex = 0;
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < i; j++) {
if (array[j] <= array[i]) {
startIndex = j + 1;
} else {
endIndex = i;
if (firstStartIndex == 0) {
firstStartIndex = startIndex;
}
}
}
}
return new int[]{firstStartIndex, endIndex};
}