Searching and sorting values - java

I try to scan the input one-by-one using charAt and sorting the letters of alphabet. If there is 2 'a's in the input the list array should start with 2. If there is 1 'b' in the input list[1] = 1. If c is used 3 times list[2] = 3. I want to have this for all letters in English.
For example if the input is "I bought a car."
The output should be 2 1 1 0 0 0 1 1 1 0 0 0 0 0 1 0 0 1 0 1 1 0 0 0 0
Note : The method is not case sensitive.
error: method sortInput in class sorting cannot be applied to given types; in line 24
What should I do?
UPDATE : Now I get an output but I get an 26-length array which all has 0's for 26 times.
import java.util.*;
public class sorting
{
public static void main(String[] args)
{
String input;
int i;
int[] list = new int[26];
Scanner scan = new Scanner(System.in);
System.out.println("Enter an input");
input = scan.nextLine();
for(i = 0; i <= list.length; i++)
{
System.out.print(Arrays.toString(sortInput(Integer.toString(list[i]))) + " ");
}
}
public static int[] sortInput(String input)
{
input = input.toLowerCase();
char k,l;
int i, j;
String alphabet;
alphabet = "abcdefghijklmnopqrstuvwxyz";
char[] letter = new char[26];
int[] list = new int[26];
j = 0;
for(i = 0; i <= alphabet.length() - 1; i++)
{
k = alphabet.charAt(i);
letter[i] = k;
}
for(i = 0; i <= input.length() - 1; i++)
{
l = input.charAt(i);
if(letter[i] == l)
{
for(i = 0; i <= input.length() - 1; i++)
{
if(letter[i] == l)
{
j = 0;
j++;
}
}
}
list[i] = j;
}
return list;
}
}

Your instance method sortInput(String) doesn't apply to sortInput(int).
This
sortInput(list[i])
could be something like
sortInput(Integer.toString(list[i]))
or change the method to take an int. Or maybe you wanted
sortInput(input)
but it will also need to be static (or you'll need an instance) as noted by #MikeKobit here.
Edit
Based on your comments. Pass in input and your method should look something like
public static int[] sortInput(String input) {
input = input.toLowerCase();
int[] list = new int[26];
for (char ch : input.toCharArray()) {
if (ch >= 'a' && ch <= 'z') {
list[ch - 'a']++;
}
}
return list;
}
public static void main(String[] args) {
String input = "I bought a car.";
int[] out = sortInput(input);
for (int i : out) {
System.out.print(i);
System.out.print(" ");
}
System.out.println();
}
Edit 2
Without toCharArray(),
public static int[] sortInput(String input) {
input = input.toLowerCase();
int[] list = new int[26];
for (int i = 0, len = input.length(); i < len; i++) {
char ch = input.charAt(i);
if (ch >= 'a' && ch <= 'z') {
list[ch - 'a']++;
}
}
return list;
}

Compare your
System.out.print(sortInput(list[i]) + " ");
with
public int[] sortInput(String input)
You are trying to call it with something else than it expects.

You are trying to call the method sortInput, which is an instance method, from a static context. You can either instantiate the class you are trying to call the method on or in this case it seems like you would want that method to be static.
public static int[] sortInput(String input)
You are also trying to call that method with the incorrect type parameter.
int[] list = new int[26];
...
sortInput(list[i])
You are currently trying to call your method with an int, not a String.

Related

Print the length of maximum subsequence of '1' s

import java.util.Scanner;
class Motu
{
// Returns length of the longest subsequence
// of the form 0*1*0*
public static int longestSubseq(String s)
{
int n = s.length();
int[] count_1 = new int[n + 1];
count_1[0] = 0;
for (int j = 1; j <= n; j++)
{
count_1[j] = count_1[j - 1];
if (s.charAt(j - 1) != '0')
count_1[j]++;
}
// Compute result using precomputed values
int ans = 0;
for (int i = 1; i <= n; i++)
for (int j = i; j <= n; j++)
ans = Math.max(count_1[j] - count_1[i - 1] , ans);
return ans;
}
// Driver code
public static void main(String[] args)
{
#SuppressWarnings("resource")
Scanner sc=new Scanner(System.in);
String s =sc.next();
System.out.println(longestSubseq(s));
}
}
I am trying to make a program to get maximum sequences 1 in a string containing 0's & 1's. But I am unable to make out the logic for it, my program prints a number of 1's in the string which is not my desired output.
Sample input:- 0011100111100
output:- 4
You're quite good, but you're missing one thing : if the char is '0' : reset the counter to zero
for (int j = 1; j <= n; j++) {
if (s.charAt(j - 1) != '0')
count_1[j] = count_1[j - 1] + 1;
else
count_1[j] = 0;
}
But that can be done in one loop only, count with an int, and keep track of the max
public static int longestSubseq(String s) {
int ans = 0;
int count = 0;
for (char c : s.toCharArray()) {
if (c == '1')
count++;
else
count = 0;
ans = Math.max(ans, count);
}
return ans;
}
public static int longestSubSequence(String str, char ch) {
int res = 0;
int count = 0;
for (int i = 0; i < str.length(); i++) {
count = str.charAt(i) == ch ? count + 1 : 0;
res = Math.max(res, count);
}
return res;
}
The input string may be split by the characters that are not 1 (thus all non-1 characters are ignored and subsequences containing only 1 remain), and then the max length of the remaining parts can be found using Stream API:
public static int longestSubSequence(String str, char ch) {
return Arrays.stream(str.split("[^" + ch + "]"))
.mapToInt(String::length)
.max()
.orElse(0);
}
Similarly, a matching pattern can be created, and the max length of the group can be found:
public static int longestSubSequence(String str, char ch) {
return Pattern.compile(ch + "+")
.matcher(str)
.results()
.map(MatchResult::group)
.mapToInt(String::length)
.max()
.orElse(0);
}
Test:
System.out.println(longestSubSequence("00111011001111", '1')); // 4
It's worth mentioning that the characters other than '0' and '1' may be present in the input string, only subsequences of the given char are counted.
As an alternative to the other answers that work with a for-loop:
You could split the sequence into groups of ones with regex. Next, just iterate over the groups and update the count, if the length of the group is bigger than the previous length.
The first group will be 111 and the next one 1111. Thus the count will first be 3 and then it will be updated to 4.
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class CountSubsequence {
public static void main(String []args){
String sequence = "0011100111100";
Pattern pattern = Pattern.compile("(1+)");
Matcher matcher = pattern.matcher(sequence);
int count = 0;
while (matcher.find()) {
int currentLength = matcher.group().length();
if (currentLength > count) count = currentLength;
}
System.out.println(count); // 4
}
}
Since regex is not that performant you might want to use the for-loop in case you care for performance - but that just matters if you execute it a lot.

Generate all possible string combinations by replacing the hidden “#” number sign

My task is to generates all possible combinations of that rows without the hidden # number sign. The input is XOXX#OO#XO and here is the example of what the output should be:
XOXXOOOOXO
XOXXOOOXXO
XOXXXOOOXO
XOXXXOOXXO
I am only allowed to solve this solution iteratively and I am not sure how to fix this and have been working on this code for a week now.
Here is my code:
import java.lang.Math;
public class help {
public static void main(String[] args) {
String str = new String("XOXX#OO#XO");
UnHide(str);
}
public static void UnHide(String str) {
//converting string to char
char[] chArr = str.toCharArray();
//finding all combinations for XO
char[] xo = new char[]{'X', 'O'};
int count = 0;
char perm = 0;
String s = "";
//finding amount of times '#' appears in string
for (int i = 0; i < str.length(); i++) {
if (chArr[i] == '#')
count++;
}
int[] combo = new int[count];
int pMax = xo.length;
while (combo[0] < pMax) {
// print the current permutation
for (int k = 0; k < count; k++) {
//print each character
//System.out.print(xo[combo[i]]);
perm = xo[combo[k]];
s = String.valueOf(perm);
char[] xoArr = s.toCharArray();
String strChar = new String(xoArr);
//substituting '#' to XO combo
for (int i = 0; i < chArr.length; i++) {
for (int j = 0; j < s.length(); j++) {
if (chArr[i] == '#') {
chArr[i] = xoArr[j];
strChar = String.copyValueOf(chArr);
i++;
}
}
i++;
if (i == chArr.length - 1) {
System.out.println(strChar);
i = 0;
}
}
}
System.out.println(); //print end of line
// increment combo
combo[count - 1]++; // increment the last index
//// if increment overflows
for (int i = count - 1; combo[i] == pMax && i > 0; i--) {
combo[i - 1]++; // increment previous index
combo[i] = 0; // set current index to zero
}
}
}
}
Since your input has 2 #'s, there are 2n = 4 permutations.
If you count from 0 to 3, and look at the numbers in binary, you get 00, 01, 10, and 11, so if you use that, inserting O for 0 and X for 1, you can do this using simple loops.
public static void unHide(String str) {
int count = 0;
for (int i = 0; i < str.length(); i++)
if (str.charAt(i) == '#')
count++;
if (count > 30)
throw new IllegalArgumentException("Too many #'s found. " + count + " > 30");
char[] buf = str.toCharArray();
for (int permutation = 0, end = 1 << count; permutation < end; permutation++) {
for (int i = buf.length - 1, bit = 0; i >= 0; i--)
if (str.charAt(i) == '#')
buf[i] = "OX".charAt(permutation >>> bit++ & 1);
System.out.println(buf);
}
}
Test
unHide("XOXX#OO#XO");
Output
XOXXOOOOXO
XOXXOOOXXO
XOXXXOOOXO
XOXXXOOXXO
You can iteratively generate all possible combinations of strings using streams as follows:
public static String[] unHide(String str) {
// an array of substrings around a 'number sign'
String[] arr = str.split("#", -1);
// an array of possible combinations
return IntStream
// iterate over array indices
.range(0, arr.length)
// append each substring with possible
// combinations, except the last one
// return Stream<String[]>
.mapToObj(i -> i < arr.length - 1 ?
new String[]{arr[i] + "O", arr[i] + "X"} :
new String[]{arr[i]})
// reduce stream of arrays to a single array
// by sequentially multiplying array pairs
.reduce((arr1, arr2) -> Arrays.stream(arr1)
.flatMap(str1 -> Arrays.stream(arr2)
.map(str2 -> str1 + str2))
.toArray(String[]::new))
.orElse(null);
}
// output to the markdown table
public static void main(String[] args) {
String[] tests = {"XOXX#OOXO", "XOXX#OO#XO", "#XOXX#OOXO#", "XO#XX#OO#XO"};
String header = String.join("</pre> | <pre>", tests);
String matrices = Arrays.stream(tests)
.map(test -> unHide(test))
.map(arr -> String.join("<br>", arr))
.collect(Collectors.joining("</pre> | <pre>"));
System.out.println("| <pre>" + header + "</pre> |");
System.out.println("|---|---|---|---|");
System.out.println("| <pre>" + matrices + "</pre> |");
}
XOXX#OOXO
XOXX#OO#XO
#XOXX#OOXO#
XO#XX#OO#XO
XOXXOOOXOXOXXXOOXO
XOXXOOOOXOXOXXOOOXXOXOXXXOOOXOXOXXXOOXXO
OXOXXOOOXOOOXOXXOOOXOXOXOXXXOOXOOOXOXXXOOXOXXXOXXOOOXOOXXOXXOOOXOXXXOXXXOOXOOXXOXXXOOXOX
XOOXXOOOOXOXOOXXOOOXXOXOOXXXOOOXOXOOXXXOOXXOXOXXXOOOOXOXOXXXOOOXXOXOXXXXOOOXOXOXXXXOOXXO
The process would probably be best to calculate the number of permutations, then loop through each to define what combination of characters to use.
For that, we'll have to divide the permutation number by some value related to the index of the character we're replacing, which will serve as the index of the character to swap it to.
public static void test(String word) {
// Should be defined in class (outside method)
String[] replaceChars = {"O", "X"};
char replCharacter = '#';
String temp;
int charIndex;
int numReplaceable = 0;
// Count the number of chars to replace
for (char c : word.toCharArray())
if (c == replCharacter)
numReplaceable++;
int totalPermutations = (int) Math.pow(replaceChars.length, numReplaceable);
// For all permutations:
for (int permNum = 0; permNum < totalPermutations; permNum++) {
temp = word;
// For each replacement character in the word:
for (int n = 0; n < numReplaceable; n++) {
// Calculate the character to swap the nth replacement char to
charIndex = permNum / (int) (Math.pow(replaceChars.length, n))
% replaceChars.length;
temp = temp.replaceFirst(
replCharacter + "", replaceChars[charIndex]);
}
System.out.println(temp);
}
}
Which can produces:
java Test "#TEST#"
OTESTO
XTESTO
OTESTX
XTESTX
This can also be used with any number of characters, just add more to replaceChars.

How to get the first and last digits of a number and combine both

Example:
If i give a number 12345 , i should get an answer like 15243
in the same way if it is 123456 , i should get 162534
i have already tried getting the first value and appending the last value using reverse technique
public class MyFirstJavaProgram {
public static void main(String []args) {
String str = "12345";
String val = str;
char a;
int num=0;
int d=0;
int n;
for(int i=0; i<=str.length()/2; i++) {
a = str.charAt(i);
num = num*10+Character.getNumericValue(a);
if(Integer.parseInt(str)!=0){
d=Integer.parseInt(str)%10;
num = num*10+d;
n=Integer.parseInt(str)/10;
str = Integer.toString(n);
}
}
System.out.println(num);
}
}
i should get the result if they give even number or odd number
Without doing what is presumably homework for you, imagine you have a loop in which there are two integer variables a and b. Variables a and b are string indexes.
You are taking characters from the string at positions a,b,a,b,a,b etc.
BUT the values of a and b need to change for each iteration. If the length of the String is n, a will follow the sequence 0,1,2,3... and b will follow the sequence (n-1),(n-2),(n-3) etc
The loop should continue while a < b.
This is my solution for your exercise:
Method parameter "A" is Integer number you want to parse.
First you create Char Array from given number and then iterate through it. If i%2 == 0 it means that you take number from beginning otherwise from the end
public static int algorithm(int A) {
StringBuilder shuffleNumber = new StringBuilder();
char[] numbersArray = Integer.toString(A).toCharArray();
for (int i = 0; i < numbersArray.length; i++) {
if (i % 2 == 0)
shuffleNumber.append(numbersArray[i / 2]);
else
shuffleNumber.append(numbersArray[numbersArray.length - i / 2 - 1]);
}
return Integer.parseInt(shuffleNumber.toString());
}
If you want a solution without string methods, there is a not so complicated one:
public static void main(String[] args) throws IOException {
String str = "1234567";
int len = str.length();
int num=0;
char a;
for(int i = 0; i < len / 2; i++) {
a = str.charAt(i);
num = num * 10 + Character.getNumericValue(a);
a = str.charAt(len -1 - i);
num = num * 10 + Character.getNumericValue(a);
}
if (len % 2 == 1) {
a = str.charAt(str.length() / 2);
num = num * 10 + Character.getNumericValue(a);
}
System.out.println(num);
}
will print
1726354
Check the last if that takes care the case of odd number of digits in the number.
public class MyFirstJavaProgram {
public static void main(String []args) {
String str = "12345678";
int val = str.length();
char a;
int num=0;
int d=0;
int n;
for(int i=0; i<=str.length()-2; i++)
{
a = str.charAt(i);
num = num*10+Character.getNumericValue(a);
if(Integer.parseInt(str)!=0)
{
d=Integer.parseInt(str)%10;
num = num*10+d;
n=Integer.parseInt(str)/10;
str = Integer.toString( n );
}
}
if(val%2!=0)
{
num = num*10+Integer.parseInt(str)%10;
System.out.println(num);
}
else{System.out.println(num);}
}
}
this is working for my question... Thanks all
Following is my solution -
public static void solution(String s) {
StringBuffer st = new StringBuffer();
for (int i = 0; i < s.length() / 2; i++) {
st.append(s.charAt(i));
st.append(s.charAt(s.length() - 1 - i)); // appending characters from last
}
if (s.length() % 2 != 0) {
st.append(s.charAt(s.length() / 2));
}
System.out.println(Integer.parseInt(st.toString()));
}
my logic is to keep appending first and last character to new string till i < s.length/2.
If string is of odd length , it means only last character is remaining, append it to your resultant string.
Else , no character is left and you have your complete string.

Return array from class in Java

The array that returns from method contain undesirable values. I don't know why.
This is DriverExam Class:
public class DriverExam
{
private char[] answer = {'B','D','A','A','C','A','B','A','C','D',
'B','C','D','A','D','C','C','B','D','A'};
private char[] stuAnswer = new char[20];
private int totalCorrect = 0;
private int[] missed = new int[20];
public DriverExam(char stuAnswer[])
{
for (int i = 0; i < stuAnswer.length; i++)
{
this.stuAnswer[i] = stuAnswer[i];
}
}
public int gettotalCorrect()
{
int k = 0;
for (int i = 0; i < stuAnswer.length; i++)
{
if (stuAnswer[i] == answer[i])
totalCorrect++;
}
return totalCorrect;
}
public int gettotalIncorrect()
{
return 20-totalCorrect;
}
public int[] getMissed()
{
int k = 0;
for (int i = 0; i < stuAnswer.length; i++)
{
if (stuAnswer[i] != answer[i])
{
missed[k] = i;
k++;
}
}
return missed;
}
}
This is the main program:
import java.util.Scanner;
public class Main6
{
public static void main(String[] args)
{
char[] answer = new char[20];
int[] missed2;
String str;
Scanner keyboard = new Scanner(System.in);
for (int i = 1; i <= 20; i++)
{
System.out.println("Enter the answer for question #"+i);
str = keyboard.nextLine();
while (Character.toUpperCase(str.charAt(0)) != 'A'
&& Character.toUpperCase(str.charAt(0)) != 'B'
&& Character.toUpperCase(str.charAt(0)) != 'C'
&& Character.toUpperCase(str.charAt(0)) != 'D')
{
System.out.println("Your input is invalid. Only accept A, B, C, or D");
System.out.println("Enter the answer for question #"+i);
str = keyboard.nextLine();
}
answer[i-1] = Character.toUpperCase(str.charAt(0));
}
DriverExam de = new DriverExam (answer);
System.out.print("***FINAL RESULT:");
System.out.print("\nTotal correct answers: "+de.gettotalCorrect());
System.out.print("\nTotal incorrect answers: "+de.gettotalIncorrect());
System.out.print("\nQuestions missed: ");
missed2 = de.getMissed();
for (int i = 0; i < missed.length; i++)
{
System.out.print(i+" ");
}
}
}
In DriverExam class I return an array named "missed" to the main program. In main program, I use an array named "missed2" to store the array returned. But when I print the result (I type all the answer with "A"). It's like below:
FINAL RESULT:
Total correct answers: 6
Total incorrect answers: 14
Questions missed: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
The question missed result is strange and incorrect.
What you want for "missed" to be is a variable length result. To do this with an array, you will need a value that signals the end of the results. Here, I've used -1.
public int[] getMissed()
{
int k = 0;
for (int i = 0; i < stuAnswer.length; i++)
{
if (stuAnswer[i] != answer[i])
{
missed[k] = i;
k++;
}
}
if(k < missed.length)
{
missed[k] = -1
}
return missed;
}
Then, in your for loop, check for the end value. The strange values are probably default int values caused by not setting them explicitly in the array.
for (int i = 0; i < missed2.length && missed2[i] != -1; i++)
{
System.out.print(i+" ");
}

How can I print out an array list in a foursome fragmented list?

This is My Array code with given string numbers(0098765424100304643528):
public class Main
{
public static void main(String[] args)
{
String mynumbers = "0098765424100304643528";
int len = mynumbers.length();
char[] tempCharArray = new char[len];
for (int i = 0; i < len; i++)
{
tempCharArray[i] = mynumbers.charAt(i);
System.out.print(tempCharArray[i]+"->");
}
System.out.println();
}
}
this is the result after running :
0->0->9->8->7->6->5->4->2->4->1->0->0->3->0->4->6->4->3->5->2->8->
I want to change it such below (How can I fragment my array in foursome ?)
0098->7654->2410->0304->4352->8
System.out.println(StringUtils.join("0098765424100304643528".split("(?<=\\G.{4})"), "->"));
maybe you write the result is wrong as you say (foursome), if you just want the output foursome , you can do like that :
for (int i = 0; i < len; i++)
{
tempCharArray[i] = mynumbers.charAt(i);
System.out.print(tempCharArray[i]);
if((i+1)%4==0)
{
System.out.print("->");
}
}
We will check if value of i is not 0 and i is divisible by 4. If true, then print -> else print number without it.
public class Main
{
public static void main(String[] args)
{
String mynumbers = "0098765424100304643528";
int len = mynumbers.length();
char[] tempCharArray = new char[len];
for (int i = 0; i < len; i++)
{
tempCharArray[i] = mynumbers.charAt(i);
if(i > 0 && i%4 == 0)
System.out.print(tempCharArray[i]+"->");
else
System.out.print(tempCharArray[i]);
}
System.out.println();
}
}
You could check if i is dividable by 4, if it is add an arrow, otherwise just print the number. Ie:
public class Main
{
public static void main(String[] args)
{
String mynumbers = "0098765424100304643528";
int len = mynumbers.length();
char[] tempCharArray = new char[len];
for (int i = 0; i < len; i++)
{
tempCharArray[i] = mynumbers.charAt(i);
if((i % 4 == 0) && i > 0)
System.out.print(tempCharArray[i]+"->");
else
System.out.print(tempCharArray[i]);
}
System.out.println();
}
}
Here the % is the modulus operator, which tells us the remainder of something divided by something else, ie: 5 % 4 = 1 since 5 / 4 = 1 * 4 + 1

Categories