I have to create a method, that returns an array with common elements from two different arrays. I am aware there are lots of questions about this, but mine is a little bit different from those as I have to create a new array.
I've tried to first count how many common elements there are from two arrays, and then create an array with size the number of that.
After, I tried to set the new array to the common elements using a for loop.
public static int [] commonElements(int []a, int [] b){
int count=0;
for(int i=0;i<a.length;i++) {
for(int j=0;j<b.length;j++) {
if(a[i] == b[j]) {
count++;
}
}
}
int []array= new int[count];
for(int i=0;i<a.length;i++) {
for(int j=0;j<b.length;j++) {
if(a[i] == b[j]) {
for (int k=0; k<count; k++){
array[k]=a[i];
}
}
}
}
return array;
}
This returns four -1's, so it doesn't work.
I am also required not to use arraylist, so I have no idea how to make this code complete.
The expected value with
// checking common elements
System.out.println ("\nLooking for common elements in the arrays ");
int [] arr3= {56, -21, -5, 7, 10, 21, 2, -1};
int [] arr4= {-1, -56, 5, 21, 3 , 7, 4, -6, 2, 90};
int [] result4 = commonElements(arr3, arr4);
System.out.println (Arrays.toString(arr3));
System.out.println (Arrays.toString(arr4));
System.out.print ("\nCommon elements array: ");
System.out.println (Arrays.toString(result4));
in the main is
Looking for common elements in the arrays
[56, -21, -5, 7, 10, 21, 2, -1]
[-1, -56, 5, 21, 3, 7, 4, -6, 2, 90]
Common elements array: [7, 21, 2, -1]
Any help would be greatly appreciated!
You might want to use a list to store the intermediate intersecting values, and then convert to an array at the end of the method:
public static int[] commonElements(int[] a, int[] b) {
List<Integer> common = new ArrayList<>();
for (int i=0; i < a.length; i++) {
for(int j=0; j < b.length; j++) {
if (a[i] == b[j]) {
common.add(a[i]);
}
}
}
int[] array = common.stream().mapToInt(Integer::intValue).toArray();
return array;
}
If you don't want to record duplicates, then replace common with Set<Integer>.
First, instead of int []array= new array[count]; you need new int[count]; - second, instead of a third inner loop when populating your output keep a position index and increment it when you encounter a duplicate. Like,
public static int[] commonElements(int[] a, int[] b) {
int count = 0;
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < b.length; j++) {
if (a[i] == b[j]) {
count++;
}
}
}
int[] array = new int[count];
int p = 0;
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < b.length; j++) {
if (a[i] == b[j]) {
array[p] = a[i];
p++;
}
}
}
return array;
}
Alternatively, if using Java 8+, the above can be simplified by filtering on an IntStream of the two arrays. Like,
return Arrays.stream(a).filter(i -> Arrays.stream(b).anyMatch(x -> x == i))
.toArray();
Related
The method I have to create should take as parameter an array of integers and return the integer array with its contents sorted in descending order — largest to smallest.
Note - no libraries should be used in your implementation for this method.
I've attempted to use a regular selection sort and using a swap at the end but syntax errors just occurred:
public static int[] reverseSelectionSort(int[] arrayToBeSorted) {
// implementation of Task 3 goes here
for(int i = 0; i < arrayToBeSorted.length; i++){
int maxPosition=i;
int minPosition=i;
for(int j = i+1; j < arrayToBeSorted.length - i; j++){
if(arrayToBeSorted[j] < arrayToBeSorted[minPosition]){
minPosition = j;
}
if(arrayToBeSorted[j] > arrayToBeSorted[maxPosition]){
maxPosition = j;
}
}
swap(arrayToBeSorted,minPosition,maxPosition);
swap(arrayToBeSorted,maxPosition,i);
swap(arrayToBeSorted,minPosition,arrayToBeSorted.length-i-1);
}
return arrayToBeSorted; // change this to return the sorted array
}
public static void main(String[] args) {
int[] array2 = {3, 6, 8, 3, 5, 7, 1};
int[] sorted = reverseSelectionSort(array2);
System.out.print("task: [");
for (int i = 0; i < sorted.length; i++) {
if (i > 0) {
System.out.print(", ");
}
System.out.print(sorted[i]);
}
System.out.println("]");
}
If you call the method on the array [3, 6, 8,
3, 5, 7, 1], then the method should return the array [8, 7, 6, 5, 3, 3, 1].
Once you add the implementation of swap to your code (and put it all inside a class), it produces exactly the output you wanted it to. Maybe you thought swap was a java uitl, which it is for Collections, but an array is not a Collection.
So very little has changed in the below:
public class soSelect{ //embed in class, added
public static int[] reverseSelectionSort(int[] arrayToBeSorted) {
// implementation of Task 3 goes here
for(int i = 0; i < arrayToBeSorted.length; i++){
int maxPosition=i;
int minPosition=i;
for(int j = i+1; j < arrayToBeSorted.length - i; j++){
if(arrayToBeSorted[j] < arrayToBeSorted[minPosition]){
minPosition = j;
}
if(arrayToBeSorted[j] > arrayToBeSorted[maxPosition]){
maxPosition = j;
}
}
swap(arrayToBeSorted,minPosition,maxPosition);
swap(arrayToBeSorted,maxPosition,i);
swap(arrayToBeSorted,minPosition,arrayToBeSorted.length-i-1);
}
return arrayToBeSorted; // change this to return the sorted array
}
public static void swap(int[] a, int i, int j){ //had to implement it
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
public static void main(String[] args) {
int[] array2 = {3, 6, 8, 3, 5, 7, 1};
int[] sorted = reverseSelectionSort(array2);
System.out.print("task: [");
for (int i = 0; i < sorted.length; i++) {
if (i > 0) {
System.out.print(", ");
}
System.out.print(sorted[i]);
}
System.out.println("]");
}
}//added outer brace
I ran it in java doodle and it printed:
task: [8, 7, 6, 5, 3, 3, 1]
I did not test beyond that, but this should at least get you unstuck, or, at best, finished. For sure you could compare with the implementation to which the above comment points you.
I'm trying to write a method that takes a sorted array and an integer, creates a new array that is 1 size larger, and inserts the new integer and keeps it sorted.
I've tried a few different implementations and had them to work - but for this specific one, I can't grasp where it's going wrong.
int[] array1 = new int[]{1, 2, 3, 4, 6, 7, 8};
int[] printArray = insert(array1, 5);
are the arrays, and the method is
public static int[] insert(int[] a, int k) {
int[] s = new int[a.length + 1];
for(int i = 0; i < a.length; i++) {
if(k < s[i]) {
s[i] = k;
for(int j = i + 1; j < s.length; j++) {
s[j] = a[i];
i++;
}
return s;
} else {
s[i] = a[i];
}
}
return s;
}
This method prints out 1, 2, 3, 4, 6, 7, 8, 0, instead of 1, 2, 3, 4, 5, 6, 7, 8.
Change
if(k < s[i]) {
to
if(k < a[i]) {
in line 4.
Actually in the following line you are creating an array with all elements zero:
int[] s = new int[a.length + 1];
s[0] to s[7] will be 0.
Your loop counter i runs from 0 to a.length but the point to note is all the elements of array s will be zero. You are comparing k with s[i] which is zero and for that reason the shifting of arrays never happen (if block never executes).
You need to do two things to fix it.
Initialize element zero of s with the value of a[0].
Compare element with previous element to figure out position to insert.
The final code is:
public static int[] insert(int[] a, int k) {
int[] s = new int[a.length + 1];
s[0] = a[0];
for(int i = 1; i < a.length; i++) {
if(k < s[i-1]) {
s[i] = k;
for(int j = i + 1; j < s.length; j++) {
s[j] = a[i];
i++;
}
return s;
} else {
s[i] = a[i];
}
}
return s;
}
Now you will get:
[1, 2, 3, 4, 6, 5, 7, 8]
I would start by using Arrays.copyOf(int[], int) to create a new array that is one larger than the input. Then iterate that array until I reached the index that the new value belongs at. Then use System.arraycopy(Object,int,Object,int,int) to copy the values into the end of the array. That might look something like
public static int[] insert(int[] a, int k) {
int[] s = Arrays.copyOf(a, a.length + 1);
for (int i = 0; i < s.length; i++) {
if (a[i] < k) {
continue;
}
System.arraycopy(a, i, s, i + 1, s.length - i - 1);
s[i] = k;
break;
}
return s;
}
Which I tested with Arrays.toString(int[]) like
public static void main(String s[]) throws IOException {
int[] array1 = new int[] { 1, 2, 3, 4, 6, 7, 8 };
int[] printArray = insert(array1, 5);
System.out.println(Arrays.toString(printArray));
}
And I get the (expected)
[1, 2, 3, 4, 5, 6, 7, 8]
I am encountering some slight and stupid issue while trying to sort out my arrays.
So here's what I'm doing and what I want to do :
I generate an array of ints (good ol' t = new int[];) filled with random generated numbers from -1 to 9. The size of the array is irrelevant. I would like to make so that each "-1" will get to the end of the array while every other will get "pushed" to take the place.
As I'm not a native english speaker it's really hard to express myself correctly on this.
Example :
my array is : 9 2 -1 4 6 -1
I want : 9 2 4 6 -1 -1
I currrently managed to get this BUT it won't work if there are two consecutives -1 cause the second one will get swapped.
Ex :
Initial : 9 2 -1 -1 4 6
After modif : 9 2 -1 4 6 -1
As I said the problem is probably really near from being solved but I really can't find a fix right now.
Here's my code :
for(int i=0;i<NB_CARD;i++)
{
t[i]=randomGenerator.nextInt(10)-1;
System.out.print("t["+i+"]= "+t[i]+"\t\t");
if(i==4){System.out.println("");}
}
//each -1 should be at the end of array
for(int i=0;i<NB_CARD;i++)
{
int tmp=0;
if(t[i]==-1)
{
for(int y=i;y<NB_CARD-1;y++)
{
tmp=t[y+1];
t[y+1]=t[y];
t[y]=tmp;
}
}
}
for(int i=0;i<NB_CARD;i++)
{
System.out.print("t["+i+"]= "+t[i]+"\t\t");
if(i==4){System.out.println("");}
}
Thank you in advance for every tip/help that could lead me to solve this
A more efficient way of doing this with one loop is.
int j = 0;
// copy all the non -1 values down.
for (int i = 0; i < NB_CARD; i++)
if (t[i] != -1)
t[j++] = t[i];
// fill the rest with -1
Arrays.fill(t, j, NB_CARD, -1);
if NB_CARD == t.length you can do
int[] t = {3, -1, -1, -1, 4, 5, 6, -1, -1};
int j = 0;
// copy all the non -1 values down.
for (int i : t)
if (i != -1)
t[j++] = i;
// fill the rest with -1
Arrays.fill(t, j, t.length, -1);
System.out.println(Arrays.toString(t));
prints
[3, 4, 5, 6, -1, -1, -1, -1, -1]
In Java 8 you can do this
int[] t = {6, -1, -1, -1, 4, 5, 3, -1, -1};
List<Integer> sorted = IntStream.of(t).boxed()
.sorted((a, b) -> (a > -1 ? 1 : 0) - (b > -1 ? 1 : 0))
.collect(Collectors.toList());
for (int i = 0; i < t.length; i++)
t[i] = sorted.get(i);
System.out.println(Arrays.toString(t));
which prints
[6, 4, 5, 3, -1, -1, -1, -1, -1]
though it is O(N log N) instead of O(N) and has more code.
I'd use Arrays.sort(T[] a, Comparator c), supplying your own Comparator that puts -1 at the end of the output.
Using bubble sort
package com.appkart.collections;
import java.util.Random;
public class Test {
public void fillRandomNumber(int a[]) {
Random random = new Random();
for (int i = 0; i < a.length; i++) {
a[i] = random.nextInt(10)-1;
}
}
public void printNumber(int a[]) {
for (int i = 0 ; i < a.length ;i++) {
System.out.print(a[i] +" ");
}
}
//Using bubble sort
public void sortRandomNumber(int a[]) {
int length = a.length;
int temp;
for (int i = 0; i < length; i++) {
for (int j = 1; j < length - i; j++) {
if (a[j - 1] < a[j]) {
temp = a[j - 1];
a[j - 1] = a[j];
a[j] = temp;
}
}
}
}
public static void main(String[] args) {
int a[] = new int[10];
Test test = new Test();
test.fillRandomNumber(a);
System.out.println("Random Number bofore sort");
test.printNumber(a);
test.sortRandomNumber(a);
System.out.println("\n Random Number after sort");
test.printNumber(a);
}
}
You can use something like this:
int[] a = { 9, 2, -1, 4, 6, -1 };
for(int i=a.length-1; i>0; i--)
{
for(int j=0; j<i; j++)
{
if(a[i] < a[j])
{
int jvalue = a[j];
a[j] = a[i];
a[i] = jvalue;
}
}
}
If I am understanding the code correctly, if you find a -1, you eventually bubble it up to the end.
What you could do, would be to store the location of the current last element, which at the beginning would be n - 1.
When you find a -1, you could replace the ith element with the current last element and then, decrease the value of current by 1. This should allow you to always put any new -1 elements you encounter at the end.
Code wise:
int[] t = new int[5];
t[0] = -1; t[1] = -1; t[2] = 4;
t[3] = -1; //Just for demonstration purposes
t[4] = -1; //Just for demonstration purposes
int currentLast = 0;
for(int i = t.length - 1; i >=0; i--)
{
if(t[i] == -1)
currentLast = i - 1;
else
break;
}
for(int i = 0; i < t.length; i++)
System.out.println(t[i]);
System.out.println("After");
for(int i = 0; i < currentLast; i++)
{
if(t[i] == -1)
{
int temp = t[currentLast];
t[currentLast] = t[i];
t[i] = temp;
currentLast--;
}
}
for(int i = 0; i < t.length; i++)
System.out.println(t[i]);
}
Yields:
-1
-1
4
-1
-1
After
4
-1
-1
-1
-1
You can convert the array into list, iterate over list and remove all -1, counting how many you removed. Then add that many at the end of the list. If the end result has to be an array, you can use List.toArray method to convert it back.
public static void main(String[] args) {
Integer[] t = {3, -1, -1, -1, 4, 5, 6, -1, -1};
List<Integer> list = new ArrayList<>();
Collections.addAll(list, t);
int numberOfMinusOnes = 0;
for (Integer number : list) {
if (number == -1) {
numberOfMinusOnes++;
}
}
list.removeAll(Arrays.asList(-1));
for (int i = 0; i < numberOfMinusOnes; i++) {
list.add(-1);
}
list.toArray(t);
System.out.println(Arrays.toString(t));
}
Some of boiler plate code can be simplified using google collections library. I would also advise to extract some parts into separate methods to increase readability.
I have searched a lot in google but I didnt get any kind of solution I could use. Suppose input of array is:
{3,1,2,4,9,8,7,6,5,10}
then output must be like this:
{1,2,3,4,5,10,9,8,7,6}
by using Basic Java .
Your array: {3,1,2,4,9,8,7,6,5,10}
Sort it in ascending order: {1,2,3,4,5,6,7,8,9,10}
Break this array into two half arrays: {1,2,3,4,5}{6,7,8,9,10}
Sort the second array in descending order or reverse it: {10, 9,8,7,6}
Add the second array to the first array & you get: {1,2,3,4,5,10,9,8,7,6}
This would be the minimal code which uses an array of primitive ints:
static final int[] xs = {3,1,2,4,9,8,7,6,5,10};
static void sortAndReverse() {
Arrays.sort(xs);
for (int i = xs.length/2; i < dest(i); i++) {
int tmp = xs[i]; xs[i] = xs[dest(i)]; xs[dest(i)] = tmp;
}
System.out.println(Arrays.toString(xs));
}
static int dest(int i) { return 3*xs.length/2-i-1; }
If you're not ashamed of using wrapper objects, then this is unbeatable:
final Integer[] xs = {3,1,2,4,9,8,7,6,5,10};
final List<Integer> list = Arrays.asList(xs);
Collections.sort(list);
Collections.reverse(list.subList(list.size()/2, list.size()));
System.out.println(Arrays.toString(xs));
Please find the below code
import java.util.Arrays;
public class fre {
public static void main(String[] args) {
int[] vals = { 3, 1, 2, 4, 9, 8, 7, 6, 5, 10 };
Arrays.sort(vals); // Sorts the basic first array
int[] vals2 = Arrays.copyOfRange(vals, vals.length / 2, vals.length); // Gets the las values of the arrays i.e. it devies the array in multiple same part and another array is created
// Below loop will reverse the second array
for (int i = 0; i < vals2.length / 2; i++) {
int temp = vals2[i];
vals2[i] = vals2[vals2.length - 1 - i];
vals2[vals2.length - 1 - i] = temp;
}
vals = Arrays.copyOfRange(vals, 0, vals.length / 2);
// Final array array1and2 will be created where we will append first array with second array
int[] array1and2 = new int[vals.length + vals2.length];
System.arraycopy(vals, 0, array1and2, 0, vals.length);
System.arraycopy(vals2, 0, array1and2, vals.length, vals2.length);
// Prints the final result array
System.out.println(Arrays.toString(array1and2));
}
}
Output
[1, 2, 3, 4, 5, 10, 9, 8, 7, 6]
You can use the java features to do this too ... Use
public static <T> void sort(T[] a,
int fromIndex,
int toIndex,
Comparator<? super T> c)
But the elements need to be objects ... The comparator needs to be changed while sorting the first half and second half of the array.
Should be a bit simpler than manually reversing each item in the second half.
Integer [] array = { 3,1,2,4,9,8,7,6,5,10 };
Arrays.sort(array);
Arrays.sort(array, array.length/2, array.length, new Comparator<Integer>(){
#Override
public int compare(Integer o1, Integer o2)
{
return -o1.compareTo(o2);
}
});
System.out.println(Arrays.toString(array));
[1, 2, 3, 4, 5, 10, 9, 8, 7, 6]
IPSOS isn't it?
int m;
if(array.length%2==0)
m=array.length/2;
else
m=(array.length+1)/2;
for(int i=0; i<array.length; ++i){
if(i<m){
int min = i;
for(int j=i+1; j<m;++j){
if(array[min]>array[j]){
min=j;
}
int tem = array[i];
array[i]=array[min];
array[min]=tem;
}
}
else {
int max = i;
for(int k=i+1; k<array.length; ++k){
if(array[max]<array[k]){
max=k;
}
int te = array[i];
array[i]=array[max];
array[max]=te;
}
}
}
for(int i=0;i<array.length;++i){
System.out.print(array[i] + " ");
}
1. Sort the array input_Array[]
2. j = lenght(input_Array)-1
3. loop i = lenght(input_Array)/2 to j
swap(input_Array[i] , input_Array[j-i])
input: 3,1,2,4,9,8,7,6,5,10
output: 1 3 5 7 9 10 8 6 4 2 (uniform acceding and descending )
public class AscendingDecending {
public static void main(String[]args) {
int a[]= {2,3,2,5,7,5,6,3};
int i,j,temp;
//Traverse the element of array
System.out.println("Input:");
for(i=0; i<a.length; i++) {
System.out.print(" "+ a[i]);
}
//lets move for ascending function
System.out.println("");
System.out.println("Output:");
//Create a Swap Function for sorting
for(i=0; i<a.length; i++) {
for(j=i+1; j<a.length; j++) {
if(a[i]>a[j]) {
temp= a[i];
a[i]= a[j];
a[j]= temp;
}
}
}
// Now the input is in sorted order
for(i=0; i<a.length/2; i++) {
System.out.print(" "+ a[i]);
}
//For Descending
for(i=0; i<a.length; i++) {
for(int j=i+1; j<a.length; j++) {
if(a[i]<a[j]) {
temp= a[i];
a[i]= a[j];
a[j]= temp;
}
}
}
// Now the input is in sorted order
System.out.println(" ");
for(i=0; i<a.length/2; i++) {
System.out.print(" "+ a[i]);
}
}
}
I hope this piece of code will help:
static void printarray(int[] arr, int len)
{
Arrays.sort(arr);
for (int i = 0; i < len / 2; i++)
System.out.println(arr[i]);
for (int j = len - 1; j >= len / 2; j--)
System.out.println(arr[j]);
}
Here is what i have done but i have some questions:
class masivins {
public static void main (String args[]) {
int mas[][] = {{0, 2, 7, 0, 8, 5, 3},
{0, 4, 0, 6, 0, 0, 0},
{0, 0, 0, 0, 3, 0, 0},
{7, 0, 0, 9, 1, 0, 7},
{5, 0, 4, 0, 0, 2, 0}};
int nulmas[] = new int [7];
int nul=0;
for(int j=0; j<7; j++) {
nul=0;
for(int i=0; i<5; i++) {
if(mas[i][j]==0) {
nul++;
}
}
nulmas[j]=nul;
}
for(int i=0; i<5; i++) {
for(int j=0; j<7; j++) {
System.out.println(mas[i][j]);
}
System.out.println();
}
System.out.println();
for(int i=0; i<5; i++) {
System.out.println("Zeros in each array column: " + nulmas[i]);
}
System.out.println();
}
}
so my questions are:
Why after running project there are only 5 "Zeros in each array column....." shown?
What and where i need to change in this code to get out the number of column in which zeros are least?
Question 1 - look at your code:
for(int i=0; i<5; i++) {
System.out.println("Zeros in each array column: " + nulmas[i]);
}
In particular, look at the loop. How many lines do you expect it to print out?
Question 2: You could keep a "least number of 0s in an array column so far" and "column in which the least number of 0s appeared" - then update those variables at the end of the inner loop where you set nulmas[j].
1) because you loop from 0 to 4:
for(int i=0; i<5; i++) {
If you looped until 7, all values would be printed out:
for(int i=0; i<7; i++) {
System.out.println("Zeros in each array column: " + nulmas[i]);
}
2) you could keep an index and a minimum counter. The min counter stores the minimum number of zeros, the index the column where this is found:
int nulmas[] = new int [7];
int nul=0;
int minNuls=5;
int minIndex=0;
for(int j=0; j<7; j++) {
nul=0;
for(int i=0; i<5; i++) {
if(mas[i][j]==0) {
nul++;
}
}
nulmas[j]=nul;
if (nul < minNul) {
minNul = nul;
minIndex = j;
}
}
You seem to be very close to answering the question. It looks to me like you've set up the nul_mas array to contain the number of zeros in each column, so the question becomes "which index of nul_mas has the smallest value?". You can do this with two variables - one for the smallest value seen so far, one for the index where it was seen - and a loop through that array to look at each element in turn. (Then, when you've got it working, consider what happens if there is a tie.)
Try:
int leastZeroIndex = 0;
for(int i=0;i<5;i++) {
if (nul_mas[i] < nul_mas[leastZeroIndex])
leastZeroIndex = i;
}
System.out.print(leastZeroIndex);
Though there is no check if there are multiple rows with the lowest amount of zeros.
It looks to me as if you need to create some new arrays, so create an array for each column, and then put the numbers for the column in there. After that, just iterate over that array of arrays which represent the columns and count the numbers (you could use a method for doing this, i.e., int count(int num, int[] arr). I think this'll give the least amount of code.
int[][] mas = ...; // (you have this already), it's [NO_OF_ARRS][NO_OF_COLS] with the data
int[][] colsarrs = new int[NO_OF_COLS][NO_OF_ARRS];
for (int i = 0; i < NO_OF_ARRS; i++) {
for (int j = 0; j < NO_OF_COLS; i++) {
colsarrs[j][i] = mas[i][j];
}
}
int[] resultarr = new int[NO_OF_COLS];
for (int i = 0; i < NO_OF_COLS; i++) {
resultarr[i] = count(0, colsarrs[i]);
}
int count(int num, int[] arr) {
int count;
for (int i = 0; i < arr.length; i++) {
if (arr[i] == num) ++count;
}
return count;
}
Store the amount of zeros in an additional array (resultarr) gathered from this function for each column. After this, go over the array and find the lowest number, and grab the index of it. That's your column with the lowest amount of zeroes.
int lowestcurr = 0;
for (int i = 0; i < NO_OF_COLS; i++) {
if (resultarr[i] < resultarr[lowestcurr]) {
lowestcurr = i;
}
}
for(int i=0; i<5; i++) {
System.out.println("Zeros in each array column: " + nulmas[i]);
}
System.out.println(); place there it
change it on :
int minElement = 0;
for(int i=0; i<7; i++) {
if (nulmas[i] < nulmas[minElement]) minElement = i;
System.out.println("Zeros in each array column: " + nulmas[i]);
}
System.out.println(nulmas[minElement]);
better use "\n" to skip one line in console