counting cosecutive numbers in arrays - java

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

Related

Compare 2 team strength and find the wining probability

TeamA = {3,6,7,5,3,5,6,2,9,1}
TeamB = {2,7,0,9,3,6,0,6,2,6}
print the maximum number of fights TeamA can win if they go to fight in an optimal manner. Consider each number in array is a member and that member fight against another member of other team. For e.g TeamA[i] will fight with TeamB[i] and TeamA[i] wins if it is greater than TeamB. With the given array order of TeamA will win only 4 one to one fight. If we re-arrange TeamA array, there is possibility to win 7 fights.i.e TeamA==> {3,9,1,5,5,7,2,6,3,6}
Below is the code which determines the output correctly but there is complexity in time due to sorting, Please help me to optimize the below code
import java.io.*;
import java.util.*;
public class FightCode{
// static long[] result ={};
public static void main(String args[] ) throws Exception {
Scanner scanner = new Scanner(System.in);
try {
int testCount = scanner.nextInt();
for (int test=0;test<testCount;test++) {
int totalMem = scanner.nextInt();
Long[] teamA = new Long[totalMem];
Long[] teamB = new Long[totalMem];
if (totalMem <1)
return;
for (int r = 0; r < totalMem; r++) {
teamA[r] = (Long)scanner.nextLong();
}
for (int i = 0; i < totalMem; i++) {
teamB[i] = (Long)scanner.nextLong();
}
int count = 0;
// int[]swapar = new int[totalMem];
Arrays.sort(teamB, Collections.reverseOrder());
Arrays.sort(teamA, Collections.reverseOrder());
boolean result = Arrays.equals(teamA, teamB);
if (result)
return;
// System.out.println(Arrays.toString(teamB));
// System.out.println(Arrays.toString(teamA));
for (int a = 0; a < totalMem; a++) {
for (int k=0;k<totalMem;k++) {
if(teamA[k] > teamB[a]){
// swapar[a] = teamA[k];
teamA[k] = 0L;
count++;
break;
}
}
}
// System.out.println(Arrays.toString(swapar));
System.out.println(count);
}
} catch(Exception e) {
System.err.println(e.getStackTrace().toString());
} finally {
scanner.close();
}
}
}
This question was asked on techgig Code Gladiator 2020.
Instead of looping over entire team B in range 0 to k-1, you can loop between x and k-1 , where x is last index in team B where last match was found.
for (int a = 0; a < totalMem; a++) {
for (int k=minIndex;k<a-1;k++) {
if(teamA[a] > teamB[k]){
// swapar[a] = teamA[k];
minIndex=k+1;
count++;
break;
}
}
}

Use multiple methods in Java

How to use multiple methods in a code? First it asks for the size of an array, then for the numbers of the element. One method is rounding numbers with a special rule.
Second method is a void method which modifies the array. Third method is making a new array with the modified values and returns to this array.
package tombtombbekerekit;
import java.util.Scanner;
public class TombTombbeKerekit {
public static int round(int osszeg)
{
int last_Digit = osszeg % 10;
if(last_Digit < 3)
return osszeg - last_Digit;
else if(last_Digit > 7)
return osszeg + (10 - last_Digit);
else
return osszeg - (last_Digit) + 5;
}
public static void roundSelf(int [] numbers)
{
int[] array = numbers;
for (int i = 0; i < array.length; i++)
return;
}
public static int [] roundNew(int [] numbers)
{
int [] newArray = new int[numbers.length];
return newArray;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Kérem az összegek számát: ");
int size = sc.nextInt();
System.out.println("Kérem az összegeket: ");
int [] array = new int[size];
for (int i = 0; i < array.length; i ++)
{
array[i] = sc.nextInt();
}
int [] kerek = roundNew(array);
System.out.println("Kerekítve: ");
for (int i = 0; i < kerek.length; i++)
System.out.println(kerek[i]);
}
}
You should write your own function. Just find the rule for the rounding. You can use n%10 to get the last digit of an integer named n.
I've written something but haven't tested it, I believe it should work. Check it out:
public int weirdRounding(int n)
{
int last_Digit = n % 10;
if(last_Digit < 3)
return n - last_Digit;
else if(last_Digit > 7)
return n + (10 - last_Digit);
else // the last digit is 3,4,5,6,7
return n - (last_Digit) + 5;
}
Note: You should probably make this code more readable if you're going to use it. For example define int LOWER_BOUND = 3 and int UPPER_BOUND = 7 instead of using '3' and '7', you could also wrap the ugly expressions with functions (e.g. roundUp, roundToFive ..). #Magic_Numbers_Are_Bad

Counting number of times an int occurs in an array (Java)

I'm trying to count the number of occurences of ints, one to six inclusive, in an array of size 6. I want to return an array with the number of times an int appears in each index, but with one at index zero.
Example:
Input: [3,2,1,4,5,1,3]
Expected output: [2,1,2,1,1,0].
Problem:
It outputs [1,1,3,0,1,0] with the code excerpt below. How can I fix this? I can't find where I'm going wrong.
public static int arrayCount(int[] array, int item) {
int amt = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] == item) {
amt++;
}
}
return amt;
}
public int[] countNumOfEachScore(){
int[] scores = new int[6];
int[] counts = new int[6];
for (int i = 0; i < 6; i++){
scores[i] = dice[i].getValue();
}
for (int j = 0; j < 6; j++){
counts[j] = arrayCount(scores, j+1);
}
return counts;
}
dice[] is just an array of Die objects, which have a method getValue() which returns an int between 1 and 6, inclusive. counts[] is the int array with the wrong contents.
It'll be faster to write another code instead of debugging yours.
public static int[] count(int[] array) {
int[] result = new int[6];
for (int i = 0; i < array.length; i++) {
try{
result[array[i]-1]++;
} catch (IndexOutOfBoundsException e) {
throw new IllegalArgumentException("The numbers must be between 1 and 6. Was " + String.valueOf(array[i]));
}
}
return result;
}
The above will result in an array of 6 ints. ith number in the result array will store the number of occurences of i+1.
PoC for the OP
public static void main(String [] args){
int []ar=new int[]{3,2,1,4,5,1,3};
System.out.println(Arrays.toString(counter(ar)));
}
public static int[] counter(int []ar){
int []result=new int [6];
for(int i=0;i<ar.length;i++){
int c=0;
for(int j=0;j<ar.length;j++){
if(j<i && ar[i]==ar[j])
break;
if(ar[i]==ar[j])
c++;
if(j==ar.length-1){
result[i]=c;
}
}
}
return result;
}

Given an array with 2 integers that repeat themselves the same no. of times, how do i print the two integers

i'm new to this, Say if you typed 6 6 6 1 4 4 4 in the command line, my code gives the most frequent as only 6 and i need it to print out 6 and 4 and i feel that there should be another loop in my code
public class MostFrequent {
//this method creates an array that calculates the length of an integer typed and returns
//the maximum integer...
public static int freq(final int[] n) {
int maxKey = 0;
//initiates the count to zero
int maxCounts = 0;
//creates the array...
int[] counts = new int[n.length];
for (int i=0; i < n.length; i++) {
for (int j=0; j < n[i].length; j++)
counts[n[i][j]]++;
if (maxCounts < counts[n[i]]) {
maxCounts = counts[n[i]];
maxKey = n[i];
}
}
return maxKey;
}
//method mainly get the argument from the user
public static void main(String[] args) {
int len = args.length;
if (len == 0) {
//System.out.println("Usage: java MostFrequent n1 n2 n3 ...");
return;
}
int[] n = new int[len + 1];
for (int i=0; i<len; i++) {
n[i] = Integer.parseInt(args[i]);
}
System.out.println("Most frequent is "+freq(n));
}
}
Thanks...enter code here
Though this may not be a complete solution, it's a suggestion. If you want to return more than one value, your method should return an array, or better yet, an ArrayList (because you don't know how many frequent numbers there will be). In the method, you can add to the list every number that is the most frequest.
public static ArrayList<Integer> freq(final int[] n) {
ArrayList<Integer> list = new ArrayList<>();
...
if (something)
list.add(thatMostFrequentNumber)
return list;
}
The solutions looks like this:
// To use count sort the length of the array need to be at least as
// large as the maximum number in the list.
int[] counts = new int[MAX_NUM];
for (int i=0; i < n.length; i++)
counts[n[i]]++;
// If your need more than one value return a collection
ArrayList<Integer> mf = new ArrayList<Integer>();
int max = 0;
for (int i = 0; i < MAX_NUM; i++)
if (counts[i] > max)
max = counts[i];
for (int i = 0; i < MAX_NUM; i++)
if (counts[i] == max)
mf.add(i);
return mf;
Well you can just do this easily by using the HashTable class.
Part 1. Figure out the frequency of each number.
You can do this by either a HashTable or just a simple array if your numbers are whole numbrs and have a decent enough upper limit.
Part 2. Find duplicate frequencies.
You can just do a simple for loop to figure out which numbers are repeated more than once and then print them accordingly. This wont necessarily give them to you in order though so you can store the information in the first pass and then print it out accordingly. You can use a HashTable<Integer,ArrayList<Integer> for this. Use the key to store frequency and the ArrayList to store the numbers that fall within that frequency.
You can maintain a "max" here while inserting into our HashTable if you only want to print out only the things with most frequency.
Here is a different way to handle this. First you sort the list, then loop through and keep track of the largest numbers:
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
int n[] = { 6, 4, 6, 4, 6, 4, 1 };
List<Integer> maxNums = new ArrayList<Integer>();
int max = Integer.MIN_VALUE;
Integer lastValue = null;
int currentCount = 0;
Arrays.sort(n);
for( int i : n ){
if( lastValue == null || i != lastValue ){
if( currentCount == max ){
maxNums.add(lastValue);
}
else if( currentCount > max ){
maxNums.clear();
maxNums.add(lastValue);
max = currentCount;
}
lastValue = i;
currentCount = 1;
}
else {
currentCount++;
}
System.out.println("i=" + i + ", currentCount=" + currentCount);
}
if( currentCount == max ){
maxNums.add(lastValue);
}
else if( currentCount >= max ){
maxNums.clear();
maxNums.add(lastValue);
}
System.out.println(maxNums);
}
}
You can try it at: http://ideone.com/UbmoZ5

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