How to find sub string of a binary string in java - 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

Related

Sum of the Difference between the first letter and the last letter, second letter and the penultimate letter, and so on till the center of the word

If the given string is “WORLD WIDE WEB”
In each word, find the Sum of the Difference between the first letter and the last letter, second letter and the penultimate letter, and so on till the center of the word.
WORLD = [W-D]+[O-L]+[R] = [23-4]+[15-12]+[18] = [19]+[3]+[18] = [40]
WIDE = [W-E]+[I-D] = [23-5]+[9-4] = [18]+[5] = [23]
WEB = [W-B]+[E] = [23-2]+[5] = [21]+[5] = [26]
Concatenate the sums of each word to form the result
[40] [23] [26]
[402326]
class Strcode{
public static void main(String args[]){
int xd[]=new int[100];
int n[]=new int[100];
int position=0;
String input = "hello".toLowerCase(); //note the to lower case in order to treat a and A the same way
for( int i = 0; i < input.length(); ++i) {
position = input.charAt(i) - 'a' + 1;
System.out.println(position);
for( int k=0,j=position.length()-1;k<j;k++,j--){
xd[k]=Math.abs(xd[k]-xd[j]);
System.out.println(xd[k]);
}
}
}
}
By the above code i am able to get numerical value of letters, but failed to do next step of subtraction.
It is one of the basic problems for beginners. Let me crack it down for you. You need to perform following steps :
Extract each word from your given string. ( Do it on your own! )
Calculate sum for each word. ( Find below code! )
Concatenate these sums. ( Easy! )
public class sample{
public static void main(String args[]){
// Do your part of code here
String sampleWord = "hello";
int individualWordSum = countSum(sampleWord);
}
public static int countSum(String word){
String input = word.toLowerCase();
int sum = 0;
for( int i = 0; i < input.length()/2; i++) {
int s = (input.charAt(i) - 'a') - (input.charAt(input.length() - 1 - i) - 'a');
sum += Math.abs(s);
}
if(input.length()%2!=0){
sum += input.charAt(input.length()/2) - 'a' + 1;
}
System.out.println("sum for " + input + " is " + sum);
return sum;
}
}
Here is the complete code you need, but first try on your own.
public class sample{
public static void main(String args[]){
String sentence = "WORLD WIDE WEB";
String words[] = sentence.split(" ");
String result = "";
for(String word : words){
result += String.valueOf(countSum(word));
}
System.out.println("Sum for " + sentence + " is " + result);
}
public static int countSum(String word){
String input = word.toLowerCase();
int sum = 0;
for( int i = 0; i < input.length()/2; i++) {
int s = (input.charAt(i) - 'a') - (input.charAt(input.length() - 1 - i) - 'a');
sum += Math.abs(s);
}
if(input.length()%2!=0){
sum += input.charAt(input.length()/2) - 'a' + 1;
}
return sum;
}
}
You can make it quite simpler if instead of implementing the described logic, you analyze it and get a simpler solution.
Instead of summing up the difference between the first letter and the last letter and so on, you can sum the first half of the word (including the middle letter if the word is of odd length) and subtract the second half.
String sentance = "WORLD";
int middle = Math.ceil(sentance.length() / 2);
int sum = 0;
for (int i = 0; i < sentance.length(); i++)
{
if (i <= middle)
{
sum += sentance[i] - 'A' + 1;
}
else
{
sum -= sentance[i] - 'A' + 1;
}
}
System.out.println("Sum: " + sum);
You'll get:
Sum: 40

how to count the number of letters in an array java

I have an assignment about how to count the number of letters in an array.
Here is my code:
import java.util.Scanner;
public class task1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
//Create a scanner object
Scanner input = new Scanner(System.in);
//Prompt user's input
System.out.println("Enter strings (use a space to separate them; hit enter to finish) : ");
String str = input.nextLine();
// use split to divide the string into different words cutting by " "
String [] wordsArray = str.trim().split(" ");
System.out.println("The length of string is " + wordsArray.length);
for(int i = 0 ; i < wordsArray.length; i++){
char [] eachLetterinArray = wordsArray[i].toCharArray();
for(int j = 0,count = 0 ; j < eachLetterinArray.length; j++){
if( (eachLetterinArray[j]+'a'-97 >=65 && eachLetterinArray[j]+'a'-97 <=90 )
|| (eachLetterinArray[j]+'a'-97 >=97 && eachLetterinArray[j]+'a'-97 <=122 ) ){
count++;
}
System.out.print(count);
}
}
}
if I enter "end tr"
the output is "12312"
but what I want is "3 and 2 "
I have tried a lot and still have nothing to do about this...
can you help me?
You want to print count per word, but you are printing for each character. Just print the count variable outside of the inner loop.
for (int i = 0; i < wordsArray.length; i++) {
char[] eachLetterinArray = wordsArray[i].toCharArray();
int count = 0;
for (int j = 0; j < eachLetterinArray.length; j++) {
if ((eachLetterinArray[j] + 'a' - 97 >= 65 && eachLetterinArray[j] + 'a' - 97 <= 90)
|| (eachLetterinArray[j] + 'a' - 97 >= 97 && eachLetterinArray[j] + 'a' - 97 <= 122)) {
count++;
}
}
System.out.println(count);
}
Improvement:
Instead of the little bit complex condition, you can do this way also:
if (Character.isLetter(eachLetterinArray[j])) {
count++;
}
int countedLength = 0;
for(String string: arrayList) {
countedLength += string.length();
}
//Your count of Number of Letters in Array
System.out.pritnln(countedLength);
Or if you want to count every letter unique, do a new for in this for like
if(letter.equals("a")) {
letterVariableCountA++;
}
You are using space to split the word and count the letters. So use split() on string.
split() takes a string which splits the word. In your case it is space.
It returns splitted strings as an array. Just iterate over strings and use length() on string to get the number of characters present in the word.
public class Main
{
public static void main(String[] args)
{
int count;
String s = "This is your string for example";
String[] split = s.split(" ");
for(String str: split)
{
char[] ch = str.toCharArray(); // convert string to char array
count = 0; // reset count for every new word/string
for(char c: ch) // iterate over all the characters
{
if(Character.isLetter(c)) // Returns true if the character is a Letter
{
count++; // increase the count to represent no. of letters
}
}
System.out.print(count + " "); // print the no.of characters that are letters in a word/string.
}
}
}
This should do the trick, you were printing your count within the loop which is why it was counting. If you set the inital count value outside of it, you can then print it once the loop is complete, and then set it back to 0 before it starts on the next word.
public static void main(String[] args) {
String str = "test1 phrase";
int count = 0;
// use split to divide the string into different words cutting by " "
String[] wordsArray = str.trim().split(" ");
System.out.println("The length of string is " + wordsArray.length);
for (int i = 0; i < wordsArray.length; i++) {
char[] eachLetterinArray = wordsArray[i].toCharArray();
for (int j = 0; j < eachLetterinArray.length; j++) {
if ((eachLetterinArray[j] + 'a' - 97 >= 65 && eachLetterinArray[j] + 'a' - 97 <= 90)
|| (eachLetterinArray[j] + 'a' - 97 >= 97 && eachLetterinArray[j] + 'a' - 97 <= 122)) {
count++;
}
}
System.out.print(count + "\n");
count = 0;
}
}
with the above example I got an output of
The length of string is 2
4
6

Finding Consecutive Duplicate integers in an array

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 )

Find the longest sequence of same characters in a string

This code supposed to output the longest run on which a character in a string has a consecutive runs of itself. Though the problem is that it outputs: 8 (which should be 5 instead). I just would like to ask what seems to be the problem regarding this code.
public class Sample {
public static void main(String[] args) {
String setofletters = "aaakkcccccczz"; /* 15 */
int output = runLongestIndex(setofletters);
System.out.println("Longest run that first appeared in index:" + output);
}
public static int runLongestIndex(String setofletters) {
int ctr = 0;
int ctrstor = 0;
int ii = 0;
int output = 0;
// loops until the last character in the string
for (int i = 0; i < setofletters.length() - 1; i++) {
// checks if the letter is the same to the next
if (setofletters.charAt(i) == setofletters.charAt(i++)) {
ctr++;
ii = i++;
// loops until the letter in the index is no longer equal
while (setofletters.charAt(i) == setofletters.charAt(ii)) {
ii++;
ctr++;
}
if (ctr > ctrstor) {
output = i;
}
// storing purposes
ctrstor = ctr;
}
// resets the counter
ctr = 0;
}
return output;
}
}
UPDATE Sorry, I misunderstood your question a bit, you need to make the following changes in your code to make it work.(lines with comments)
public static int runLongestIndex(String setofletters){
int ctr = 1; // every character is repeated at least once, so you should initialize it to 1, not 0
int ctrstor = 0;
int ii = 0;
int output = 0;
for (int i = 0; i < setofletters.length() - 1; i++) {
if (i < setofletters.length() - 1 && setofletters.charAt(i) == setofletters.charAt(i+1)) { // i++ is not same as i+1
ctr++;
ii = i+1; // i++ is not same as i+1
while (setofletters.charAt(i) == setofletters.charAt(ii)) {
ii++;
ctr++;
}
if (ctr > ctrstor) {
output = i;
}
ctrstor = ctr;
}
ctr = 1; // for the same reason I mentioned above
}
return output;
}
EDIT : the easiest way to write your code is :
public static int runLongestIndex(String setofletters){
int ctr = 1;
int output = 0;
int j=0;
for(int i=0; i<setofletters.length()-1;i++){
j=i;
while(i <setofletters.length()-1 && setofletters.charAt(i)==setofletters.charAt(i+1)){
i++;
ctr++;
}
if(ctr>output){
output=j;
}
ctr = 1;
}
return output;
}
Why are you assigning i to output? You should assign ctr to output.
change
if(ctr>ctrstor){
output=i;
}
to
if(ctr>ctrstor){
output=ctr;
}
and also I think you should change
if(setofletters.charAt(i)==setofletters.charAt(i++))
to
if(i<setofletters.length()-1 && setofletters.charAt(i)==setofletters.charAt(i+1)){
and you should intialize ctr to 1 but not 0 because every character is repeated at least once.
I'll give you a Scala implementation for that problem.
Here it is the automatic test (in BDD style with ScalaTest)
import org.scalatest._
class RichStringSpec extends FlatSpec with MustMatchers {
"A rich string" should "find the longest run of consecutive characters" in {
import Example._
"abceedd".longestRun mustBe Set("ee", "dd")
"aeebceeedd".longestRun mustBe Set("eee")
"aaaaaaa".longestRun mustBe Set("aaaaaaa")
"abcdefgh".longestRun mustBe empty
}
}
Following is the imperative style implementation, with nested loops and mutable variables as you would normally choose to do in Java or C++:
object Example {
implicit class RichString(string: String) {
def longestRun: Set[String] = {
val chunks = mutable.Set.empty[String]
val ilen = string.length
var gmax = 0
for ((ch, curr) <- string.zipWithIndex) {
val chunk = mutable.ListBuffer(ch)
var next = curr + 1
while (next < ilen && string(next) == ch) {
chunk += string(next)
next = next + 1
}
gmax = chunk.length max gmax
if (gmax > 1) chunks += chunk.mkString
}
chunks.toSet.filter( _.length == gmax )
}
}
}
Following is a functional-style implementation, hence no variables, no loops but tail recursion with result accumulators and pattern matching to compare each character with the next one (Crazy! Isn't it?):
object Example {
implicit class RichString(string: String) {
def longestRun: Set[String] = {
def recurse(chars: String, chunk: mutable.ListBuffer[Char], chunks: mutable.Set[String]): Set[String] = {
chars.toList match {
case List(x, y, _*) if (x == y) =>
recurse(
chars.tail,
if (chunk.isEmpty) chunk ++= List(x, y) else chunk += y,
chunks
)
case Nil =>
// terminate recursion
chunks.toSet
case _ => // x != y
recurse(
chars.tail,
chunk = mutable.ListBuffer(),
chunks += chunk.mkString
)
}
}
val chunks = recurse(string, mutable.ListBuffer(), mutable.Set.empty[String])
val max = chunks.map(_.length).max
if (max > 0) chunks.filter( _.length == max ) else Set()
}
}
}
For example, for the given "aeebceeedd" string, both implementations above will build the following set of chunks (repeating characters)
Set("ee", "eee", "dd")
and they will filter those chunks having the maximum length (resulting "eee").
This code should work for any length of string sequence.
public class LongestStringSequqnce {
static String myString = "aaaabbbbcccchhhhiiiiibbbbbbbbbccccccc";
static int largestSequence = 0;
static char longestChar = '\0';
public static void main(String args[]) {
int currentSequence = 1;
char current = '\0';
char next = '\0';
for (int i = 0; i < myString.length() - 1; i++) {
current = myString.charAt(i);
next = myString.charAt(i + 1);
// If character's are in sequence , increase the counter
if (current == next) {
currentSequence += 1;
} else {
if (currentSequence > largestSequence) { // When sequence is
// completed, check if
// it is longest
largestSequence = currentSequence;
longestChar = current;
}
currentSequence = 1; // re-initialize counter
}
}
if (currentSequence > largestSequence) { // Check if last string
// sequence is longest
largestSequence = currentSequence;
longestChar = current;
}
System.out.println("Longest character sequence is of character "
+ longestChar + " and is " + largestSequence + " long");
}
}
Source : http://www.5balloons.info/program-java-code-to-find-longest-character-sequence-in-a-random-string/
if(ctr>ctrstor){
output=i;
}
//storing purposes
ctrstor=ctr;
This looks like the problem. So if you find 8 consecutive characters, it will set output to 8, and proceed. The next time thru, it finds 3 consecutive characters, so doesn't set output, but sets ctrstor. Next time thru it finds 4 consecutive characters, and this will set output to 4
There are few traps in the code that your logic felt in:
Code incorrectly assumes that there is always next character to compare current one.
This fails for string like "a" or the last character in any string.
Code does not store the max count of characters but only the max index (i).
MaxCount is needed to compare the next chars sequence size.
Loop for and loop while repeat the same subset of characters.
Also variable name style makes it harder to understand the code.
After correcting above
public static int runLongestIndex(String setofletters) {
int maxCount = 0;
int maxIndex = 0;
// loops each character in the string
for (int i = 0; i < setofletters.length() - 1; ) {
// new char sequence starts here
char currChar = setofletters.charAt(i);
int count = 1;
int index = i;
while ( (index < setofletters.length() - 1) &&
(currChar == setofletters.charAt(++index)) ) {
count++;
}
if (count > maxCount) {
maxIndex = i;
maxCount = count;
}
i = index;
}
return maxIndex;
}
See Java DEMO
I think you don't need an internal loop:
public static int runLongestIndex(String setofletters) {
if (setofletters == null || setofletters.isEmpty()) {
return -1;
}
int cnt = 1;
char prevC = setofletters.charAt(0);
int maxCnt = 1;
//char maxC = prevC;
int maxRunIdx = 0;
int curRunIdx = 0;
for (int i = 1; i < setofletters.length(); i++){
final char c = setofletters.charAt(i);
if (prevC == c) {
cnt++;
} else {
if (cnt > maxCnt) {
maxCnt = cnt;
//maxC = prevC;
maxRunIdx = curRunIdx;
}
cnt = 1;
curRunIdx = i;
}
prevC = c;
}
if (setofletters.charAt(setofletters.length() - 1) == prevC) {
if (cnt > maxCnt) {
//maxC = prevC;
maxCnt = cnt;
maxRunIdx = curRunIdx;
}
}
return maxRunIdx;
}
and this code:
System.out.println(runLongestIndex("aaakkcccccczz"));
gives you
5
This is how a "colleague" of mine is understanding to write readable code in order to solve this problem, even if this is working :)
public static int count (String str) {
int i = 0;
while(i < str.length()-1 && str.charAt(i)==str.charAt(i+1))
i ++;
return ++i;
}
public static int getLongestIndex(String str){
int output = 0;
for(int i=0, cnt = 1, counter = 0 ; i<str.length() - 1;i += cnt, cnt = count(str.substring(i)), output = (counter = (cnt > counter ? cnt : counter)) == cnt ? i : output);
return output;
}
int indexOfLongestRun(String str) {
char[] ar = str.toCharArray();
int longestRun = 0;
int lastLongestRun = 0;
int index = 0;
for(int i = ar.length-1; i>0; i--){
if(ar[i] == ar[i-1]){
longestRun++;
}else{
if(longestRun > lastLongestRun){
lastLongestRun = longestRun;
longestRun = 0;
index = i;
}
}
}
return index;
Well, the solution a bit depends on the additional requirements. Here is the code which returns the FIRST longest sequence of a repeated character int the given string, meaning if you have a second sequence with the same length you never get it out :(. But still, this is a simple and clear solution here, so good news - it works! :)
string = 'abbbccddddddddeehhhfffzzzzzzzzdddvyy'
longest_sequence = ''
for i in range(len(string)):
is_sequence = True
ch_sequence = ''
while is_sequence:
ch_sequence += string[i]
if i+1 < len(string) and string[i]==string[i+1]:
i += 1
else:
is_sequence = False
if len(ch_sequence) > len(longest_sequence):
longest_sequence = ch_sequence
print (longest_sequence)
#Paolo Angioletti already provided an answer using Scala, but it's more complicated than it needs to be. The idea is not very different from Run-length encoding. Time complexity O(n).
def longestConsecutive(s: String): (Char, Int) = {
Iterator.iterate(('\u0000', 0, 0)) { case (ch, longestRun, i) =>
val run = (i until s.length)
.takeWhile(s(_) == s(i))
.size
if (run > longestRun) (s(i), run, i + run)
else (ch, longestRun, i + run)
}
.dropWhile(i => s.isDefinedAt(i._3))
.take(1)
.map(x => (x._1, x._2))
.next()
}
Tested with:
("s", "ch", "n")
----------------
("", '\u0000', 0),
("a", 'a', 1),
("aabcddbbbea", 'b', 3),
("abcddbbb", 'b', 3),
("cbccca", 'c', 3)
#include <iostream>
#include<algorithm>
using namespace std;
int main() {
string s="abbcccccbbffffffffff";
//cin>>s;
int count=1;
int maxcount=1;
int start=0;
int ps=0;
for (int i=0;i<s.size()-1;i++)
{
if(s.at(i)==s.at(i+1))
{
count +=1;
maxcount=max(maxcount,count);
}
else
{
ps=max(ps,start+count);
count =1;
start=i;
}
}
for(int i=1;i<=maxcount;i++)
{
cout<<s.at(i+ps);
}
// your code goes here
return 0;
}
This is the simplest I can think of and it will print the number of the longest sequenced identical characters in a one line string.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String s = scanner.nextLine();
scanner.close();
int count = 0;
int curCount = 1;
for (int i = 0; i < s.length() -1; i++) {
if (s.charAt(i) == s.charAt(i + 1)) {
curCount++;
if (curCount > count) {
count = curCount;
}
}else {
if (curCount > count) {
count = curCount;
}
curCount = 1;
}
}
System.out.println(count);
}

Count of most occurring digit... Find the digit that occurs most in a given number

the following s the code to
Find the number of occurrences of a given digit in a number.wat shall i do in order to Find the digit that occurs most in a given number.(should i create array and save those values and then compare)
can anyone please help me ..
import java.util.*;
public class NumOccurenceDigit
{
public static void main(String[] args)
{
Scanner s= new Scanner(System.in);
System.out.println("Enter a Valid Digit.(contaioning only numerals)");
int number = s.nextInt();
String numberStr = Integer.toString(number);
int numLength = numberStr.length();
System.out.println("Enter numer to find its occurence");
int noToFindOccurance = s.nextInt();
String noToFindOccuranceStr = Integer.toString(noToFindOccurance);
char noToFindOccuranceChar=noToFindOccuranceStr.charAt(0);
int count = 0;
char firstChar = 0;
int i = numLength-1;
recFunNumOccurenceDigit(firstChar,count,i,noToFindOccuranceChar,numberStr);
}
static void recFunNumOccurenceDigit(char firstChar,int count,int i,char noToFindOccuranceChar,String numberStr)
{
if(i >= 0)
{
firstChar = numberStr.charAt(i);
if(firstChar == noToFindOccuranceChar)
//if(a.compareTo(noToFindOccuranceStr) == 0)
{
count++;
}
i--;
recFunNumOccurenceDigit(firstChar,count,i,noToFindOccuranceChar,numberStr);
}
else
{
System.out.println("The number of occurance of the "+noToFindOccuranceChar+" is :"+count);
System.exit(0);
}
}
}
/*
* Enter a Valid Digit.(contaioning only numerals)
456456
Enter numer to find its occurence
4
The number of occurance of the 4 is :2*/
O(n)
keep int digits[] = new int[10];
every time encounter with digit i increase value of digits[i]++
the return the max of digits array and its index. that's all.
Here is my Java code:
public static int countMaxOccurence(String s) {
int digits[] = new int[10];
for (int i = 0; i < s.length(); i++) {
int j = s.charAt(i) - 48;
digits[j]++;
}
int digit = 0;
int count = digits[0];
for (int i = 1; i < 10; i++) {
if (digits[i] > count) {
count = digits[i];
digit = i;
}
}
System.out.println("digit = " + digit + " count= " + count);
return digit;
}
and here are some tests
System.out.println(countMaxOccurence("12365444433212"));
System.out.println(countMaxOccurence("1111111"));
declare a count[] array
and change your find function to something like
//for (i = 1 to n)
{
count[numberStr.charAt(i)]++;
}
then find the largest item in count[]
public class Demo{
public static void main(String[] args) {
System.out.println("Result: " + maxOccurDigit(327277));
}
public static int maxOccurDigit(int n) {
int maxCount = 0;
int maxNumber = 0;
if (n < 0) {
n = n * (-1);
}
for (int i = 0; i <= 9; i++) {
int num = n;
int count = 0;
while (num > 0) {
if (num % 10 == i) {
count++;
}
num = num / 10;
}
if (count > maxCount) {
maxCount = count;
maxNumber = i;
} else if (count == maxCount) {
maxNumber = -1;
}
}
return maxNumber;
}}
The above code returns the digit that occur the most in a given number. If there is no such digit, it will return -1 (i.e.if there are 2 or more digits that occurs same number of times then -1 is returned. For e.g. if 323277 is passed then result is -1). Also if a number with single digit is passed then number itself is returned back. For e.g. if number 5 is passed then result is 5.

Categories