extract different number in two array in java - java

Here i come with to extract different number in two array in java .different number are to be store in third list of array i am new to java could some one guide me in right Direction
which i tried upto now??
int[] list={1,2,3,4,5,6,7};
int[] list1={1,2,3,4,5,6,7,8,9,10};
int [] list2 =null;
for (int i = 0; i < list.length; i++)
{
for (int j = 0; j < list1.length; j++)
{
if(list[i]!=list1[j])
{
System.out.println(list2[]);
}
}
}

int[] list={1,2,3,4,5,6,7};
int[] list1={1,2,3,4,5,6,7,8,9,10};
int [10] list2 =null;
boolean flag=false;
int k=0;
for (int i = 0; i < list.length; i++)
{
for (int j = 0; j < list1.length; j++)
{
if(list[i]!=list1[j])
{
flag=false;
}
else
{
flag=true;
}
if(flag==true)
{
list2[k]=list[i];
k++;
}
}
}
Now I am pretty sure about answer.

Well the problem is that in java you need to specify the size of the array.
What you can do :
int[] list={1,2,3,4,5,6,7};
int[] list1={1,2,3,4,5,6,7,8,9,10};
int size = list1.length;
boolean found = false;
int[] list2=new int[size];
for (int i = 0; i < list1.length; i++)
{
for (int i = 0; i < list1.length; i++){
if(list[i]==list1[i])
{
found = true;
}
}
if(found)
found = false;
else
list2[i]=list1[i];
}
System.print.out("List2={");
for(int k = 0; k < list2.length; k++){
if(list2[k] != 0)
System.print.out(list2[k] + ", ");
}
System.print.out("}");
(c.f. : JavaDoc)

Related

Sort array in descending order and collect the changes of main array in new array

public static int[] sortByScores(double[] scores){
double temp;
int i,j;
int[] scoreIndex = new int[3];
for (i = 0; i <= scores.length; i++)
for (j = i+1; j < scores.length; j++) {
if (scores[i] < scores[j]) {
temp = scores[i];
scores[i] = scores[j];
scores[j] = temp;
scoreIndex[i] = j;
scoreIndex[j] = i;
}
}
return scoreIndex;
}
This method sort the "scores" array in descending order and store which index key is changed from the array in "scoreIndex" array.
This method doesn't work if I enter 1,3,2,4
Is they any better way to store the index key changes log?
Example if 1 enter:
1
2
4
3
Sorted will be:
4
3
2
1
And sortIndex should be:
Key Value
0 3
1 2
2 0
3 1
You can actually get the array containing the proper ordering of the elements at certain indices without sorting this array, for example, by doing this:
for(int i = 0; i < scores.length; i++) {
for(int j = i; j < scores.length; j++) {
if(scores[scoreIndex[j]] > scores[scoreIndex[i]]) {
int temp = scoreIndex[j];
scoreIndex[j] = scoreIndex[i];
scoreIndex[i] = temp;
}
}
}
In short, at the beginning of this method we are creating an array which contains the current order of indices in your scores[] array, this is 0, 1, ..., scores.length-1. Then, we perform an operation similar to standard sorting but not in terms of the scores[] array, but in terms of the scoreIndex[] array.
Once we have this array sorted, we can create another array and and place its elements at the appropriate position by:
double[] copy = new double[scores.length];
for(int k = 0; k < scores.length; k++) {
copy[k] = scores[k];
}
for(int n = 0; n < scores.length; n++) {
scores[n] = copy[scoreIndex[n]];
System.out.println(scores[n]);
}
So, to put it together:
public static int[] sort(double[] scores) {
int[] scoreIndex = new int[scores.length];
for(int i = 0; i < scores.length; i++) {
scoreIndex[i] = i;
}
for(int i = 0; i < scores.length; i++) {
for(int j = i; j < scores.length; j++) {
if(scores[scoreIndex[j]] > scores[scoreIndex[i]]) {
int temp = scoreIndex[j];
scoreIndex[j] = scoreIndex[i];
scoreIndex[i] = temp;
}
}
}
double[] copy = new double[scores.length];
for(int k = 0; k < scores.length; k++) {
copy[k] = scores[k];
}
for(int n = 0; n < scores.length; n++) {
scores[n] = copy[scoreIndex[n]];
System.out.println(scores[n]);
}
return scoreIndex;
}
First, you should declare scoreIndex as:
int[] scoreIndex = new int[scores.length];
And, in every outer loop, you find the max element, set it as scores[i], at the same time, set scoreIndex[indexOfMaxElement] = i. To achieve this, you also need a copy of the origial array.
Here is the complete code:
public class Main {
public static void main(String[] args) {
double[] array = new double[] {1, 2, 4, 3};
int[] result = sortByScores(array);
for (int i = 0; i < result.length; i++) {
System.out.println(result[i]);
}
for (int i = 0; i < array.length; i++) {
System.out.println(array[i]);
}
}
public static int[] sortByScores(double[] scores){
int[] scoreIndex = new int[scores.length];
double[] copy = new double[scores.length];
boolean[] records = new boolean[scores.length];
// copy
for (int i = 0; i < scores.length; i++) {
copy[i] = scores[i];
}
for (int i = 0; i < scores.length; i++) {
// find the max element
for (int j = i + 1; j < scores.length; j++) {
if (scores[i] < scores[j]) {
double temp = scores[i];
scores[i] = scores[j];
scores[j] = temp;
}
}
// set the max element's index
for (int k = 0; k < copy.length; k++) {
if (copy[k] == scores[i] && !records[k]) {
scoreIndex[k] = i;
records[k] = true;
break;
}
}
}
return scoreIndex;
}
}
My one worked too but #user6690200 your one is way better.
public static int[] sortByScores(double[] scores){
double temp,temp2;
int i,j;
int[] scoreIndex = new int[3];
double[] scoreBackup = new double[scores.length];
double[] scoreBackup2 = new double[scores.length];
// Generating unique score, beacuse student can have same score
for(i=0;i<scores.length;i++)
scoreBackup[i] = scores[i]*(i+1);
for(i=0;i<scores.length;i++)
scoreBackup2[i] = scores[i]*(i+1);
for (i = 0; i < scores.length; i++) {
for (j = i+1; j < scores.length; j++) {
if (scores[i] < scores[j]) {
temp = scores[i];
temp2 = scoreBackup2[i];
scores[i] = scores[j];
scoreBackup2[i] = scoreBackup2[j];
scores[j] = temp;
scoreBackup2[j] = temp2;
}
}
}
for(i = 0; i<scores.length;i++)
for(j=0;j<scores.length;j++)
if(scoreBackup[i] == scoreBackup2[j])
scoreIndex[i] = j;
return scoreIndex;
}

Removing N duplicates from integer array

problem statement: I have to remove n duplicates from array.
Here is the full problem statement : https://pastebin.com/EJgKUGe3
and my solution is :
public class minion_labour_shift_2ndTry {
static int[] data = {1,2, 2, 3, 3, 3, 4, 5, 5};
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int n = reader.nextInt();
data = answer(data, n);
for (int i = 0; i < data.length; i++) {
System.out.print(data[i] + " ");
}
}
public static int[] answer(int[] data, int n) {
if (data.length>99){
System.exit(0);
}
int[] result = new int[99];
ArrayList<Integer> temp = new ArrayList<>();
int counter = 0, count ,maxCount = 0;
for (int i = 0; i < data.length; i++) {
boolean isDistinct = false;
for (int j = 0; j < i; j++) {
if (data[i] == data[j]) {
isDistinct = true;
break;
}
}
if (!isDistinct) {
result[counter++] = data[i];
}
}
for (int i = 0; i < counter; i++) {
count = 0;
for (int j = 0; j < data.length; j++) {
if (result[i] == data[j]) {
count++;
}
}
System.out.println("....... count"+count);
if (maxCount <= count){
maxCount = count;
}
if (count <= n){
temp.add(result[i]);
}
}
if (maxCount-1 < n){
return data;
}
data = new int[temp.size()];
for (int i = 0; i <temp.size() ; i++) {
data[i] = temp.get(i);
}
return data;
}
}
Now, my question is, what I am missing and what should I do to pass all the 10 cases.
Thanks In Advance :)
NB:It will be compiled in java 7 , and Map,hashset or third-party libraries, input/output operations, spawning threads or processes and changes to the execution environment are not allowed.
I misread the requirements initially, this does what is asked:
public static int[] answer(int[] data, int n) {
Map<Integer, Integer> counts = new HashMap<>();
int elementsNeeded = 0;
for (int i = 0; i < data.length; i++) {
Integer currentCount = counts.get(data[i]);
currentCount = currentCount == null ? 1 : ++currentCount;
counts.put(data[i], currentCount);
if (currentCount <= n + 1) {
elementsNeeded += currentCount > n ? -n : 1;
}
}
int[] resultArray = new int[elementsNeeded];
int j = 0;
for (int i = 0; i < data.length; i++) {
if (counts.get(data[i]) <= n) {
resultArray[j++] = data[i];
}
}
return resultArray;
}
...and also your own code, slightly altered:
public static int[] answer2(int[] data, int n) {
if (data.length>99){
System.exit(0);
}
ArrayList<Integer> temp = new ArrayList<>();
int count;
for (int i = 0; i < data.length; i++) {
count = 0;
for (int j = 0; j < data.length; j++) {
if (data[i] == data[j]) {
count++;
}
}
if (count <= n){
temp.add(data[i]);
}
}
data = new int[temp.size()];
for (int i = 0; i <temp.size() ; i++) {
data[i] = temp.get(i);
}
return data;
}
Not going to provide a full solution but suggesting a reworking of the algorithm because it's not clear what you're doing, you never explained your actual thoughts of the algorithm. For example, what are you using isDistinct for?
1) Loop through once and compute the frequency of every number. You can just use an array of length 100 since that's all the data inputs will be. As you loop through, keep track of two things: The total number of entries that occur more than n times, as well as which those numbers are
2) Create a resulting array of the appropriate size (calculated from above) and loop through the list again and fill in the elements that didn't cross the threshold.

I am trying this simple sudoku

I am trying a simple sudoku program. i started by taking the values in a 3D
array and then copied them into a 1D array by using mr.serpardum's method.
i know that there is an error at the point where i am trying to find
duplicate elements,because even if i give same numbers as input the output
says "its a sudoku" but i can't to find it...apparently i can't add any
image coz i dont have enough credits
public class SecondAssignment {
#SuppressWarnings("unused")
public static void main(String[] args) throws IOException {
int i = 0, j = 0, k = 0;
boolean result = false;
int arr1[][];
arr1 = new int[3][3];
int arr2[];
arr2 = new int[9];
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the elements in the sudoku block");
//getting elements into array
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
arr1[i][j] = Integer.parseInt(br.readLine());
}
}
//printing it in matrix form
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
System.out.print(arr1[i][j] + "\t");
}
System.out.println(" ");
}
//copying array1 elements into array 2
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
arr2[i * 3 + j] = arr1[i][j];
}
}
//finding duplicate elements
for (i = 0; i < arr2.length; i++) {
for (int m = i + 1; m < arr2.length; m++) {
if (arr2[i] == (arr2[m])) {
System.out.println("Not a sudoku");
//result = true;
} else {
System.out.println("Its a sudoku");
//result = false;
}
}
}
}
}
You can update your code to following
//finding duplicate elements
for( i = 0; i < arr2.length; i++){
for(int m = i+1; m < arr2.length; m++){
if(arr2[i] == (arr2[m])){
result = true;
break;
}
}
}
if(result){
System.out.println("\nNot a sudoku");
}
else{
System.out.println("\nIts a sudoku");
}
You should have used break as soon as the match was found.
This code just checks if duplicate element is present in the array (of size 9) or not.

java.lang.ArrayIndexOutOfBoundsException Error

How do I fix this error and what does it mean?
java.lang.ArrayIndexOutOfBoundsException: 5
at Sort.sort(Sort.java:29)
at Sort.<init>(Sort.java:13)
at SortedArray.<init>(SortedArray.java:23)
Here is the code:
import java.util.Scanner;
import java.util.Random;
public class SortedArray
{
Scanner input = new Scanner(System.in);
int [] Array;
Sort sortedArray;
int sizeOfArray;
public SortedArray()
{
System.out.print("Enter the number of values to put in the array: ");
sizeOfArray = input.nextInt();
Array = new int [sizeOfArray];
System.out.println("");
for(int i = 0; i < sizeOfArray; i++)
{
Random r = new Random();
Array[i] = r.nextInt(100) + 1;
System.out.println(Array[i]);
}
sortedArray = new Sort(Array, sizeOfArray);
sortedArray.display();
}
}
public class Sort
{
int[] array;
int sizeOfArray;
public Sort(int[] oldArray, int sizeOfOldArray)
{
sizeOfArray = sizeOfOldArray;
array = new int [sizeOfArray];
for( int i = 0; i < sizeOfArray; i++)
{
array[i] = oldArray[i];
}
sort();
}
public void display()
{
for ( int i = 0; i < sizeOfArray; i++){
System.out.println(array[i]);
}
}
private void sort()
{
for (int i = 0; i < sizeOfArray; i++)
{
for (int j = 0; j < sizeOfArray; i++)
{
if (array[j] < array[i])
{
swap(i,j);
}
}
}
}
private void swap(int x, int y)
{
int temp;
temp = array[x];
array[x] = array[y];
array[y] = temp;
}
}
I get the error when I run the program and enter the value. The program is supposed to sort the numbers from greatest to least. I'm not sure what is wrong.
First, what it means: you have an array and are trying to acces an index that is outside its range (below 0 or bigger or equal than the length of the array).
The probable cause is:
for (int j = 0; j < sizeOfArray; i++)
Notice that you check that j does not get too big but you are increasing i.
The Problem is that the inner loop also incrementsi which isn't correct in this situation!
private void sort()
{
for (int i = 0; i < sizeOfArray; i++)
{
for (int j = 0; j < sizeOfArray; j++)
{
if (array[j] < array[i])
{
swap(i,j);
}
}
}
}
Your problem is on this line
for (int j = 0; j < sizeOfArray; i++)
it should be
for (int j = 0; j < sizeOfArray; j++)

2-dimensional array in Java

Assume you are given an int variable named nPositive and a 2-dimensional array of ints that has been created and assigned to a2d. Write some statements that compute the number of all the elements in the entire 2-dimensional array that are greater than zero and assign the value to nPositive.
Code:
for(int i=0; i<a2d.length; i++){
int nPositive;
for(int j=0; j<a2d[a2d.length-1].length; j++) {
if(a2d[i][j] > 0) {
nPositive = a2d[i][j];
}
}
}
It has a compilation error. Why?
The iiner cycle is incorrect:
for(int j=0; j<a2d[i].length; j++){
You didn't initialize nPositive.
// make nPositive a global variable
int nPositive = 0;
for(int i=0; i<a2d.length; i++){
for(int j=0; j<a2d[a2d.length-1].length; j++) {
if(a2d[i][j] > 0) {
nPositive += a2d[i][j]; // add the value into nPositive as you go through the array
}
}
}
I tested it and find that,There is no any compilation error in your code...
for(int j=0; j<a2d[a2d.length-1].length; j++){//
let the length is a2d[10][10]
on statement a2d[a2d.length-1].length ,is equal a2d[10-1].length ,is equal a2d[9].length=>10
your algo is working fine for me ,i found no any error
here's my test code
public class A2dTest {
public static void main(String[] arr) {
int[][] a2d = new int[10][10];
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
a2d[i][j] = (int) (Math.random() * 100) + 1000000;// all positives
}
}
for (int i = 0; i < a2d.length; i++) {
int nPositive = 0;
for (int j = 0; j < a2d[a2d.length - 1].length; j++) {
if (a2d[i][j] > 0) {
nPositive = a2d[i][j];
System.out.println("nPositive=" + nPositive);
}}
}
}
}
I believe this is one of the questions on codeLab. You just need to properly initialize nPositive at 0 and increment it for every positive integer. That's all they're looking for involving the output. So your code needs to be:
nPositive = 0;
for (int i = 0; i < a2d.length; i++)
{
for (int j = 0; j < a2d[i].length; j++)
{
if (a2d[i][j] > 0)
{
nPositive++;
}
}
}

Categories

Resources