Delete item from array in Java - java

What is wrong here? I want delete an item from an array, but it shows me
error ArrayIndexOutBound exception
public class delete {
public static void main(String[]args) {
int i;
//delete item from array
int k[] = new int[]{77,99,44,11,00,55,66,33,10};
//delete 55
int searchkey=55;
int nums=k.length;
for ( i=0;i<nums;i++)
if (k[i]==searchkey)
break;
for (int t=i;t<nums;t++)
k[t]=k[t+1];
nums--;
for (int m=0;m<nums;m++) {
System.out.println(k[m]);
}
}
}

for (int t=i;t<nums-1;t++) //Should be -1 here, as k[t+1] will be out of bounds if t = nums-1
Or another variant to nums-- before you move the numbers
nums--;
for (int t=i;t<nums;t++)
k[t]=k[t+1];

The following rewriting should be instructive:
public class Delete {
static int search(int key, int[] arr) {
for (int i = 0; i < arr.length; i++)
if (arr[i] == key) {
return i;
}
return -1;
}
static void print(int[] arr, final int L) {
for (int i = 0; i < L; i++) {
System.out.println(arr[i]);
// try this also:
// System.out.format("%02d ", arr[i]);
}
}
public static void main(String[] args) {
int nums[] = { 77, 99, 44, 11, 00, 55, 66, 33, 10 };
final int N = nums.length;
int searchKey = 55;
int pos = search(searchKey, nums);
for (int t = pos; t < N-1; t++) {
nums[t] = nums[t + 1];
}
print(nums, N-1);
// prints 77, 99, 44, 11, 0, 66, 33, 10
System.out.println(010 == 8); // prints "true"
System.out.println(00000); // prints "0
}
}
Here are some key observations:
Break apart logic into helper methods. This makes the logical components easier to test and reuse, and the overall logic easier to understand.
It makes the code easier to understand if you use final local variables like N to denote the initial size of int[] nums, and define the rest of the logic in terms of N, N-1, etc.
The more non-final variables there are, the harder it is to understand what's going on as their values changes over time
Follow coding convention. In particular, class names starts with uppercase.
Do be careful with the 00 in the array. The 0 prefix is for octal literals. That is, 010 == 8.
Do note that 00 is printed as simple 0. Numerically, 00 = 000 = 0000 = 0. If you need this to be zero-padded, then that's a formatting issue.
See also
On octal literals
09 is not recognized where as 9 is recognized
Integer with leading zeroes
On zero-padding
Left padding integers with zeros in Java

in the following loop
for (int t=i;t<nums;t++)
k[t]=k[t+1];
when t is pointing to the last element then k[t+1] operation will throw an exception which is what you are getting now.

On k[t]=k[t+1]; you got error es k[t+1] tries to access 10th element with index 9, but your array contains 9 elements. So you got data out of bounds.

It works if you use it as Draco Ater said:
for (int t=i;t<nums-1;t++) {
k[t]=k[t+1];
}
nums--;
Output is then:
77
99
44
11
0
66
33
10
which should be correct. ;-)

for (int t=i;t<nums;t++)
k[t]=k[t+1];
just replace nums with nums-1 because you have already deleted(skipped) one element.

I find it to work best in the following way:
Make sure the iteration does not go beyond the second last element (array.length-1) so it can have an element to compare to:
for(int i=elementPosition-1;i<array.length-1;i++){array[i]=array[i+1];}

import java.util.ArrayList;
import java.util.Arrays;
public class Sort {
public static void main(String a[]) {
int swap;
int length;
int[] unsorted = { 1, 2, 4, 3, 6, 5, 7, 8, 18, 17, 65, 46, 2, 4, 5, 3,
4 };
length = unsorted.length;
for (int i = 0; i < length; i++) {
for (int j = i + 1; j < length; j++) {
if (unsorted[i] > unsorted[j]) {
swap = unsorted[i];
unsorted[i] = unsorted[j];
unsorted[j] = swap;
} else if (unsorted[i] == unsorted[j]) {
for (int k = j; k < length - 1; k++) {
unsorted[k] = unsorted[k + 1];
}
length -= 1;
}
}
}
for (int i = 0; i < length; i++) {
System.out.println(" " + i + "th element " + unsorted[i]);
}
}
}

Related

I need to find the top 5 numbers in a 2D array of random numbers

I am pretty new to java and am just learning 2D arrays. I need to get the top 5 numbers and have tried everything I could think of. I was able to get the highest number using an If statement but am not able to get past that. I figured that I would try and get the second number and then move on to the rest. My friend said he got it done using for loops but I also could not get that to work. Any help would be appreciated. Thanks!
This is the code that I used:
package secondAssignment;
import java.util.Random;
public class BiggestNumbersRectangular {
public static void main(String[] args) {
Random rand = new Random();
int[][] arrSize = new int [4][5];
for (int i = 0; i < arrSize.length; i++) {
for (int j=0; j< arrSize.length; j++) {
arrSize[i][j] = rand.nextInt(89) + 10;
System.out.print(arrSize[i][j] + " ");
}
System.out.println();
}
int max = arrSize [0][0];
int largeNumTwo = arrSize [0][0];
for (int i = 0; i < arrSize.length; i++) {
for (int j = 0; j < arrSize.length; j++) {
if (max < arrSize[i][j]) {
max = arrSize [i][j];
if (largeNumTwo < max) {
arrSize [i][j] = largeNumTwo;
}
}
}
}
System.out.println("Highest Number: " + max);
System.out.println("Second Highest Number:" + largeNumTwo);
}
}
The output that I get is this:
45 10 44 70
36 87 35 38
68 14 30 79
34 69 50 92
Highest Number: 92
Second Highest Number:45
The code that I used for the second number is outputting only the first randomly generated number.
I am not sure how to fix this.
If you're allowed to use a List, then I'd do it this way.
There's nothing terribly fancy in here:
import java.util.*;
class Main {
public static void main(String[] args) {
Random rand = new Random();
int[][] arrSize = new int [4][5];
for (int row = 0; row < arrSize.length; row++) {
for (int col=0; col < arrSize[row].length; col++) {
arrSize[row][col] = rand.nextInt(89) + 10;
}
}
displayArray(arrSize);
List<Integer> top5 = new ArrayList();
for (int row = 0; row < arrSize.length; row++) {
for (int col=0; col < arrSize[row].length; col++) {
int current = arrSize[row][col];
// see if current is larger than anything in top5
boolean added = false;
for(int i=0; i<top5.size() && !added; i++) {
if (current >= top5.get(i)) {
// insert new top 5 number in correct spot
top5.add(i, current);
added = true;
}
}
if (!added && top5.size() < 5) {
top5.add(current); // add it to the end
}
else if (added && top5.size() > 5) {
top5.remove(top5.size() - 1); // remove 6th largest
}
}
}
// display the top 5 numbers from the 2D array
for(int i=0; i<top5.size(); i++) {
System.out.println("#" + (i+1) + ": " + top5.get(i));
}
}
public static void displayArray(int[][] numbers) {
for(int[] row : numbers) {
System.out.println(Arrays.toString(row));
}
}
}
Sample run:
[38, 63, 19, 17, 11]
[49, 42, 98, 71, 32]
[54, 74, 89, 44, 56]
[56, 91, 52, 72, 49]
#1: 98
#2: 91
#3: 89
#4: 74
#5: 72
This is basically the same approach that Javohir Xoldorov took, but the code is a little easier to understand because we can easily add, insert, and delete elements from a List without having to manually shift everything like you would in an Array.
Maybe you can see this solution.
Approach:
you can declare five variable but then You will use most if so we can:
Declare static array size = 5
Fill array which possible min val INT_MIN
We get one element given matrix and compare five element If which element < firstArray[i] then it changed and before matrix element one step move right side
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Random rand = new Random();
int[][] arr = new int[4][5];
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr.length; j++) {
arr[i][j] = rand.nextInt(89) + 10;
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
int[] max_element = new int[5];
for (int i = 0; i < max_element.length; i++) {
max_element[i] = Integer.MIN_VALUE;
}
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
for (int k = 0; k < max_element.length; k++) {
if (max_element[k] < arr[i][j]) {
int before = max_element[k], current;
for (int z = k + 1; z < max_element.length; z++) {
current = max_element[z];
max_element[z] = before;
before = current;
}
max_element[k] = arr[i][j];
break;
}
}
}
}
for (int i = 0; i < max_element.length; i++) {
System.out.println((i + 1) + " Highest Number: " + max_element[i]);
}
}
}
UPDATE 2: After testing, I changed my algorithm now finally to work really correctly if the highest value of all is contained within the first five entries. And I produced code:
package examples.stackoverflow.q75461466;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
public class Q75461466 {
public static void main(String[] args) {
int[][] myArray = initRandomArray(4, 5, 79, 10);
// for testing it's better to work with a fixed dataset
// int[][] myArray = {{94, 61, 17, 27, 67}, {68, 74, 46, 61, 98}, {42, 79, 95, 77, 39}, {41, 42, 97, 50, 76}};
System.out.print("Original data: ");
System.out.println(Arrays.deepToString(myArray));
List<Integer> topFive = new ArrayList<>();
Integer min = Integer.MIN_VALUE;
for (int[] row : myArray) {
for (int value : row) {
if ((value > min) || topFive.size() < 5) {
topFive.add(value);
if (topFive.size() > 5) {
topFive.remove(min);
}
min = topFive.stream().min(Integer::compareTo).orElse(Integer.MIN_VALUE);
}
}
}
System.out.print("The 5 highest numbers are: ");
System.out.println(topFive);
}
private static int[][] initRandomArray(int height, int width, int upper, int lower) {
int[][] randomArray = new int[height][width];
Random rand = new Random();
for (int row = 0; row < randomArray.length; row++) {
for (int col = 0; col < randomArray[row].length; col++) {
randomArray[row][col] = rand.nextInt(upper + lower) + lower;
}
}
return randomArray;
}
}
First the array is initialized and filled with data in the method initRandomArray. Please note that for testing it is better if you work with a fixed array, it will get you reproducible results where you also can simulate "problematic" cases.
Then the list topFive is used - a name a bit misleading, because it does not contain five elements all the time.
I loop over all the entries in the arrays with two nested loops (the code is written to be independent of the actual array dimensions, otherwise further optimizations could have been done).
Array indexes are not necessary, the for-each variant is sufficient, as I only need each value once.
I make sure that the first five entries are always put into the topFive list, and I always track the minimum value inside that list (in min). For this I use a bit "stream magic", the orElse(Integer.MIN_VALUE) in the end is needed since the min method returns an Optional in the case the list is empty. Should never happen in this algorithm, but the Optional has to be handled properly.
After five values are in the list, it is relevant if the next input value is bigger than the smallest value already in the list - if so, then the input value is added to the list, and the current minimum value is removed.
The new minimum value has to be calculated, as the value just inserted is not necessarily the new minimum.
After all values of the arrays have been processed, the list contains five values at maximum, so it can be directly output as the result.
The resulting list will not be sorted, but will contain the values in the order of their first occurrence.
In the case that the first five input values contain a value more than once, it is possible that the output list contains the same value also more than once.
I'd suggest doing this using Java's PriorityQueue class. While it might be overkill for 5 items, it's quite straightforward to use and will perform extremely well for larger target sets.
The default constructor gives a min priority queue, which is exactly what we want. Add the first desiredQty items to the priority queue. The minimum of those will be at the front of the queue, and can be inspected using peek(). For all subsequent values in the array, compare them to the current minimum value. If the new value is larger than the current minimum, toss the min and add the current value. When you get to the end of the array the priority queue will contain the desiredQty largest values, so you can just iterate through and print them (or do whatever else suits your fancy).
import java.util.Arrays;
import java.util.Random;
import java.util.PriorityQueue;
class Top5 {
public static void main(String[] args) {
Random rand = new Random();
PriorityQueue<Integer> pq = new PriorityQueue<Integer>();
int[][] arr = new int [4][5];
int desiredQty = 5;
for (int row = 0; row < arr.length; row++) {
for (int col=0; col < arr[row].length; col++) {
arr[row][col] = rand.nextInt(89) + 10;
if (pq.size() < desiredQty) {
// If we don't yet have desiredQty items, just add the latest one to pq.
pq.add(arr[row][col]);
} else {
// If pq has the desiredQty and the latest value is bigger than
// the current min, remove the min and add the latest value.
if (arr[row][col] > pq.peek()) {
pq.poll();
pq.add(arr[row][col]);
}
}
}
System.out.println(Arrays.toString(arr[row]));
}
System.out.println("\n" + desiredQty + " largest values are:");
System.out.println(Arrays.toString(pq.toArray()));
}
}
Sample output:
[55, 82, 92, 93, 79]
[84, 26, 78, 87, 23]
[49, 67, 76, 37, 18]
[12, 39, 54, 38, 68]
5 largest values are:
[82, 84, 92, 93, 87]

Getting java.lang.NullPointerException while returning an array of integers in java

public class Omit {
int[] omitnum(int[] a) {
int[] arr = null;
for (int i = 0; i <= 7; i++) {
if (a[i] >= 13 && a[i] <= 19) {
System.out.print(a[i]);
} else {
arr[i] = a[i];
}
}
return arr;
}
public static void main(String[] args) {
Omit c = new Omit();
int[] a = {
1,
2,
3,
12,
113,
14,
19,
20
};
int[] b = null;
b = c.omitnum(a);
for (int i = 0; i <= 7; i++) {
System.out.println(b[i]);
}
}
}
}
Getting this error while running Exception in thread "main"
java.lang.NullPointerException
at omit.Omit.omitnum(Omit.java:20)
at omit.Omit.main(Omit.java:28)
Initialized an array to return some values but it isn't returning any values and giving null error
From the stack trace you posted in your question, line 20 in file Omit.java is throwing NullPointerException. Which line is line 20 in class Omit.java? Could it be this line:
arr[i] = a[i];
That would mean that either arr is null or a is null. If you debug your program, you will discover which of them is null. (Perhaps both are null?)
Any decent java IDE includes a debugger. Decent java IDE's include Intellij, Eclipse, NetBeans and JDeveloper. I also suggest you read How to debug small programs
Nonetheless, I see in this line of your code (which is the first line in method omitnum()) that you are explicitly setting local method variable arr to null:
int[] arr = null;
After that line you never assign a different value to arr and hence, when you get to this line:
arr[i] = a[i];
the variable arr is still null and hence the NullPointerException. Refer to this stackoverflow question: What is a NullPointerException, and how do I fix it?
You need to initialize an array before you can use it. If you Google for the terms java initialize array, you will get several million results, including Initializing Arrays in Java.
You should initialize an array before you are using it.
Else you can get NullPointerException.
Instead of this:
int[] arr = null;
You can use this:
int[] arr = new int[a.length];
You get NullPointerException meaning you try to access some variable that is null.
In java you need to initialize arrays before you can use them, and in your code you just set arr = null so this is why it's not working.
If you want it to work just define arr properly like:
int[] arr = new int[a.length];
That error means you are assigning to a null pointer,
you could write arr[a.length] but that would allocate
memory for more elements than you actually need, because
you need to only store according to a condition,
that way you should do it like this:
public class Omit {
int[] omitnum(int[] a) {
int maxNum = 0;
// calculate how much memory needed
for(int i = 0;i < a.length; i++) {
if(!(a[i] >= 13 && a[i] <= 19)) {
maxNum++;
}
}
// --------------------------------
int[] arr = new int[maxNum];
for(int i = 0, j = 0; i < a.length; i++) {
if(a[i] >= 13 && a[i] <= 19) {
System.out.println("Deleted: " + a[i]);
}else {
/* we can't use `i` because that would gives an error
because arr has less elements than a :) */
arr[j++] = a[i];
}
}
return arr;
}
public static void main(String[] args) {
Omit c = new Omit();
int[] a = {1, 2, 3, 12, 113, 14, 19, 20};
int[] b = c.omitnum(a);
for(int i = 0; i < b.length; i++) {
System.out.println(b[i]);
}
}
}
Output:
Deleted: 14
Deleted: 19
1
2
3
12
113
20
and array.length gives you flexibility instead of
looping to a static position, to avoid changing
your code each time you add or remove elements,
and from counting of course
Here is another way using ArrayLists
import java.util.ArrayList;
public class Omit {
ArrayList omitnum(int[] a) {
ArrayList<Integer> arr = new ArrayList<Integer>();
for(int i = 0; i < a.length; i++) {
if(a[i] >= 13 && a[i] <= 19) {
System.out.println("Deleted: " + a[i]);
}else {
arr.add(a[i]);
}
}
return arr;
}
public static void main(String[] args) {
Omit c = new Omit();
int[] a = {1, 2, 3, 12, 113, 14, 19, 20};
ArrayList b = c.omitnum(a);
for(int i = 0, n = b.size(); i < n; i++) {
System.out.println(b.get(i));
}
}
}
Output:
Deleted: 14
Deleted: 19
1
2
3
12
113
20
Here is another way suggested by the user Abra, but I made
some changes to preserve the default behaviour of printing
import java.util.Arrays;
public class Omit {
static boolean printN(int n) {
System.out.println("Deleted: " + Integer.toString(n));
return false;
}
public static void main(String[] args) {
int[] a = {1, 2, 3, 12, 113, 14, 19, 20};
int[] b = Arrays.stream(a).filter(n -> n < 13 || n > 19 ||
printN(n)).toArray();
for(int i = 0;i < b.length; i++) {
System.out.println(b[i]);
}
}
}
Output:
Deleted: 14
Deleted: 19
1
2
3
12
113
20

Java remove odd number from an mixed array

why isn't this code working?
I'm supposed to write a function which removes the odd numbers from an array. here is my code but I don't know where it went wrong. It's giving me an error.
public class Test{
public static int [] removeOdd(int[] input){
int c = 0;
for(int i=0; i<input.length; i++){
if(input[i]%2==0){
c++;
}
}
int [] a = new int[c];
for(int i=0; i<input.length; i++){
if(input[i]%2==0){
a[i] = input[i];
}
}
return a;
}
public static void main(String [] args){
int [] mixedArray = {21, 33, 44, 66, 11, 1, 88, 45, 10, 9};
for (int i = 0; i < mixedArray.length; i++) {
System.out.print(mixedArray[i] + " ");
}
System.out.println();
int [] noOdd = Test.removeOdd(mixedArray);
for (int i = 0; i < noOdd.length; i++) {
System.out.print(noOdd[i] + " ");
}
}
Thanks in advance :)
You need another index variable to access the items of a and not use i:
public static int [] removeOdd(int[] input){
int c = 0;
for(int i=0; i<input.length; i++){
if(input[i]%2==0){
c++;
}
}
int [] a = new int[c];
int k = 0;
for(int i=0; i<input.length; i++){
if(input[i]%2==0){
a[k] = input[i];
k++;
}
}
return a;
}
The index variable i iterates through input and its values do not match and will exceed the permitted values of the indexes of a so I have used k.
The problem is here:
int [] a = new int[c];
for(int i=0; i<input.length; i++){
if(input[i]%2==0){
a[i] = input[i];
}
}
This loop will iterate through the whole input array, and try to insert just the even ones into a, but a is smaller than input, because you allocated space equal to the amount of just the even numbers in input.
In your test case, your a will have size 4, but will try to access the position 6, giving you an out of bound exception.
The problem is that you are trying to insert at a[i] which you could visualise like this:
index: 0 1 2 3 4
input: [1 2 3 4 5]
a: [ 2 4 ]
However, your a array is smaller than your input array, because you have reduced the size to account for the lack of odd numbers. You actually want to do this:
index: 0 1 2 3 4
input [1 2 3 4 5]
a [2 4]
Notice how the index of both even numbers has changed. You were trying to keep it the same.
One way to solve this would be to keep a separate counter variable which tracks where you're up when inserting into a.
int[] a = new int[c];
int sizeOfA = 0;
for (int i = 0; i < input.length; i++)
{
if (input[i] % 2 == 0)
{
a[sizeOfA] = input[i];
sizeOfA++;
}
}
You can simplify the method removeOdd using Streams:
import java.util.Arrays;
public class Test {
public static int[] removeOdd(int[] input) {
return Arrays.stream(input).filter(i -> i % 2 == 0).toArray();
}
public static void main(String[] args) {
int[] mixedArray = { 21, 33, 44, 66, 11, 1, 88, 45, 10, 9 };
for (int i = 0; i < mixedArray.length; i++) {
System.out.print(mixedArray[i] + " ");
}
System.out.println();
int[] noOdd = Test.removeOdd(mixedArray);
for (int i = 0; i < noOdd.length; i++) {
System.out.print(noOdd[i] + " ");
}
}
}

Merge K sorted arrays

I am given k sorted arrays and need to merge them into one sorted array. We are assuming that n is the total number of elements in all the input arrays and that k=3.
public class Merge {
// Create a mergeklists() to merge 3 sorted arrays into one sorted array
// Input: 3 sorted arrays a1[], a2[], a3[]
// Output: one sorted array a[] that contains all the elements from input arrays
public static void merge3lists(int[] a1, int[] a2, int[] a3, int[] a)
{
int i=0;
int j=0;
int h=0;
int n = a1.length + a2.length + a3.length;
for(int k; a.length < n-1; k++){
if(a1[i] < a2[j]){
k = a1[i];
i++;
}
else if(a2[j] < a3[h]){
k = a2[j];
j++;
}
else{
k = a3[h];
h++;
}
}
}
public static void main(String[] args) {
int[] l1 = {1,5,9,10,20};
int[] l2 = {2,4,5,6,7,9,15};
int[] l3 = {3,8,13,15,22};
int[] newl = new int[l1.length+l2.length+l3.length];
merge3lists(l1,l2,l3,newl);
for(int i = 0; i< newl.length; i++)
{
System.out.print(newl[i]+ " ");
}
}
}
I know that the integers I am using (I,j,and h) are messing up the problem, but I don't think I can use i while comparing all the arrays. I need to use the declared array a, but I'm not sure how to reference it in this case.
To have to method merge an arbitrary number of arrays (k), you need to make the method use varargs.
It would also be better to have the method create the result array for you.
You then loop until the result array is filled. For each iteration, you find the smallest of the next value from each source array, and add that to the result array, and step forward in the source array you picked the value from.
Like this:
public static int[] mergeArrays(int[]... arrays) {
// Create result array
int n = 0;
for (int[] a : arrays)
n += a.length;
int[] result = new int[n];
// Start at index 0 in each source array
int[] idx = new int[arrays.length];
// Merge source arrays into result array
for (int i = 0; i < n; i++) {
// Find smallest value
int minJ = -1, minVal = 0;
for (int j = 0; j < arrays.length; j++) {
if (idx[j] < arrays[j].length) {
int val = arrays[j][idx[j]];
if (minJ == -1 || val < minVal) {
minJ = j;
minVal = val;
}
}
}
// Add to result array and step forward in appropriate source array
result[i] = minVal;
idx[minJ]++;
}
return result;
}
Test
int[] merged = mergeArrays(new int[] { 23, 39, 63, 68 },
new int[] { 11, 21, 76 },
new int[] { 5, 10, 37, 80 },
new int[] { 30, 49, 50, 94 },
new int[] { 13, 25, 48 });
System.out.println(Arrays.toString(merged));
Output
[5, 10, 11, 13, 21, 23, 25, 30, 37, 39, 48, 49, 50, 63, 68, 76, 80, 94]
Looks like a preparation exercise to motivate the introduction of array of arrays :)
Number the indices analogous to the lists to avoid confusion.
Identify the list with the smallest element at its current index. Avoid reading beyond the end of the array, as it will result in an exception.
Take this element and proceed.
int i1=0;
int i2=0;
int i3=0;
int n = a1.length + a2.length + a3.length;
for( int k = 0; k < n; k++) {
int advance = 0;
int value = Integer.MAX_VALUE;
if (i1 < a1.length && a1[i1] <= value) {
advance = 1;
value = a1[i1];
}
if (i2 < a2.length && a2[i2] <= value) {
advance = 2;
value = a2[i2];
}
if (i3 < a3.length && a3[i3] <= value) {
advance = 3;
value = a3[i3];
}
a[k] = value;
switch(advance) {
case 1: i1++; break;
case 2: i2++; break;
case 3: i3++; break;
}
}
A more efficient algorithm is to use a min-heap.
The algorithm is roughly described as follows:
First, construct a min-heap of size k (in this case size 3 for the three lists) taking the minimum elements in each list. You would then delete then the minimum element from the heap (noting which list it came from), add it to your newly constructed list, and then insert the next element from that same list which it was initially drawn from.
The time complexity would drop from O(n * k) to O(n * log(k)). Where n is the total number of elements in the final sorted list.
https://cs.stackexchange.com/questions/12853/heap-give-an-on-lg-k-time-algorithm-to-merge-k-sorted-lists-into-one-so

How to get a sequence of 5 numbers from an array

I want to get a sequence of 5 numbers from an array.
For example :
int arr1[] = {3,88,99,5,4,6,22,32,7,45}; // array where there is the sequence 3,4,5,6,7
Vector<Integer> myVec = new Vector<Integer>(); // vector wehre to save the sequence
Now what do I have to do to get the sequence from that array?
I have a code here but it does not work properly:
for(int i = 0; i < arr1.length -1; i++) {
int a = arr1[i];
int b = arr1[i+1];
int c = b - a;
if(c == 1) {
myvec.add(arr1[i]);
}
}
How should I change my code to solve this?
This program will print all the sequence in the array WITHOUT SORTING THE ARRAY. You could select the list with size.. Say if you want match 5 sequence get the list with size 5. Hope this help. (Modify as per your need.)
import java.util.ArrayList;
import java.util.List;
public class Sequence {
private static int arr1[] = { 3, 88, 99, 5, 4, 6, 22, 32, 7, 45 };
private static int findNextInSequence(int start) {
int next = -1;
for(int i = 0; i < arr1.length; i++){
if((start - arr1[i]) == -1){
next = arr1[i];
}
}
return next;
}
public static void main(String[] args) {
for (int i = 0; i < arr1.length; i++) {
List<Integer> sequence = new ArrayList<Integer>();
int nextSequence = arr1[i];
do{
sequence.add(nextSequence);
nextSequence = findNextInSequence(nextSequence);
} while(nextSequence != -1);
System.out.println(sequence);
}
}
}
Your code checks the difference between two successive values from arr1 array. Because it is not sorted, it works like this:
88-3 !=1 (value not added)
99-88 !=1 (value not added)
5-99 !=1 (value not added)
...
45-7 !=1 (value not added).
You have to ensure that values in your array are sorted first. Use Arrays.sort() and apply the method on sorted array. This should add values: 3,4,5,6, but it WON'T add 7 (because it'll be your arr[i+1] value at the time of loop execution.
4-3 ==1 (value added)
5-4 ==1 (value added)
6-5 ==1 (value added)
7-6 ==1 (value added, but it is only number 6 that is added!)
You should count successive count upto 5 and put the result into ArrayList instead of Vector. Because, ArrayList is more efficient than Vector. Try,
int arr1[] = {3, 88, 99, 5, 4, 6, 22, 32, 7, 45, 11, 12, 13, 14, 15};
List<Integer> myVec = new ArrayList<>();
Arrays.sort(arr1);
int count = 0;
int lastValue = 0;
for (int i = 0; i < arr1.length - 1; i++) {
if (arr1[i + 1] - arr1[i] == 1) {
count++;
System.out.println(arr1[i]);
lastValue = arr1[i + 1];
} else {
System.out.println(count);
if (count >= 4) {
for (int j = 0; j <= count; j++) {
myVec.add(lastValue - 4 + j);
}
}
count = 0;
}
}
System.out.println(myVec);

Categories

Resources