Have a program where the user inputs 10 int values into the array. Lastly I need to pull out the distinct values and display them. Added my second for loop which would determine if the the value is distinct (i.e. meaning if the number appears multiple times it is only displayed once).
For instance, let say I pass in the numbers: 1, 2, 3, 2, 1, 6, 3, 4, 5, 2 the distinct array should only contain numbers {1, 2, 3, 6, 4, 5}
import java.util.Scanner;
import java.io.*;
public class ArrayDistinct {
public static void main(String[] args) throws IOException {
Scanner input = new Scanner(System.in);
// Create arrays & variables
int arrayLength = 10;
int[] numbers = new int[arrayLength];
int[] distinctArray = new int[arrayLength];
int count = 0;
System.out.println("Program starting...");
System.out.print("Please enter in " + numbers.length + " numbers: ");
for (int i = 0; i < numbers.length; i++) {
numbers[i] = input.nextInt();
}
for (int i = 0; i < numbers.length; i++) {
int temp = numbers[i];
int tempTwo = numbers[i + 1];
if (tempTwo == temp) {
count++;
distinctArray[i] = temp;
}
}
// Print out results
} // end main
} // end class
Try this :
Set<Integer> uniqueNumbers = new HashSet<Integer>(Arrays.asList(numbers));
uniqueNumbers will contain only unique values
In Java 8
Stream< T > distinct()
Returns a stream consisting of the distinct elements (according to
Object.equals(Object)) of this stream. For ordered streams, the
selection of distinct elements is stable (for duplicated elements, the
element appearing first in the encounter order is preserved.) For
unordered streams, no stability guarantees are made.
Code:
Integer[] array = new Integer[]{5, 10, 20, 58, 10};
Stream.of(array)
.distinct()
.forEach(i -> System.out.print(" " + i));
Output:
5,10,20,58
Read More About distinct function
Try this code.. it will work
package Exercises;
import java.util.Scanner;
public class E5Second
{
public static void main(String[] args)
{
Scanner In = new Scanner(System.in);
int [] number = new int [10];
fillArr(number);
boolean [] distinct = new boolean [10];
int count = 0;
for (int i = 0; i < number.length; i++)
{
if (isThere(number,i) == false)
{
distinct[i] = true;
count++;
}
}
System.out.println("\nThe number of distinct numbers is " + count);
System.out.print("The distinct numbers are: ");
displayDistinct(number, distinct);
}
public static void fillArr(int [] number)
{
Scanner In = new Scanner(System.in);
System.out.print("Enter ten integers ");
for (int i = 0; i < number.length; i++)
number[i] = In.nextInt();
}
public static boolean isThere(int [] number, int i)
{
for (int j = 0; j < i; j++)
if(number[i] == number[j])
return true;
return false;
}
public static void displayDistinct(int [] number, boolean [] distinct)
{
for (int i = 0; i < distinct.length; i++)
if (distinct[i])
System.out.print(number[i] + " ");
}
}
One possible logic: If you're supposed to only sort out "unique" numbers, then you'll want to test each number as it's entered and added to the first array, and loop through the array and see if it's equal to any of the numbers already there; if not, add it to the "unique" array.
Sets in java doesn't allow duplicates:
Integer[] array = new Integer[]{5, 10, 20, 58, 10};
HashSet<Integer> uniques = new HashSet<>(Arrays.asList(array));
That's it.
Something like this should work for you:
Scanner input = new Scanner(System.in);
// Create arrays & variables
int arrayLength = 10;
int[] numbers = new int[arrayLength];
int[] distinctArray = new int[arrayLength];
int count = 0;
Set<Integer> set = new HashSet<Integer>();
System.out.println("Program starting...");
System.out.print("Please enter in " + numbers.length + " numbers: ");
for (int i = 0; i < numbers.length; i++) {
set.add(input.nextInt());
}
for(Integer i : set)
{
System.out.println("" + i);
}
This will only add unique values to the set.
int a[] = { 2, 4, 5, 3, 3, 3, 4, 6 };
int flag = 0;
for (int i = 0; i < a.length; i++)
{
flag = 0;
for (int j = i + 1; j < a.length; j++)
{
if (a[i] == a[j])
{
flag = 1;
}
}
if (flag == 0)
{
System.out.println(a[i]);
}
}
Related
Basically I need to find the 2nd maximum number in a array.
Suppose the size of the array is 5 and elements are user-inputed.
Here's my solution:
class Main {
public static void main(String[] args) {
int q = 0;
Scanner sc = new Scanner(System.in);
int[] arr = new int[5];
for (int i = 0; i < 5; i++) {
arr[i] = sc.nextInt();
}
System.out.println(getSecondLargest(arr, 5));
}
public static int getSecondLargest(int[] a, int total) {
int temp;
for (int i = 0; i < total; i++) {
for (int j = i + 1; j < total; j++) {
if (a[i] == a[j]) {
return a[i];
}
if (a[i] > a[j]) {
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
return a[total - 2];
}
}
Everything works but it fails when the input has the multiple duplicates values of the maximum number. For eg - 5 5 5 4 3 it needs to give 4 as output but it returns 5 as output.
I also tried to simplify code since size is already mentioned:
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int q = 0;
Scanner sc = new Scanner(System.in);
int[] arr = new int[5];
for (int i = 0; i < 5; i++) {
arr[i] = sc.nextInt();
}
print2largest(arr, 5);
}
static void print2largest(int arr[], 5) {
Arrays.sort(arr);
System.out.println(arr[3]);
}
}
But for the above simplified code to work perfectly no duplicate values must be present in the array.
How to get 2nd maximum element in case of there are multiple duplicate values.
You can use Java-Stream to do this:
int[] arr = new int[] {3,5, 9, 7, 4, 12};
int secondLargest = Arrays.stream(arr)
.boxed()
.distinct() // remove duplicates
.sorted(Comparator.comparingInt(value -> (int) value).reversed())
.skip(1) // skip the first largest
.findFirst()
.get();
System.out.println(secondLargest);
Output:
9
You can use a TreeSet with reverse comparing:
static void print2largest(int arr[]) {
// Creates a TreeSet where, each time an element is added, will order it
// with a reverse comparator (so the largest values will come first).
// Since this is a set, it'll ignore duplicated elements.
final Set<Integer> set = new TreeSet<>(Collections.reverseOrder());
// Add all values from the input array to this set
for (int value : arr) set.add(value);
// Transforms the set into a list so we can get the second largest element
final List<Integer> sortedValues = new ArrayList(set);
// Returns the second largest element from this set
System.out.println(sortedValues.get(1));
}
You can do two functions.(Simple algorithm)
-First function:
Remove duplicates.
-Second function:
Sort a given array, and return the element located in `[array.length-2]`.
Remember to check if `array.length >= 2`, else,( `array.length = 1` ), return
array[0].
We can find the second largest number in an array in java by sorting the array and returning the 2nd largest number.
public class SecondLargestInArrayExample {
public static int getSecondLargest(int[] a, int total) {
int temp;
for (int i = 0; i < total; i++) {
for (int j = i + 1; j < total; j++) {
if (a[i] > a[j]) {
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
return a[total - 2];
}
public static void main(String args[]) {
int a[] = {1, 2, 5, 6, 3, 2};
int b[] = {44, 66, 99, 77, 33, 22, 55};
System.out.println("Second Largest: " + getSecondLargest(a, 6));
System.out.println("Second Largest: " + getSecondLargest(b, 7));
}
}
Output:
Second Largest: 5
Second Largest: 77
I'm trying to know what number is repeated in Java.
I'm using 1.8JDK and never enter in IF.
I don't know how can I do for program works, I'm hardstucked.
Can you check my code?
package exercici10;
import java.util.Scanner;
public class isRepeatedOrNot {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] myArray = new int[10];
int[] myArray2 = new int[10];
for (int i = 0; i < 10; i++) {
myArray2[i] = myArray[i];
}
System.out.print("Enter 10 numbers: ");
// Get myArray.
for (int i = 0; i < 10; i++) {
myArray[i] = sc.nextInt();
}
// Print myArray.
for (int i = 0; i < myArray.length; i++) {
for (int j = 0; j < myArray2.length; j++) {
if (myArray[i] == myArray2[j]) {
System.out.println("Is repeated.");
return;
}
}
}
System.out.println("No numbers repeated.");
sc.close();
}
}
Thank you.
Regards,
Alex.
You do not need to have two arrays, it is enough to use one array and a function that will check if there is a repetition of a number:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] myArray = new int[10];
System.out.print("Enter 10 numbers: ");
// Get myArray.
for (int i = 0; i < 10; i++) {
myArray[i] = sc.nextInt();
}
System.out.println(isNumberRepeated(myArray));
sc.close();
}
public static boolean isNumberRepeated(int[] array)
{
for (int i=0; i<array.length; i++) {
for (int j=i+1; j<array.length; j++) {
if (array[i]==array[j]) {
return true;
}
}
}
return false;
}
}
Input :
Enter 10 numbers: 1
2
3
4
5
6
7
8
9
10
false
Input 2 :
Enter 10 numbers: 1
2
3
4
5
54
6
7
54
9
true
You could use HashSet which doesn't allow duplicate values.
public static void main(String[] args) {
Integer[] myArray = {1, 2, 3, 1, 3, 4, 5, 7, 6, 3, 2};
HashSet<Integer> uniqueNumbers = new HashSet<>();
HashSet<Integer> repeatedNumbers = new HashSet<>();
for (Integer integer : myArray) {
if (uniqueNumbers.contains(integer)) {
repeatedNumbers.add(integer);
} else {
uniqueNumbers.add(integer);
}
}
System.out.println(repeatedNumbers);
}
Also if you need to modify your code to show number of times every number repeated, you could use hashmap.
Given problem:
0/1-Knapsack problem, n items each having weight w_i and value v_i. Find the maximum total value of items whose weights sum up to weight W.
But there are two constraits:
The total weight of all items in the knapsack need to be exactly W.
The total amount of items must be even.
I want to find an algorithm that pays attention to both constraits. I already found out how I can pay attention to one of them at one time.
Here is my implementation which pays attention to constrait 1 (exact weight W):
public class KnapSackExactWeight {
public static void main(String[] args) {
int[] w = new int[] {4, 1, 5, 8, 3, 9, 2}; //weights
int[] v = new int[] {2, 12, 8, 9, 3, 4, 3}; //values
int n = w.length;
int W = 10; // W (max weight)
int[][] DP = new int[n+1][W+1];
for(int i = 1; i < n+1; i++) {
for(int j = 0; j < W+1; j++) {
if(i == 0 || j == 0) {
DP[i][j] = 0;
} else if (j - w[i-1] >= 0) {
DP[i][j] = Math.max(DP[i-1][j], DP[i-1][j - w[i-1]] + v[i-1]);
} else {
DP[i][j] = -Integer.MAX_VALUE;
}
}
}
System.out.println("Result: " + DP[n][W]);
}
}
Result: 22
And here is my implementation which takes constrait 2 into account (even amount of items):
public class KnapSackEvenAmount {
public static void main(String[] args) {
int[] weights = new int[] {4, 1, 5, 8, 3, 9, 2}; //weights
int[] values = new int[] {2, 12, 8, 9, 3, 4, 3}; //values
int n = weights.length;
int W = 10;
int[][] DP_odd = new int[n+1][W+1];
int[][] DP_even = new int[n+1][W+1];
for(int i = 0; i < n+1; i++) {
for(int j = 0; j < W+1; j++) {
DP_even[i][j] = -1;
DP_odd[i][j] = -1;
if(i == 0 || j == 0) {
DP_odd[i][j] = -1;
DP_even[i][j] = 0;
} else if(j - weights[i-1] >= 0) {
if(DP_odd[i-1][j - weights[i-1]] >= 0) {
DP_even[i][j] = Math.max(DP_even[i-1][j], DP_odd[i-1][j - weights[i-1]] + values[i-1]);
}
if(DP_even[i-1][j - weights[i-1]] >= 0) {
DP_odd[i][j] = Math.max(DP_odd[i-1][j], DP_even[i-1][j - weights[i-1]] + values[i-1]);
}
}
if(i > 0) {
DP_odd[i][j] = Math.max(DP_odd[i][j], DP_odd[i-1][j]);
DP_even[i][j] = Math.max(DP_even[i][j], DP_even[i-1][j]);
}
}
}
System.out.println("Result: " + DP_even[n][W]);
}
}
Result: 21
The idea for that: I use two DP tables (DP_even and DP_odd) and save the best solution for a knapsack with odd amount of items in DP_odd and for one with an even amount of items in DP_even.
Now my Problem is how to implement that both constraits work together. Is there a way to solve this?
(If anything is unclear in my question, just ask!)
Not sure if it's the best way to do this problem but what I've done here is to initially reduce the problem to fit the constraints. First find the possible even number of items that weigh equal to the knapsack weight and then find the combination with highest value
import java.util.Scanner;
import static java.lang.Math.pow;
public class subSet{
void subset(int num,int n, int x[])
{
int i;
for(i=1;i<=n;i++)
x[i]=0;
for(i=n;num!=0;i--)
{
x[i]=num%2;
num=num/2;
}
}
public static void main(String[] args) {
int n,d,sum,present=0;
int j;
System.out.println("enter the number of items");
Scanner sc=new Scanner(System.in);
n=sc.nextInt();
int a[]=new int[n+1];
int x[]=new int[n+1];
System.out.println("enter the weights of items");
for(int i=1;i<=n;i++)
a[i]=sc.nextInt();
System.out.println("enter the values of items");
int v[]=new int[n+1];
for(int i=1;i<=n;i++)
v[i]=sc.nextInt();
System.out.println("enter the max weight");
d=sc.nextInt();
int sol=0;int max=0;
if(d>0)
{
for(int i=1;i<=Math.pow(2,n)-1;i++)
{
subSet s=new subSet();
s.subset(i,n,x);
sum=0;int count=0;
for(j=1;j<=n;j++)
if(x[j]==1)
{
sum=sum+a[j];
count++;
}
sol=0;
if(d==sum && count%2==0)
{
present=1;
for(j=1;j<=n;j++)
{
if(x[j]==1)
sol=v[j]+sol;
if(sol>max)
max=sol;
}
}
}
}
if(present==0)
System.out.println("Solution does not exists");
else
System.out.print("solution = "+max);
}
}
I think the problem might be this line:
DP_odd[i][j] = -1;
You give a penalty of only 1 for using an odd amount of times.
If you simply increase this to a larger negative number (e.g. max negative value for integers) I think your current algorithm should work.
I'm writing a code that ask at the user to insert the numbers of the array and then write each numbers, do the same thing in another array, and at the end compare the first array with the second array and print out the bubble sort of all numbers, so a kind of bubble sort for the first and second array togheter. I wrote this below, but I don t know how to compare with one method the two different arrays.
public static void main(String[] args) {
public static int[] macello(int[]A){
for(int i=0; i<A.length-1; i++){
for(int j=0; j<A.length-1-i;j++){
if(A[j]>A[j+1]){
int temp = A[j+1];
A[j+1]= A[j];
A[j] = temp;
}
}
}
return A;
}
public static void printArray2(int[]A){
for(int i = 0; i<A.length; i++){
System.out.print(A[i]+",");
}
}
Scanner scan = new Scanner(System.in);
System.out.println("Insert the capacity's array1: ");
int n = scan.nextInt();
int[]numbers1 = {n};
for(int i=0; i<n; i++){
System.out.println("Insert the value of each numbers: ");
int j =0;
numbers1[j] = scan.nextInt();
j++;
}
System.out.println("Insert the capacity's array2: ");
int m = scan.nextInt();
int[]numbers2 = {m};
for(int i=0; i<m; i++){
System.out.println("Insert the value of each numbers: ");
int j=0;
numbers2[j] = scan.nextInt();
j++;
}
macello(Arrays.equals(numbers1,numbers2));
printArray2(Arrays.equals(numbers1,numbers2));
}
}
You mention in the comments that you've already solved bubblesort. So I'm going to assume you have a method with the signature void bubbleSort(int[] arr).
Your code shows you understand how to acquire an array from the user, so we don't need to handle that.
Now what you're describing is bubbleSorting these two arrays. To do this, you need one -big- array that holds them both.
int combinedLength = array1.length + array2.length;
int[] combined = new int[combinedLength];
for(int i = 0; i < array1.length; i++) {
combined[i] = array1[i];
}
for(int i = 0; i < array2.length; i++) {
combined[array1.length + i] = array2[i];
}
// now you can bubbleSort
bubbleSort(combined);
arrayPrint(combined);
Ideally you wrap that logic in a merge method - this particular method leverages the Arrays and System classes to do some of the lifting for you. Obviously you could use the "naive" logic above if you want.
int[] merge(int[] a , int[] b) {
int[] c = Arrays.copyOf(a, a.length + b.length);
System.arraycopy(b,0,c,a.length,b.length);
return c;
}
If you also make a method that acquires an array, like this:
public int[] acquireArray(Scanner sc) {
System.out.println("Length? ");
int len = sc.nextInt();
int[] arr = new int[len];
for(int i = 0; i < len; i++) {
System.out.println("Enter element " + (i+1) + ":");
arr[i] = sc.nextInt();
}
return arr;
}
Then your code becomes very, very clean:
Scanner sc = new Scanner(System.in);
int[] a = acquireArray(sc);
int[] b = acquireArray(sc);
int[] c = merge(a,b);
bubbleSort(c);
arrayPrint(c);
I made a driver to test each of these ideas out to make sure they all work. I am a bit concerned, though, because you mention recursion. As you can see in this driver, there is no recursion here. Also be aware that I take a number of shortcuts that are probably not allowed (such as System.arraycopy, Arrays.copyOf, and Arrays.toString). I just wanted to validate the various pieces of functionality. The message uses 1 indexing because that's what most people think in. If you enter 5 elements, they'll be 1-5. You and I know Java stores them 0 indexed, 0-4. It's just a matter of taste and UX.
import java.util.*;
public class BubbleSort {
public static void main(String...args) {
Scanner sc = new Scanner(System.in);
int[] a = acquireArray(sc);
int[] b = acquireArray(sc);
int[] c = merge(a,b);
bubbleSort(c);
printArray(c);
}
public static int[] acquireArray(Scanner sc) {
System.out.println("Length? ");
int len = sc.nextInt();
int[] arr = new int[len];
for(int i = 0; i < len; i++) {
System.out.println("Enter element " + (i+1) + ":");
arr[i] = sc.nextInt();
}
return arr;
}
public static int[] merge(int[] a , int[] b) {
int[] c = Arrays.copyOf(a, a.length + b.length);
System.arraycopy(b,0,c,a.length,b.length);
return c;
}
public static void bubbleSort(int[] a) {
boolean swapped = true;
int j = 0;
while(swapped) {
swapped = false;
j++;
for(int i = 0; i < a.length - j; i++) {
if(a[i] > a[i+1]) {
int t = a[i];
a[i] = a[i+1];
a[i+1] = t;
swapped = true;
}
}
}
}
public static void printArray(int[] a) {
System.out.println(Arrays.toString(a));
}
}
And here's what I get when I run it
C:\files\j>java BubbleSort
Length?
5
Enter element 1:
1
Enter element 2:
5
Enter element 3:
3
Enter element 4:
9
Enter element 5:
7
Length?
5
Enter element 1:
2
Enter element 2:
6
Enter element 3:
4
Enter element 4:
0
Enter element 5:
8
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
I am making an Array that is 10 integers long, so that each place 0-9 contains a different integer 0-9.
I am having trouble figuring out how to check if the array already contains a certain number, and if so, regenerating a new one.
So far I have:
for (int i = 0; i < perm.length; i++)
{
int num = (int) (Math.random() * 9);
int []
perm[i] = num;
}
Arrays.asList(perm).contains(num)
from How can I test if an array contains a certain value?
for (int i = 0; i < perm.length; i++)
this is not enough to loop like this, if collision happens some slots would have been not initalized.
Overall, for this task you better initialize array with values in order and then shuffle it by using random permutation indexes
here is a complete answer
int[] array = {3,9, 6, 5, 5, 5, 9, 10, 6, 9,9};
SortedSet<Integer> s = new TreeSet();
int numberToCheck=61;
for (int i = 0; i < array.length; i++) {
s.add(array[i]);
}
System.out.println("Number contains:"+!(s.add(numberToCheck)));
System.out.println("Sorted list:");
System.out.print(s);
Adding both string and integer to check is exist or not.
public class existOrNotInArray {
public static void elementExistOrNot() {
// To Check Character exist or not
String array[] = { "AB", "CD", "EF" };
ArrayList arrayList = new ArrayList<>();
String stringToCheck = "AB";
for (int i = 0; i < array.length; i++) {
arrayList.add(array[i]);
}
System.out.println("Character exist : " + arrayList.contains(stringToCheck));
// To Check number exit or not
int arrayNum[] = { 1, 2, 3, 4 }; // integer array
int numberToCheck = 5;
for (int i = 0; i < arrayNum.length; i++) {
arrayList.add(arrayNum[i]);
}
System.out.println("Number exist :" + arrayList.contains(numberToCheck));
}
public static void main(String[] args) {
elementExistOrNot();
}
}