Finding Consecutive Duplicate integers in an array - java

I have a problem in which I need to ask for user input for how many times they wish to roll a die and to create and print that an array that has the rolls requested. So far I can create the array, however another part of the problem is that whenever there are consecutive duplicate rolls I must put parentheses around them. For example inputting 11, creates the array
{1 , 2 , 1 , 4 , 4, 6 , 2 , 3 , 5 , 5 , 5} would print 1 2 1 ( 4 4 ) 6 2 3 ( 5 5 5 )
So far I have written
import java.util.Scanner;
import java.util.Random;
public class HW0603 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("How many times would you like to roll: ");
System.out.println();
int x = input.nextInt();
run(rolls(x), x);
}
public static int[] rolls(int x) {
Random random = new Random();
int y[] = new int[x];
for (int i = 0; i < x; i++) {
int z = random.nextInt(6) + 1;
y[i] = z;
}
return y;
}
public static void run(int a[], int b) {
for (int i = 1; i < b; i++) {
System.out.print(a[i] + " ");
}
}
}
As for the parentheses I honestly don't know how to start. Using if statements didn't work for me, my if statement variations seem to give me out of bound errors since I compare a[i] to a[i+1] and a[i-1]. Could anyone give me a place to start or some tips to being extracting consecutive duplicates?

you need to compare current item with next item
if equal, print "(" then print the item
make flag paranOpened that you have opened (, so you don't reopen ( again, to avoid this: 1 (2(2(2..., then when curr!=next, based on that flag either print the item or print the item then close the ")"
at end of loop
print lat item (b-1) that was excluded from the loop ..;i < b - 1;.., and check if you have opened "("
your run() method will be like this
static boolean paranOpened = false;
public static void run(int a[], int b) {
for (int i = 0; i < b - 1; i++) {
if (a[i] == a[i + 1]) {
if (!paranOpened) {
paranOpened = true;
System.out.print(" (");
}
System.out.print(a[i] + " ");
} else {
System.out.print(a[i] + " ");
if (paranOpened) {
System.out.print(") ");
paranOpened = false;
}
}
}// for loop
// print last item in array #(b-1)
System.out.print(a[b - 1] + " ");
// check if opened ( , then close it
if (paranOpened) {
System.out.print(") ");
}
}// run()
this is a quick solution, there could be better algorithms

The first problem with you program is that the counter in your run method starts
from 1 which should be zero. Your current program does not print the first element of the array.
then you need to check each element with the next one to see if they are duplicate and if they are open the parenthesis and vice versa.
The last element does not need to be checked so print it outside the loop and close the parenthesis if needed.
By the way you do not need to pass the array size element with it. Just use the array.length method.
public static void run(int a[], int b)
{
boolean pOpen = false;//keep track if parenthesis is open
for (int i = 0; i<a.length; i++)
{
if (i < a.length-1)//prevent out of bound exception
{
if (a[i] == a[i+1] && !pOpen )// check if it is needed to `open or close the parenthesis`
{
System.out.print("(");
pOpen = true;
}
System.out.print(a[i] + " ");
if (a[i] != a[i+1] && pOpen)
{
System.out.print(")");
pOpen = false;
}
}
}
System.out.print(a[a.length-1]);//print the last element
if (pOpen)//close the parenthesis if open
{
System.out.print(")");
}
}

Iterate through your array and keep a boolean that marks if parenthesis have opened.
import java.util.*;
class Ideone
{
public static int[] rolls(int x) {
Random random = new Random();
int y[] = new int[x];
for (int i = 0; i < x; i++) {
int z = random.nextInt(6) + 1;
y[i] = z;
}
return y;
}
public static void run(int a[], int b) {
StringBuilder sb = new StringBuilder();
String out = "";
boolean parens = false;
for (int j = 0; j < a.length; j++)
{
out = "" + a[j]; //by default just add an element
//check for duplicate and build parenthesis
if (j + 1 < a.length && a[j] == a[j+1]) //duplicate found
{
if (!parens) // if no parenthesis
{
parens = true; //start parenthesis
out = "( " + a[j];
}
}
else
{
if (parens) //if parenthesis already started
{
out = a[j] + " )";
parens = false; //stop parenthesis
}
}
sb.append(" " + out);
}
// if the last element occured multiple times
if (parens) //should end parens
{
sb.append(a[a.length-1] + " )");
}
//print out the result
System.out.println(sb.toString());
}
public static void main (String[] args) throws java.lang.Exception
{
Scanner input = new Scanner(System.in);
System.out.print("How many times would you like to roll: ");
System.out.println();
int x = input.nextInt();
run(rolls(x), x);
}
}

You need to use boolean to check whether your parenthesis is open or no.

Here I've tried to create a clean and readable example:
Sample code:
public class HelloWorld {
public static void main(String[] args) {
int arr[] = { 1, 2, 1, 4, 4, 6, 2, 3, 5, 5, 5 };
printConsecutiveInBrace(arr);
}
public static void printConsecutiveInBrace(int arr[]) {
int printFrom = 0;
for (int i = 0; i < arr.length; i++) {
if (i == arr.length - 1 || arr[i] != arr[i + 1]) {
print(arr, printFrom, i);
printFrom = i + 1;
}
}
}
public static void print(int arr[], int printFrom, int printTo) {
if (printFrom < printTo) //Here check: Consecutive Duplicate
System.out.print("( ");
for (int i = printFrom; i <= printTo; i++)
System.out.print(arr[i] + " ");
if (printFrom < printTo)
System.out.print(") ");
}
}
Output:
1 2 1 ( 4 4 ) 6 2 3 ( 5 5 5 )

Related

How do I print the index of which an element has been found after linear search? Java

I am making a program in which a linear search is used to iterate through an array of 100 randomly generated numbers which are less than 10000.
The user enters a startNumber, midNumber and endNumber and the linear search will iterate through the array and tell the user at which index the elements have been found
I have implemented the linear search and everything seems to be working fine but it seems that I cannot print out the index of elements when found after linear search has been implemented.
I have provided code, input and output:
Code:
import java.util.Scanner;
import java.util.Random;
import java.util.Arrays;
public class App {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// generating n, 0 < n < 10000 and 0 < length < 100
Random rand = new Random();
int[] arr = new int[100];
for (int z = 0; z < arr.length; z++) {
arr[z] = rand.nextInt(10000);
}
// sorting
Arrays.sort(arr);
System.out.println(Arrays.toString(arr));
int startNum = scanner.nextInt();
int midNum = scanner.nextInt();
int endNum = scanner.nextInt();
// linear search
for (int i = 0; i < arr.length; i++) {
if (startNum == arr[i]) {
System.out.println("Found");
}
else {
System.out.println("Not Found");
}
// where I want to print out the final message such as "startNum found at i"
}
}
}
Input:
254
1467
8185
Output:
Found
Not Found
Not Found
Not Found
Not Found
Not Found
Not Found
No
...(keeps printing not found?)
I just want to keep this simple , thanks
You can create boolean variables for each of these three numbers to track if they are found or not. Wherever they are found, print their index and change the value of the corresponding boolean variable to true.
After the loop terminates, check the value of these boolean variables and print the Not Found message if their value has not changed to true.
Code:
boolean startNumFound = false, midNumFound = false, endNumFound = false;
for (int i = 0; i < arr.length; i++) {
if (startNum == arr[i]) {
System.out.println(startNum + " was found at index, " + i);
startNumFound = true;
} else if (midNum == arr[i]) {
System.out.println(midNum + " was found at index, " + i);
midNumFound = true;
} else if (endNum == arr[i]) {
System.out.println(endNum + " was found at index, " + i);
endNumFound = true;
}
}
if (!startNumFound) {
System.out.println(startNum + " was not found");
}
if (!midNumFound) {
System.out.println(midNum + " was not found");
}
if (!endNumFound) {
System.out.println(endNum + " was not found");
}
if you want to print the result outside of loop, then simply define another variable with value of -1 because indexes start with zero then store the index of founded element inside it and if nothing found then value will be -1 which means not found:
// linear search
int index = -1;
for (int i = 0; i < arr.length; i++) {
if (startNum == arr[i]) {
index = i;
break;
}
}
if (index != -1) {
System.out.print(startNum + " Found at index: " + index);
} else {
System.out.println("Not Found");
}

Car fueling problem in java. Can anyone figure out any error in while loop condition?

import java.util.*;
import java.io.*;
public class CarFueling {
static int compute_refills(int dist,int tank,int stops[],int n){
int current_refills=0;
int num_refills=0;
int last_refill=0;
while(current_refills<=n) {
last_refill = current_refills;
while ((current_refills <= n) && (stops[current_refills + 1] - stops[last_refill]) <= tank) {
current_refills = current_refills + 1;
}
if (current_refills == last_refill)
return -1;
if (current_refills <= n)
num_refills = num_refills + 1;
}
return num_refills;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int dist = scanner.nextInt();
int tank = scanner.nextInt();
int n = scanner.nextInt();
int stops[] = new int[n*n*n];// to solve array index out of bound exception increase the size of the array
for (int i = 0; i < n; i++) {
stops[i] = scanner.nextInt();
}
System.out.println(compute_refills(dist,tank,stops,n));
}
}
I think there is some issue in my while loop condition.
Input:
950
400
4
200 375 550 750
my output:
1
correct output:
2
If you look at the
(current_refills <= n) && (stops[current_refills + 1] ... )
part, two things:
current_refills <= n is true for both n-1 (the last element of a n-element array, as the first one has index 0), and n (which is already outside the array)
then stops[current_refills + 1] accesses an element "later", which is 1 or 2 elements above the max for these two cases
But actually this can work, just you could add 0 for the beginning of the trip and dist as the end:
int n = scanner.nextInt();
int stops[] = new int[n+2];
stops[0] = 0; // well, it is 0 already
stops[n+1] = dist;
for (int i = 1; i <= n; i++) {
stops[i] = scanner.nextInt();
}
Then compute_refills() may work correctly (though I haven't checked).

Java Single Dimensional Arrays

Enter the integers between 1 and 50: 1 2 1 0
1 occurs 2 times
2 occurs 1 times
1 occurs 2 times
How can I do to get 1 occurs only 1 times ?
The problems is to it's print many times.
import java.util.Scanner;
public class ex3 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] num = new int[100];
int i = 0;
System.out.print("Enter the integers between 1 and 50: ");
num[i] = input.nextInt();
while(num[i] != 0){
i++;
num[i] = input.nextInt();
}
for(int j=0;j<i;j++){
int n = 0;
for(int k=0;k<i;k++){
if(num[j] == num[k]){
n++;
}
}
System.out.println(num[j] + " occurs " + n + " times");
}
}
}
Edit this Code
Try this (Refer to code comments for explanations):
import java.util.Scanner;
public class Main {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
int[] num = new int[100];
int i = 0;
while (i < 100) { // Check if the array is already full
System.out.print("Enter 0 to Exit or enter the integers between 1 and 50 (Input #" + (i + 1) + ") : ");
int value = input.nextInt();
if (value == 0) {
break;
}
if (value < 1 || value > 50) { // check if input is between 1 and 50
System.out.println("Input is not between 1 and 50");
} else {
num[i] = value;
System.out.println();
}
i++;
}
System.out.println();
System.out.println("Result: ");
for (int j = 0; j < i; j++) {
int n = 0;
boolean isAlreadyPrinted = false; // flag to check if will be printed or not
for (int k = 0; k < i; k++) {
if (num[j] == num[k]) {
if (j > k) { // this means that the same value is already found and printed
isAlreadyPrinted = true;
}
n++;
}
}
if (!isAlreadyPrinted) {
System.out.println(num[j] + " occurs " + n + " times");
}
}
}
}
The problem is with your for loop.
You should not run the j's value up to i. That's why "1 occurs 2 times" is printing twice. What you have to do is checking the value of the array's certain index has been occurred multiple times before print part executed.
public static<T> T[] subArray(T[] array, int beg, int end) {
return Arrays.copyOfRange(array, beg, end + 1);
}
public static boolean hasDuplicateValues (int[] array, int value )
{
boolean result = false ;
int count = 0 ;
for (int i=0 ; i< array.length; i++)
{
if(array[i] == value)
{
count = count+1 ;
}
}
if(count > 1)
{
result = true;
}
return result;
}
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int[] num = new int[100];
int i = 0;
System.out.print("Enter the integers between 1 and 50: ");
num[i] = input.nextInt();
while(num[i] != 0){
i++;
num[i] = input.nextInt();
}
for(int j=0;j<i;j++){
int n = 0;
for(int k=0;k<i;k++){
if(num[j] == num[k]){
n++;
}
}
int[] subarray = subArray(num, 0, i);
boolean isDuplicate = hasDuplicateValues (subarray , num[i] )
if(isDuplicate == false )
{
System.out.println(num[j] + " occurs " + n + " times");
}
}
}

Beginning Java - Creating a successful binary search algorithm

Design an application that has an array of at least 20 integers. It should call a module that uses the sequential search algorithm to locate one of the values. The module should keep a count of the number of comparisons it makes until it finds the value. Then the program should call another module that uses the binary search algorithm to locate the same value. It should also keep a count of the number of comparisons it makes. Display these values on the screen.
I already have the sequential search working properly, and it displays the number of iterations it took to find the desired value. However, I am having trouble with my binary search module. Every time it searches for a value, it always returns the value 1. Here is the code I have excluding the sequential search module.
Appreciate any help.
//Scanner class
import java.util.Scanner;
public class JavaProgramCh9Ex7_test {
//global scanner to read input
static Scanner keyboard = new Scanner(System.in);
//size of array
final static int SIZE = 20;
//main
public static void main(String[] args) {
//populate the array
int [] twentyNumbers = new int [SIZE];
populateTwentyNumbersArray(twentyNumbers);
//sort the numbers using bubble sorting:
bubbleSort(twentyNumbers);
displayTwentyNumbersSorted(twentyNumbers);
//ask the user for a value to search for:
int desiredValue = getValidInteger("Search for a number", 1, 20);
//start the binary search algorithm:
int binSearchComparison = performBinarySearch (twentyNumbers, desiredValue);
System.out.println(binSearchComparison);
}
//Display the 20 integers in the array in ascending-order:
public static void displayTwentyNumbersSorted (int [] numArray){
System.out.println("");
System.out.println("Here are the 20 numbers sorted in ascending-order");
for (int i = 0; i < numArray.length; i++) {
if(i < 19){
System.err.print(numArray[i] + ", ");
}
else{
System.err.print(numArray[i]);
}
}
}
//Perform the binary search for the user's desired value:
public static int performBinarySearch (int [] numArray, int userValue){
int first = 0;
int middle;
int last = (numArray.length - 1);
int iteration = -1;
boolean found = false;
for (int i = 0; i < numArray.length; i++) {
while ((!found) && (first <= last)) {
middle = ((first + last) / 2);
if (numArray [middle] == userValue) {
found = true;
iteration = (i + 1);
}
if(numArray [middle] > userValue) {
last = (middle - 1);
}
if(numArray [middle] < userValue) {
first = (middle + 1);
}
}
}
return iteration;
}
//Populate the array with 20 random integers:
public static void populateTwentyNumbersArray (int [] numArray){
int number = 0;
for (int i = 0; i < numArray.length; i++) {
do{
number = getRandomNumber(1, 20);
}while (checkNum(numArray, number));
numArray[i] = number;
}
}
//Check to make sure the number is unique:
public static boolean checkNum (int [] numArray, int num) {
boolean value = false;
for (int i = 0; i < numArray.length; i++) {
if (numArray[i] == num) {
value = true;
}
}
return value;
}
//Sort the array in ascending order
public static void bubbleSort(int [] numArray){
int temp;
int maxElement;
for(maxElement = (SIZE - 1); maxElement > 0; maxElement--){
for(int i = 0; i <= (maxElement - 1); i++){
if(numArray[i] > numArray[i + 1]){
temp = numArray[i];
numArray[i] = numArray[i + 1];
numArray[i + 1] = temp;
}
}
}
}
//Get a valid Integer from the user to determine the number of seats sold per section:
public static int getValidInteger(String msg, int low, int high) {
int newValue = getInteger(msg);
//Check that the user entered a valid number within the range:
while (newValue < low || newValue > high) {
System.err.println("Please enter a number from " + low + " to " + high + ".");
newValue = getInteger(msg);
}
return newValue;
}
//Check for a valid Integer input from the user:
public static int getInteger(String msg) {
System.out.println(msg);
while (!keyboard.hasNextInt()) {
keyboard.nextLine();
System.err.println("Invalid integer. Please try again.");
}
int number = keyboard.nextInt();
keyboard.nextLine(); //flushes the buffer
return number;
}
//Get a random number to represent the computer's choice:
public static int getRandomNumber(int low, int high){
return (int)(Math.random() * ((high + 1) - low)) + low;
}
}
In your performBinarySearch you check for the all values of array, this maximizes the binary search complexity, though the loop hasn't any effect on searching. If the value present in the array, then the searching function checks whether it is present or not when i=0 and make found=true. After that the inner while loop don't executes as found=true all the times.
For that reason, iterator=(i+1) for i=0 all the times if the value is present in the array, otherwise iterator=-1.
Consider the below performBinarySearch function :
public static int performBinarySearch(int[] numArray, int userValue) {
int first = 0;
int middle;
int last = (numArray.length - 1);
int iteration = 0;
boolean found = false;
while ((!found) && (first <= last)) {
iteration++;
middle = ((first + last) / 2);
if (numArray[middle] == userValue) {
found = true;
break;
}
if (numArray[middle] > userValue) {
last = (middle - 1);
}
if (numArray[middle] < userValue) {
first = (middle + 1);
}
}
if (found) return iteration;
else return -1;
}
Here, I have reused your code with a simple modification. I have deleted your redundant outer loop and calculated the number of iteration each time the while loop executes. If found then make found=true and break the loop(as I have already found the expected value) and return the value.

How to find sub string of a binary string in java

String s="101010101010";
String sub=""; //substring
int k=2;
package coreJava;
import java.util.Scanner;
public class substring {
public static void main(String args[])
{
String string, sub;
int k, c, i;
Scanner in = new Scanner(System.in);
System.out.println("Enter a string to print it's all substrings");
string = in.nextLine();
i = string.length();
System.out.println("Substrings of \""+string+"\" are :-");
for( c = 0 ; c < i ; c++ )
{
for( k = 1 ; k <= i - c ; k++ )
{
sub = string.substring(c, c+k);
System.out.println(sub);
}
}
}
}
take a binary string s="1010011010"; //etc
take one variable k=2;
take another variable i; //which is the length of the sub string(i>k)
now i want to find sub string of the above string, in such a way that if k=2,the number of 1's in sub string must be 2,if k=3,the number of 1's in substring must be 3 and so on...
Output should be like this:
string s="1010011010"
Enter value of k=2;
Enter length of substring i=3;
substring= 101 110 101 011
Create a "window" the length of your desired substrings which you move along the string, maintaining a count of the number of 1s in your current window. Each iteration you move the window along one, testing the next character outside the current window, the first character in the current window and updating the count accordingly. During each iteration, if your count is equal to the desired length, print the substring from the current window.
public class Substring {
public static void main(String[] args) {
String str = "1010011010";
int k = 2;
int i = 3;
printAllSubstrings(str, i, k);
}
private static void printAllSubstrings(String str, int substringLength, int numberOfOnes) {
// start index of the current window
int startIndex = 0;
// count of 1s in current window
int count = 0;
// count 1s in the first i characters
for (int a = 0; a < substringLength; a++) {
if (str.charAt(a) == '1') {
count++;
}
}
while (startIndex < str.length() - substringLength + 1) {
if (count == numberOfOnes) {
System.out.print(str.substring(startIndex, startIndex + substringLength));
System.out.print(" ");
}
// Test next bit, which will be inside the window next iteration
if (str.length() > startIndex + substringLength && str.charAt(startIndex + substringLength) == '1') {
count ++;
}
// Test the starting bit, which will be outside the window next iteration
if (str.charAt(startIndex) == '1') {
count --;
}
startIndex++;
}
}
}
This outputs:
101 011 110 101
Iterate over the characters and count the number of one's. If the counter reaches the desired number, stop iterating and take the substring from index zero to where you got.
String str = "010101001010";
int count = 0;
int k = 2;
int i = 0;
for (; i < str.length() && count < k; ++i)
{
if (str.charAt(i) == '1') count++;
}
You could use regular expressions:
public class BinaryString {
public static void main(String[] args) {
String binary = "11000001101110";
int count = 3;
String regEx = "1{" + count + "}";
Pattern p = Pattern.compile(regEx);
Matcher m = p.matcher(binary);
if (m.find()) {
int startIndex = m.start();
System.out.println("MATCH (#index " + startIndex + "): "+ m.group());
} else {
System.out.println("NO MATCH!");
}
}
}
OUTPUT
MATCH (#index 10): 111

Categories