avoid count same element in array java - java

// Repetaded element run multiple times means avoid duplicate element count multiple times
import java.util.Scanner;
public class FindFrequency {
public static void main(String[] args) {
int t, count=0;
Scanner in = new Scanner(System.in);
System.out.println("Enter number of elements to insert in an array: ");
int len = in.nextInt();
int[] arr = new int[len];
System.out.println("Enter elements to insert in an array: ");
for( int i=0;i<len;i++)
{
t = in.nextInt();
arr[i] = t;
}
System.out.println("\n");
for(int i=0;i<len;i++)
{
count=1;
for(int j=i+1;j<=len-1;j++)
{
if(arr[i]==arr[j] )
{
count++;
}
}
System.out.println(arr[i] + " is " + count + " times.\n");
}
}
}

I have used one more array to store the print value.We can use set as well as.I hope you get the answer.
let array = [1,2,1,3,4,5,6,2]
var arrayWithPosition = [Int]()
for i in 0..<array.count {
var position = 0
while position < arrayWithPosition.count {
if arrayWithPosition[position] == array[i]{
break
}
position += 1
}
if position == arrayWithPosition.count{
arrayWithPosition.append(array[i])
}else{
continue
}
var count = 1
for j in i+1..<array.count {
if array[i] == array[j] {
count += 1
}
}
print(array[i],count)
}
Output : -
1 2
2 2
3 1
4 1
5 1
6 1

Related

counting cosecutive numbers in arrays

Problem H [Longest Natural Successors]
Two consecutive integers are natural successors if the second is the successor of the first in the sequence of natural numbers (1 and 2 are natural successors). Write a program that reads a number N followed by N integers, and then prints the length of the longest sequence of consecutive natural successors. Example:
Input
7 2 3 5 6 7 9 10 Output 3
here is my code so far can anyone help me plz
import java.util.Scanner;
public class Conse {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scan = new Scanner(System.in);
int x=scan.nextInt();
int[] array= new int[x];
for(int i=0;i<array.length;i++)
array[i]=scan.nextInt();
System.out.println(array(array));
}
public static int array(int[] array){
int count=0,temp=0;
for(int i=0;i<array.length;i++){
count=0;
for(int j=i,k=i+1;j<array.length-1;j++,k++)
if(array[j]-array[k]==1)
count++;
else{if(temp<count)
temp=count;
break;}
}
return temp+1;
}
}
Try this
ArrayList<Integer> outList = new ArrayList<Integer>()
int lastNum = array[0];
for(int i = 1; i < array.length; i++;)
if((lastNum + 1) == array[i])
outList.add(array[i]);
I think the line i=counter; should be i += counter. otherwise, you're always resetting the loop-counter i to zero, and so it never progresses.
You don't need the inner for loop, as this can be done with one single scan through the array:
public static int consecutive(int[]array) {
int tempCounter = 1; //there will always be a count of one
int longestCounter = 1; //always be a count of one
int prevCell = array[0];
for(int i=1;i<array.length;i++) {
if( array[i] == (prevCell + 1)) {
tempCounter++; //consecutive count increases
} else {
tempCount =1; //reset to 1
}
if(tempCounter > longestCounter) {
longestCounter = tempCounter; //update longest Counter
}
prevCell = array[i];
}
return longestCounter;
}
int sequenceStart = 0;
int sequenceLength = 0;
int longestSequenceLength = 0;
for (int item: array) {
if (item == sequenceStart + sequenceLength) {
sequenceLength++;
} else {
sequenceStart = item;
sequenceLength = 1;
}
longestSequenceLength = Math.max(longestSequenceLength, sequenceLength);
}

How to limit printing occurrences in a array?

So close to having this program working but I'm stuck.
What I want it to do is simply print out the numbers that have actual occurrences,
so if the user inputs : 1, 2, 3, 2, 6
It needs to display
1 - 1 times
2 - 2 times
3 - 1 times
6 - 1 times
What I'm actually getting with the same input is something like:
1 - 1 times
2 - 2 times
3 - 1 times
4 - 0 times
5 - 0 times
6 - 1 times
I need to remove the case where there are no occurrences.
import java.util.Arrays;
import java.util.Scanner;
public class CountOccurrences
{
public static void main (String [] args)
{
Scanner input = new Scanner(System.in);
//Create Array for numbers
int numbers[] = new int[100];
//Prompt user input
System.out.println("Enter integers between 1 and 100: ");
//For loop to continue input
for (int i = 0; i < numbers.length; i++) {
int next = input.nextInt();
//Breaks loop if 0 is inputted
if (next==0)
{
break;
}
numbers[i] = next;
}
//Calls on countInts method
int[] count = countInts(numbers);
//Calls on display counts
displayIntCount(count);
}
//Counts each instance of a integer
public static int[] countInts(int[] ints)
{
int[] counts = new int[100];
for(int i = 1; i <=counts.length; i++)
for(int j=0;j<ints.length;j++)
if(ints[j] == i)
counts[i-1]++;
return counts;
}
//Displays counts of each integer
public static void displayIntCount(int[] counts)
{
for (int i = 0; i < counts.length; i++)
System.out.println((i+1) +" - " +counts[i] +" Times");
}
}
Just use a simple if statement to check if counts[i] is not 0, like this:
public static void displayIntCount(int[] counts)
{
for (int i = 0; i < counts.length; i++) {
if (counts[i] != 0) {
System.out.println((i+1) +" - " +counts[i] + " Times");
}
}
}

stop a loop from asking user input

problem here is that we want the program to stop the loop/stop asking integers when '-1' is inputted by the user that it wont have to get the maximum length of our array
import java.util.Scanner;
public class DELETE DUPLICATES {
public static void main(String[] args) {
UserInput();
getCopies(maxInput);
removeDuplicates(maxInput);
}
static int[] maxInput= new int[20];
static int[] copies = new int[20];
static int[] duplicate = new int[20];
//get user's input/s
public static void UserInput() {
Scanner scan = new Scanner(System.in);
int integer = 0;
int i = 0;
System.out.println("Enter Numbers: ");
while(i < maxInput.length)
{
integer = scan.nextInt();
maxInput[i] = integer;
i++;
if (integer == -1)
break;
}
int j = 0;
for(int allInteger : maxInput) {
System.out.print(allInteger+ " ");
j++;
}
}
//to get value/number of copies of the duplicate number/s
public static void getCopies(int[] Array) {
for(int allCopies : Array) {
copies[allCopies]++;
}
for(int k = 0; k < copies.length; k++) {
if(copies[k] > 1) {
System.out.print("\nValue " + k + " : " + copies[k] + " copies are detected");
}
}
}
//remove duplicates
public static void removeDuplicates(int[] Array) {
for(int removeCopies : Array) {
duplicate[removeCopies]++;
}
for(int a = 0; a < duplicate.length; a++) {
if(duplicate[a] >= 1) {
System.out.print("\n"+a);
}
}
}
}
Example:
If we input :
1
2
3
3
4
5
-1
The result of our program is : 1 2 3 3 4 5 -1 0 0 0 0 0 0 0 0 0 0 0 0 0
We want the result to be like: 1 2 3 3 4 5
We need your help guyz . practicing our programming 1 subject hope we could get some help here
You can do a following change just to print the required values:
for(int allInteger : maxInput)
{
if(allInteger == -1)
break;
System.out.print(allInteger+ " ");
j++;
}
but, better change would be to rethink your design and use of data structures.
The maxInput array is of specified size that is 20, so it will have that no. of elements and prints the default value of int.
You can use List instead and check the size for max input and exit loop
If you don't need to use an array, then a Collection has lots of advantages. Let's use a List:
static int maxInputCount = 20;
static ArrayList<Integer> input= new ArrayList<>();
...
for (int i = 0; i < maxInputCount; i++)
{
integer = scan.nextInt();
if (integer == -1)
break;
input.add(integer);
}
for(int integer : input) {
System.out.print(integer+ " ");
}

arraylist java counting runs of integers

I am new to java and array lists. I am supposed to sort populate an array full of random integers, then if there is a run (multiples of the same number in a row), put ( ) around that run.
So if the random list is:
2 3 4 5 5 5 5 6 7 7 9
2 3 4 (5 5 5 5) 6 (7 7) 9
This is what I have so far:
import java.util.*;
class Run {
public static void main (String [] args){
Scanner m = new Scanner(System.in);
System.out.print("Enter length wanted: ");
int len = m.nextInt();
System.out.print("Enter max number wanted: ");
int max = m.nextInt();
max = max -1;
int[] x = new int[len];
ArrayList<String> y = new ArrayList<String>();
//Filling x with random numbers
for(int i = 0; i<len; i++){
x[i] = ((int)(Math.random()*max)+1);
}
System.out.println("Orginal Array: " + Arrays.toString(x));
for(int i = 0; i<=len-1; i++){
if(x[i] == x[i++]){ //I just don't know how I am exactly supposed to sort this
}else{
}
}
//Array List with ()
System.out.println("Runs labeled Array: " + y);
}
}
You're going to need a String to display the final output. Also, don't go out of the array.
Try Something like this:
x = Collections.sort(x);
String s = "";
boolean b;
for(int i = 0; i<=len-1; i++){
if(x[i] == x[i+1]){
s+=" ("+i+" ";
b = true;
}else{
if(b == true){
s+=i+") ";
b = false;
}
s+=i + " ";
}
}
use Collections.sort(yourList) to sort your ArrayList.
If you dont wanna use API methods.
try :
for(int i=0;i<list.size(); i++){
for(int j=i+1; j<list.size(); j++){
if(list.get(i)>list.get(j)){
temp = list.get(i);
list.set(i,list.get(j));
list.set(j, temp);
}
}
}

How can i generate all subsets of a variable length set?

I am trying to write a program that generates all the subsets of an entered set in java. I think i nearly have it working.
I have to use arrays (not data structures)
The entered array will never be greater than 20
Right now when i run my code this is what i get:
Please enter the size of A: 3
Please enter A: 1 2 3
Please enter the number N: 3
Subsets:
{ }
{ 1 }
{ 1 2 }
{ 1 2 3 }
{ 2 3 }
{ 2 3 }
{ 2 }
{ 1 2 }
this is the correct number of subsets (2^size) but as you can see it prints a few duplicates and not some of the subsets.
Any ideas where I am going wrong in my code?
import java.util.Scanner;
public class subSetGenerator
{
// Fill an array with 0's and 1's
public static int [] fillArray(int [] set, int size)
{
int[] answer;
answer = new int[20];
// Initialize all elements to 1
for (int i = 0; i < answer.length; i++)
answer[i] = 1;
for (int a = 0; a < set.length; a++)
if (set[a] > 0)
answer[a] = 0;
return answer;
} // end fill array
// Generate a mask
public static void maskMaker(int [] binarySet, int [] set, int n, int size)
{
int carry;
int count = 0;
boolean done = false;
if (binarySet[0] == 0)
carry = 0;
else
carry = 1;
int answer = (int) Math.pow(2, size);
for (int i = 0; i < answer - 1; i++)
{
if (count == answer - 1)
{
done = true;
break;
}
if (i == size)
i = 0;
if (binarySet[i] == 1 && carry == 1)
{
binarySet[i] = 0;
carry = 0;
count++;
} // end if
else
{
binarySet[i] = 1;
carry = 1;
count++;
//break;
} // end else
//print the set
System.out.print("{ ");
for (int k = 0; k < size; k++)
if (binarySet[k] == 1)
System.out.print(set[k] + " ");
System.out.println("}");
} // end for
} // maskMaker
public static void main (String args [])
{
Scanner scan = new Scanner(System.in);
int[] set;
set = new int[20];
int size = 0;
int n = 0;
// take input for A and B set
System.out.print("Please enter the size of A: ");
size = scan.nextInt();
if (size > 0)
{
System.out.print("Please enter A: ");
for (int i = 0; i < size; i++)
set[i] = scan.nextInt();
} // end if
System.out.print("Please enter the number N: ");
n = scan.nextInt();
//System.out.println("Subsets with sum " + n + ": ");
System.out.println("Subsets: ");
System.out.println("{ }");
maskMaker(fillArray(set, size), set, n, size);
} // end main
} // end class
The value of i always goes from 0 to N-1 and then back to 0. This is not useful to generate every binary mask you need only one time. If you think about it, you need to move i only when you have generate all possible masks up to i-1.
There is a much easier way to do this if you remember every number is already internally represented in binary in the computer and everytime you increment it Java is doing the adding and carrying by itself. Look for bitwise operators.

Categories