How can I know what number is repeated? - java

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.

Related

why one of the code is not working on codechef?

Here is the problem statement: https://www.codechef.com/DAY4DA002/problems/CHEFSUB
Problem description
You are given an array A of N integers: A1, A2, ..., AN. You need to find a longest contiguous subarray in the array such that each integer in this subarray is an even integer, and output its length. A contiguous subarray is of the form Ai, Ai+1, ..., Aj, for some i and j.
input parameters
The code specified below is giving the desired output when i provide input manually but on CodeChef none of the test cases are getting passed
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
int j = 0;
while(t-- > 0)
{
int n = sc.nextInt();
int count = 0;
int[] arr = new int[n];
for(int i = 0; i < n; i++)
{
arr[i] = sc.nextInt();
}
for(int k = 1; k < n; k++)
{
j = k-1;
if(arr[j]%2==0 && arr[k]%2==0)
{
count++;
}
else
{
j++;
}
}
System.out.println(count+1);
}
return;
}
Input:
3
4
1 2 2 4
3
2 4 6
5
2 3 2 2 5
Output:
3
3
2
The above code is providing me the above correct answers when I run it on other IDEs
Now the below given code works for CodeChef and it passes all the test cases
public static void main (String[] args) throws java.lang.Exception
{
try {
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
while (t-->0)
{
int n=sc.nextInt();
int count = 0;
int res = -1 ;
int[] a=new int[n];
for (int i = 0; i < n; i++)
{
a[i]=sc.nextInt();
}
for (int i = 0; i < n; i++)
{
if (a[i]%2==0)
{
count++;
res = Math.max(count ,res);
}
else {
count = 0;
}
}
System.out.println(res);
}
} catch(Exception e) {
}
}
Can you tell me what is the issue with first code and why it is not working on CodeChef?

java arrays random scanner class

I am stuck in my beginner java course and am trying to get my array to print out with the user's input on randomly selected index's. With the code I have so far it will only print out an index with all 0's such as this "{0, 0, 0, 0, 0, 0}"
Here is the prompt:
Create an empty int array of size 6.
Create a method called populateArray that will pass an array, use random class to choose a random index and prompt the user to enter a value, store the value in the array. Note: Generate 6 random index numbers in an attempt to fill the array.
Create a method called printArray that prints the contents of the array using the for each enhanced loop.
Here is my code:
public class ChangeUp {
public static void main(String[] args) {
int[] array = new int[6];
System.out.println("Please enter 6 numbers to add to a list.");
populateArray(array);
printArray(array);
}
public static void populateArray(int[] array) {
Random r = new Random();
Scanner input = new Scanner(System.in);
int rArray = r.nextInt(array.length);
int i = 0;
for (i = rArray; i <= array.length; i++) {
i = input.nextInt();
}
}
public static void printArray(int[] array) {
System.out.print("{" + array[0]);
for (int i = 1; i < array.length; i++) {
System.out.print(", " + array[i]);
}
System.out.println("}");
}
}
for (int i = rArray; i <= array.length; i++) {
i = input.nextInt();
}
Here is your problem. You assign the value(s) to i, not to elements of the array.
Turn:
i = input.nextInt();
into:
array[i] = input.nextInt();
You do not change any values of array. You can do it with array[i] = value where i is index which value you want to change.
Here is example of what populateArray would looks like:
public static void populateArray(int[] array) {
Random r = new Random();
Scanner input = new Scanner(System.in);
int i = r.nextInt(array.length);
array[i] = input.nextInt();
}
You did not assigne input values to the array: array[i] = ....
I would recommend you to not randomly insert an elements, but just fill an array and then shuffle it.
public class ChangeUp {
public static void main(String... args) {
int[] arr = new int[6];
System.out.format("Please enter %d numbers to add to a list:\n", arr.length);
populateArray(arr);
printArray(arr);
}
public static void populateArray(int... arr) {
Scanner scan = new Scanner(System.in);
List<Integer> tmp = new ArrayList<>(arr.length);
for (int i = 0; i < arr.length; i++)
tmp.add(scan.nextInt());
Collections.shuffle(tmp);
int i = 0;
for (int val : tmp)
arr[i++] = val;
}
public static void printArray(int... arr) {
System.out.println(Arrays.stream(arr)
.mapToObj(String::valueOf)
.collect(Collectors.joining(", ", "{", "}")));
}
}
Demo:
Please enter 6 numbers to add to a list:
1
2
3
4
5
6
{4, 3, 1, 5, 2, 6}

How to output multiple values being stored into an array using a for loop on the same line?

I created my arrays and when I am entering the values for the arrays, they are being shown on separate lines for example...
Enter the values for the first array: 75
48
23
I would like the numbers to be shown on the same line and not sure how to do it. Thank you for your help.
public class CompareArrays
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int arraySize;
System.out.print("Enter the array size: ");
arraySize = input.nextInt();
int[] array1 = new int[arraySize];
int[] array2 = new int[arraySize];
System.out.print("Enter the values for the first array: ");
for(int i = 0; i < arraySize; i++) {
array1[i] = input.nextInt();
}
System.out.print("Enter the values for the second array: ");
for(int i = 0; i < arraySize; i++) {
array2[i] = input.nextInt();
}
if(Compare(array1, array2)) {
System.out.println("Judgement: \t The arrays are identical");
}else {
System.out.println("Judgement: \t The arrays are not identical");
}
input.close();
}
public static boolean Compare(int[] array1, int[] array2)
{
for (int i = 0; i < array1.length; i++) {
if(array1[i] != array2[i]) {
return false;
}
}
return true;
}
}
When in the console inputting those values you are hitting enter which is why it looks like it is on different lines. If you want to input the values on 1 line you could possibly input them as a string and split it.
If you're looking to just print the array on one line you can do that with a basic for loop and using System.out.print().
int[] a = {1, 2, 3, 4};
for(int i = 0; i < a.length; i++) {
System.out.print(a[i] + " ");
}

Creating an array that counts up to a given number

I need help creating an array that counts up to a given number. The output should look something like this:
Enter a positive integer: 8
Counting up: 1 2 3 4 5 6 7 8
Counting down: 8 7 6 5 4 3 2 1
The first 8 multiples of 5: 5 10 15 20 25 30 35 40
The first 8 multiples of 10: 10 20 30 40 50 60 70 80
Here is what I have so far:
Scanner input = new Scanner(System.in);
int[] myList = new int[1];
System.out.print("Enter a positive integer: ");
promptUser(myList);
int[] testArray = { 1, 1, 2, 3, 5, 8, 13 };
System.out.print("Test array: ");
printArray(testArray);
System.out.print("Counting up: ");
int[] countingUp = countUp(n);
printArray(countingUp);
}
public static void promptUser(int[] a){
Scanner input = new Scanner(System.in);
for(int i=0; i<a.length; i++){
a[i] = input.nextInt();
}
}
public static void printArray(int[] array){
for(int i=0; i<array.length; i++)
System.out.print(array[i]);
}
public static int[] countUp(int n){
for(int i=0; i<n; i++){
int count = 0;
while(count<n){
count++;
}
}
}
}
Everything seems to work alright except for the last method called countingUp.
Thank you so much!
public static int[] countUp(int n){
for(int i=0; i<n; i++){
int count = 0;
while(count<n){
count++;
}
}
}
change this to
public static int[] countUp(int n){
int [] temp=new int[n];
for(int i=0; i<n; i++){
temp[i]=i+1;
}
return temp;
}
System.out.print("Counting up: ");
int[] countingUp = countUp(n);
printArray(countingUp);
In this line change to
int[] countingUp = countUp(n);
for(int i=0;i<countingUp.length;i++){
system.out.println(countingUp[i]+" ");
}
We can start by extracting the common logic of counting by providing an initial message, the number of times to run, an initial value and an increment. Something like,
private static void count(String msg, int times, int init, int inc) {
System.out.print(msg);
for (int i = 0; i < times; i++) {
System.out.print(' ');
System.out.print(init);
init += inc;
}
System.out.println();
}
We can then implement the entirety of the requirements with something like
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a positive integer: ");
System.out.flush();
do {
int num = scanner.nextInt();
count("Counting up:", num, 1, 1);
count("Counting down:", num, num, -1);
count(String.format("The first %d multiples of 5:", num), num, 5, 5);
count(String.format("The first %d multiples of 10:", num), num, 10, 10);
System.out.print("Enter a positive integer: ");
System.out.flush();
} while (scanner.hasNextInt());
}
This will produce the requested output given an input of 8, and will then prompt for more input.
First of all, If you are trying to change the Array Size Dynamically then It is NOT POSSIBLE in java Take a look # this accepted answer. I recommend you to use ARRAYLIST instead.
Although I have found below mistakes in your code. In your code I do not understand two things.
First One:
System.out.print("Counting up: ");
int[] countingUp = countUp(n);
printArray(countingUp);
What is the value of n? I think it is not being initialized.
Second One:
public static int[] countUp(int n){
for(int i=0; i<n; i++){
int count = 0;
while(count<n){
count++;
}
}
}
What will return this function? You have not returned anything from it.
Apparently you don't need an array just follow below steps.
First create a class which handle all your calculating and counting
class SupportCounting {
public void countUp(int num) {
System.out.print("Counting up : ");
for (int i = 1; i <= num; i++) {
System.out.print(i);
System.out.print(" ");
}
System.out.println("");
}
public void countDown(int num) {
System.out.print("Counting Down : ");
for (int i = num; i > 0; i--) {
System.out.print(i);
System.out.print(" ");
}
System.out.println("");
}
public void printMultiple(int num, int scalefactor) {
System.out.print("First " + num + " multiples of " + scalefactor + " : ");
for (int i = 1; i <= num; i++) {
System.out.print(i * scalefactor);
System.out.print(" ");
}
System.out.println("");
}}
Then make use of that class in you main method
public class Counting {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.print("Enter a positive integer : ");
int n = reader.nextInt();
SupportCounting sc = new SupportCounting();
sc.countUp(n);
sc.countDown(n);
sc.printMultiple(n, 5);
sc.printMultiple(n, 10);
}}
Hope that helps

Pulling distinct values from a array in java

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]);
}
}

Categories