What is the mistake in my code?
Given a string consisting of lowercase letters, arrange all its letters in ascending order.
Input: The first line of the input contains T, denoting number of testcases. Then follows description of each testcase. The first line of the testcase contains positive integer N denoting the length of string. The second line contains the string.
Output: For each testcase, output the sorted string.
Constraints:
1 <= T <= 100
1 <= N <= 100
import java.util.*;
class GFG {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
for (int i = 1; i <= t; i++) {
int n = sc.nextInt();
sc.nextLine();
String S = sc.nextLine();
String sor = "";
for (int j = 0; j < n; j++) {
int min = j;
for (int k = j + 1; k < n; k++) {
if (S.charAt(k) > S.charAt(min)) {
min = k;
}
}
sor += S.substring(min, min + 1);
}
System.out.println(sor);
}
}
}
For Input:
1
5
edcab
Output:
edcbb
Expected Output:
abcde
import java.util.*;
class GFG {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
for (int i = 1; i <= t; i++) {
int n = sc.nextInt();
sc.nextLine();
String S = sc.nextLine();
System.out.println("S: "+S);
String sor = "";
for (int j = 0; n > 0; j++) {
int min = 0;
for (int k = 0; k < n; k++) {
if (S.charAt(k) < S.charAt(min)) {
min = k;
}
}
sor += S.substring(min, min + 1);
S = S.substring(0, min) + S.substring(min + 1);
n--;
}
System.out.println(sor);
}
}
}
This code does what you want. I changed > to < and I removed every char that added to sorted String from unsorted String. This way we don't need to deal with the same char again and again.
You are not exchanging the place of the min character after finding it. But Strings in java are immutable so you can't swap the places of characters in it. I suggest you convert your String to a char[] so that you can swap the characters:
public static void main (String[] args){
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
for(int i=1; i<=t; i++){
int n = sc.nextInt();
sc.nextLine();
String S = sc.nextLine().toCharArray(); // convert it to char array
char[] sor = new char[S.length];
for(int j=0; j<n; j++){
int min = j;
for(int k =j+1; k<n; k++){
if(S[k]<S[min]){
min = k;
}
}
swap(S, min, j);
sor[j] = S[min]
}
System.out.println(new String(sor));// reconvert to string
}
}
public static void swap(char[] c,int x,int y){
char temp= c[x];
c[x] = c[y];
c[y] = temp;
}
You can use String.toCharArray method to iterate over the array of characters char[] of this string, sort their decimal values and return back the string that contains the characters of the sorted array:
public static void main(String[] args) {
String str = "edcab";
String sorted = selectionSort(str.toCharArray());
System.out.println(sorted); // abcde
}
public static String selectionSort(char[] arr) {
// iterate over all subsets of the array
// (0-last, 1-last, 2-last, 3-last, ...)
for (int i = 0; i < arr.length; i++) {
// assume the min is
// the first element
char min = arr[i];
// index of the
// min element
int min_i = i;
// check the elements
// after i to find
// the smallest
for (int j = i + 1; j < arr.length; j++) {
// if this element
// is less, then it
// is the new min
if (arr[j] < min) {
min = arr[j];
min_i = j;
}
}
// if min element is not
// equal to the current
// one, then swap them
if (i != min_i) {
char temp = arr[i];
arr[i] = arr[min_i];
arr[min_i] = temp;
}
}
return String.valueOf(arr);
}
You can use String.codePoints method to iterate over int values of the characters of this string, sort them and collect another sorted string:
String str = "edcab";
String sorted = str.codePoints()
.sorted()
.mapToObj(Character::toString)
.collect(Collectors.joining());
System.out.println(sorted); // abcde
See also:
β’ How do I not take Special Characters in my Password Validation (without Regex)?
β’ Java Selection Sort
Related
I am writing a class to print the given string to lexicographical order but in the final method 'reverseOrder()' the array is automatically deleting values from it (I suppose). The method reverseOrder is deleting some characters for selected string such as "dkhc". Thanks
Debugging shows the values are correctly added to the array.
public class LexicalOrder {
static String biggerIsGreater(String w) {
String finalString = "";
char[] charArr = w.toCharArray();
int largestX = -1;
// Find the largest x such that P[x]<P[x+1].
// (If there is no such x, P is the last permutation.)
for (int i = 0; i < charArr.length - 1; i++) {
if (charArr[i] < charArr[i + 1]) {
largestX = i;
}
}
if (largestX == -1) {
finalString = "no answer";
}
int largestY = -1;
if (largestX != -1) {
for (int j = 0; j < charArr.length; j++) {
if (charArr[largestX] < charArr[j]) {
largestY = j;
}
}
charArr = swap(charArr, largestX, largestY);
charArr = reverseOrder(charArr, largestX + 1);
finalString = new String(charArr);
}
return finalString;
}
// Method to swap characters in index largestX and largestY
public static char[] swap(char[] a, int largestX, int largestY) {
char temp = a[largestY];
a[largestY] = a[largestX];
a[largestX] = temp;
return a;
}
// Method to reverse the order of the array from the index
// largestX + 1 to n (n being last element of array)
public static char[] reverseOrder(char[] a, int index) {
int step = 0;
char[] newArr = new char[a.length];
for (int j = 0; j < index; j++) {
System.out.println(j);
newArr[j] = a[j]; // adding elements to new arr till index=largestX
System.out.println(newArr[j] = a[j]);
}
for (int i = index; i < a.length; i++) {
System.out.println(i);
newArr[index] = a[a.length - step - 1]; // adding remaining values but with reversing order
System.out.println(newArr[index] = a[a.length - step - 1]);
step++;
}
for (char c : newArr)
System.out.println(c);
return newArr;
}
public static void main(String[] args) {
System.out.println(biggerIsGreater("dkhc"));
}
}
What is expected is = hcdk.
But what I get is = hk
I ran the method to check and it clearly adds those elements to the "newArr" array in method 'reverseOrder()' as shown below.
0
h
1
c
2
d
3
k
Output - hk (and two spaces)
The two characters are replaced by two spaces for some reason.
P.S : I am following the steps mentioned here link
Note: It works for some words such as "lmno,dcba,etc"
What you have missed is index++. In reverseOrder method increment index++ will give you hcdk expected output.
public static char[] reverseOrder(char[] a, int index) {
int step = 0;
char[] newArr = new char[a.length];
for (int j = 0; j < index; j++) {
System.out.println(j);
newArr[j] = a[j]; // adding elements to new arr till index=largestX
System.out.println(newArr[j] = a[j]);
}
for (int i = index; i < a.length; i++) {
System.out.println(i);
newArr[index] = a[a.length - step - 1]; // adding remaining values
// but with reversing order
System.out.println(newArr[index] = a[a.length - step - 1]);
step++;index++;
}
for (char c : newArr)
System.out.println(c);
return newArr;
}
In your case index value is not getting incremented due to which 2 and 3 item in an array are blank.
I have a task to ask user for input (user's name) and then to print a rhombus pattern out of it.
For example:
If user's name is Thomas, then the output should be like this:
T
Th
Tho
Thom
Thoma
Thomas
homas
omas
mas
as
s
This is my code so far. I am having trouble with second for loop. I can easily print out lines until "Thomas", but I don't know, how to print whitespace infront so that the end of the word will be on the same place.
import java.util.Scanner;
public class wordRhombus {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = sc.nextLine();
int enteredNamesLength = name.length();
for (int i = 0; i <= enteredNamesLength; i++) {
System.out.println(name.substring(0, (int) i));
for (int j = 1, k = 1; j <= enteredNamesLength; i++, k++) {
System.out.println(k * " " + name.substring(j, enteredNamesLength));
}
}
}
}
I think there must be one for loop to print the name like what you did, then another for space and inside the same print the substring.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = sc.nextLine();
int enteredNamesLength = name.length();
for (int i = 0; i <= enteredNamesLength; i++) {
System.out.println(name.substring(0, (int) i));
}
for(int i = 1;i <= enteredNamesLength; i++ ) {
for(int j = 0;j < i; j++) {
System.out.print(" ");
}
System.out.println(name.substring(i, enteredNamesLength));
}
}
It would be easier to do it in 2 times : substring from start to an index, and then print the spaces followed by the end of the world, ans some changes to do :
no need to cast i as int, it's already an int
first loop : start index i at 1 and not 0, no avoid empty line
second loop : end index for i at enteredNamesLength-1 and not enteredNamesLength to avoid also an empty line
for (int i = 1; i <= enteredNamesLength; i++) { // start at 1
System.out.println(name.substring(0, i)); // don't cast
}
for (int i = 1; i < enteredNamesLength; i++) { // stop at enteredNamesLength-1
for (int space = 0; space <= i; space++) {
System.out.print(" ");
}
System.out.println(name.substring(i, enteredNamesLength));
}
Here is another solution, you can extract a print method which accepts a start and stop. If the index between them, then print character at index, otherwise print whitespace.
import java.util.Scanner;
public class wordRhombus {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = sc.nextLine();
int enteredNamesLength = name.length();
for (int start = 0, stop = 0; start < enteredNamesLength && stop < enteredNamesLength; ) {
print(start, stop, name);
if (stop < enteredNamesLength - 1) {
stop++;
} else {
start++;
}
}
}
private static void print(int start, int stop, String name) {
for (int index = 0; index < name.length(); index++) {
if (index >= start && index <= stop) {
System.out.print(name.charAt(index));
} else {
System.out.print(" ");
}
}
System.out.println();
}
}
You can combine the upper increasing part and the lower decreasing part in one loop.
Try it online!
public static void main(String[] args) {
String str = "RHOMBUS";
int n = str.length();
// two parts: negative and positive
for (int i = 1 - n; i < n; i++) {
// leading whitespaces for the positive part
for (int j = 0; j < i; j++) System.out.print(" ");
// negative part: str.substring(0, n + i);
// positive part: str.substring(i, n);
String sub = str.substring(Math.max(0, i), Math.min(n + i, n));
// output the line
System.out.println(sub);
}
}
Output:
R
RH
RHO
RHOM
RHOMB
RHOMBU
RHOMBUS
HOMBUS
OMBUS
MBUS
BUS
US
S
See also: Writing a word in a rhombus / diamond shape
This code works with both regular UTF8 characters and surrogate pairs.
Try it online!
public static void main(String[] args) {
String str = "π₯π·πΎπΌπ±ππ¦";//"RHOMBUS";
int n = (int) str.codePoints().count();
// two parts: negative and positive, i.e.
// upper increasing and lower decreasing
IntStream.range(1 - n, n)
// leading whitespaces for the positive part
.peek(i -> IntStream.range(0, i)
.forEach(j -> System.out.print(" ")))
// negative part: range(0, n + i);
// positive part: range(i, n);
.mapToObj(i -> str.codePoints()
.skip(Math.max(0, i))
.limit(Math.min(n + i, n))
.mapToObj(Character::toString)
.collect(Collectors.joining()))
// output the line
.forEach(System.out::println);
}
Output:
π₯
π₯π·
π₯π·πΎ
π₯π·πΎπΌ
π₯π·πΎπΌπ±
π₯π·πΎπΌπ±π
π₯π·πΎπΌπ±ππ¦
π·πΎπΌπ±ππ¦
πΎπΌπ±ππ¦
πΌπ±ππ¦
π±ππ¦
ππ¦
π¦
I am new to Java Programming (or programming infact).
I have an array which contains either 4 or 6 only. Given a number, either 4 or 6, find the highest sequential occurrence of the given number.
I need highest sequential occurrence count
Example: arr[{4,4,6,6,4,4,4,4,4,6}]
If the above array is given, and next input number is 4, the output should be 5. Because the number 4 has occurred sequentially 5 times.
public static void main(String[] args) throws IOException {
String arrayTK = br.readLine(); // Input is 4466444446
int[] inpArray = new int[10];
for (int i = 0; i < 10; i++) {
inpArray[i] = arrayTK.charAt(i) - '0';
}
int maxSequenceTimes = 0;
for (int j = 0; j < 10; j++) {
// Logic
}}
Any help would be greatly appreciated.
Edit
We will separate and count all sequences and then search in each sequence to know which sequence contain the biggest length.
int[] arr = {4,4,6,6,4,4,4,4,4,6};
boolean newSeq = false;
int diffrentSeq = 0;
int currentNumber;
//Get sequence numbers
for (int i = 0; i < arr.length; i++) {
currentNumber = arr[i];
if (i >= 1 && currentNumber != arr[i - 1])
newSeq = true;
else if (i == 0)
newSeq = true;
//It's new sequence!!
if (newSeq) {
diffrentSeq++;
newSeq = false;
}
}
System.out.println(diffrentSeq);
int[] maxSequencSize = new int[diffrentSeq];
int lastIndex = 0;
for (int i = 0; i < maxSequencSize.length; i++) {
int currentNum = arr[lastIndex];
for (int j = lastIndex; j < arr.length; j++) {
if (arr[j] == currentNum) {
maxSequencSize[i]++;
lastIndex = j + 1;
} else break;
}
}
System.out.println(max(maxSequencSize));
You need to get max value which act the max sequence length:
private static int max(int[] array){
int maxVal = 0;
for (int anArray : array) {
if (anArray > maxVal)
maxVal = anArray;
}
return maxVal;
}
String arrayTK = br.readLine(); // Input is 4466444446
Because your first input is a string, you don't need to convert it to an int array and if you are using you can use:
String arrayTK = "4466444446";
int result = Arrays.asList(arrayTK.replaceAll("(\\d)((?!\\1|$))", "$1;$2").split(";"))
.stream().max(Comparator.comparingInt(String::length)).get().length();
System.out.println(result);
Explanation :
arrayTK.replaceAll("(\\d)((?!\\1|$))", "$1;$2") put a separator between each two different numbers the result should be 44;66;44444;6
.split(";") split with this separator (i used ; in this case) the result is ["44", "66", "44444", "6"]
stream().max(Comparator.comparingInt(String::length)).get() get the max input
.length() to return the length of the result
Ideone demo
Edit
How I modify the same, to get count to any specific number. I mean, max sequential occurrence of number 4
In this case you can just add a filter .filter(t -> t.matches(number + "+")) which mean get only the numbers which match 4+ where 4 can be any number :
...
int number = 6;
int result = Arrays.asList(arrayTK.replaceAll("(\\d)((?!\\1|$))", "$1;$2").split(";"))
.stream()
.filter(t -> t.matches(number + "+"))
.max(Comparator.comparingInt(String::length)).get().length();
You need something like this:
import java.util.Scanner;
public class A {
public static void main(String[] args) {
Scanner br =new Scanner(System.in);
String str = br.next();
int arr[]=new int[str.length()];
for(int i=0;i<str.length();i++)
{
arr[i]=str.charAt(i)-'0';
//System.out.println(arr[i]);
}
int j=0;
int count=1,max=0;
for(int i=0;i<str.length();i++)
{
if(i==0){
j=arr[i];
}
else
{
if(arr[i]==j)
{
count++;
//System.out.println(" "+count);
}
else
{
if(max<count){
max=count;
}
count=1;
j=arr[i];
}
}
}
if(max<count){
max=count;
}
System.out.println(max);
}
}
That should do the work. Every time you find the matching value you start counting and when the streak is over you compare the length with the maximum length you have found so far.
public int logic(int[] inpArray, int num) {
int count = 0, max = 0
for(int i = 0; i < 10; ++i){
if(inpArray[i] == num) {
count++
else{
if(count > max)
max = count;
count = 0;
}
}
if (count > max)
max = count;
return max;
}
For this java program I am taking in a string then printing/saving the string of characters in order of their frequency.
import java.util.*;
public class freqChar
{
public static void main(String args[])
{
Scanner scan = new Scanner(System.in);
String s = scan.nextLine();
int myArray[] = new int[256];
int len = s.length();
String array1 [] = new String [len];
String strArray [] = new String [len];
for(int i = 0; i < s.length(); i++)
{
myArray[(int)s.charAt(i)]++;
}
for(int i = s.length(); i > 0; i--)
{
for(int j = 0; j < myArray.length; j++)
{
if(myArray[j] == i) // Here I am trying to fill a string array with the characters from the original string after I have casted them back from ints.
{
int g = 0;
char x = ((char)(j));
array1[g] = x;
g++;
}
}
}
for (int i = 0; i < len; i++)
{
System.out.println(array1[i] + " ");
}
}
}
When I compile it gives me the error:
cannot convert char to a string.
Short answer: a char is not a String so putting a char into an array of Strings won't work.
But its very easy to fix the problem, just replace char x =((char)(j)); with char x = Character.toString((char) j);
Sample Input #1
make(4)
Sample Output #1
{"0","1","2","3"}
public class StringArrayOfNumbers {
static int testcase1 = 10;
public static void main(String args[]){
StringArrayOfNumbers testInstance = new StringArrayOfNumbers();
String[] result = testInstance.make(testcase1);
System.out.println(result);
}
public String[] make(int num){
int n=0;
String n1="n";
String[] arr=new String[num];
for(int i=0;i<num;i++){
arr[i]=n1;
n=n+1;
}
return arr;
}
}
when i am trying to run code it prints only 4 times n , how to initialise this n? also without using any string library functions?
Testcase Pass/Fail Parameters Actual Output Expected Output
1 Fail '5' {'n','n','n','n','n'}{'0','1','2','3','4'}
n1 is a String which has the value "n" in it.
whereas n is a variable whose value varies from 0 to num - 1.
SO you might want to assign n instead of n1.
int n=0;
String[] arr=new String[num];
for(int i = 0; i < num; i++){
arr[i]= n;
n = n + 1;
}
If you look closely, n and i have the same value, you don't need n too.
String[] arr=new String[num];
for(int i = 0; i < num; i++){
arr[i] = i;
}
i'm not sure of what you are asking for, but the result should be this :
public String[] make(int num) {
int n = 0;
//String n1 = "n";
String[] arr = new String[num];
for (int i = 0; i < num; i++) {
arr[i] = String.valueOf(n);
n = n + 1;
}
return arr;
}