I have to print the count of the words in a string which are repeated exactly N times?
example:
one two three four three two five
1
output:3
since one,four and five appears only once.
My code shows me the output as 1.
what is wrong with my code and logic?thank you.
import java.util.*;
public class Hello {
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
String s=scan.nextLine(),b;
int n=scan.nextInt();
int c=0,f=0,i;
String[] a=s.split(" ");
for(i=0;i<a.length;i++)
{
b=a[i];
for(int j=i+1;j<a.length;j++)
{
if(b.equalsIgnoreCase(a[j]))
{
c++;
}
}
if(n==c)
{
f++;
}
else
{
c=0;
}
}
System.out.print(f);
}
}
I see three reasons that makes your result incorrect.
First one is c
If a word is here once only, then the if statement if(b.equalsIgnoreCase(a[j])) will never be true. Which means that c will be always equal to 0.
So you you need to use 1 as default value for c or you should check the value of c using the following statement if (n == c + 1)
The second point is that you should reset the value of c even if it is equal to n.
Then with this double for loop:
for (i = 0; i < a.length; i++) {
b = a[i];
for (int j = i + 1; j < a.length; j++) {
When you searching for a value that is there once only, the last occurence of every words will be counted as well.
There is lot of ways to solve that. one of them is to use a Set<String> and only count for the words that has not been used before.
So at the end you will have something similar to that:
int c=1,f=0,i;
String[] a=s.split(" ");
Set<String> words = new HashSet<>();
for (i = 0; i < a.length; i++) {
b = a[i];
if (words.add(b)) {
for (int j = i + 1; j < a.length; j++) {
if (b.equalsIgnoreCase(a[j])) {
c++;
}
}
if (n == c) {
f++;
}
c = 1;
}
}
I think It's because you don't initialize C when n==c . Therefor it increases to 1 after one and one are matched. And it's not working well . It should be 0 for every loop
Also why j starts from i+1? After each loop it will lose comparison one by one Since a[j] is getting smaller. It should always containt list of full input numbers
Related
I'm trying to print out a string by alternating its letter cases. I want YourString to come out as YoUrStRiNg. I've tried three things but I can't get the loop to work the way I need it to. Here's what I have so far:
//one attempt
String s = "yourString";
String x = "";
for (int i = 0; i < s.length(); i += 2) {
for (int j = 1; j < s.length(); j += 2) {
x += Character.toUpperCase(s.charAt(i));
x += Character.toLowerCase(s.charAt(j));
}
}
System.out.println(x);
//the desired result but not the ideal solution
String[] sArray = {"Your", "String"};
String f = "";
for (String n : sArray) {
f += n;
}
char[] c = f.toUpperCase().toCharArray();
char[] d = f.toLowerCase().toCharArray();
System.out.print(c[0]);
System.out.print(d[1]);
System.out.print(c[2]);
System.out.print(d[3]);
System.out.print(c[4]);
System.out.print(d[5]);
System.out.print(c[6]);
System.out.print(d[7]);
System.out.print(c[8]);
System.out.print(d[9]);
System.out.println();
//third attempt with loop but the first loop keeps starting from zero
String t = "";
for (int i = 0; i < c.length; i += 2) {
for (int j = 1; j < d.length; j += 2) {
t += Character.toUpperCase(c[i]);
t += Character.toLowerCase(d[j]);
}
System.out.print(t);
}
What am I doing wrong?
Actually, there's no need to iterate more than once through the elements of the String. As you need to change the case of the character alternatively, you can just count the position of your iteration, by using the operator %. So, for example, given c as the current String character, the operation would be like this:
System.out.print(i % 2 == 0, (char)Character.toUpperCase(c) : (char)Character.toLowerCase(c));
However, you can actually take advantages from Java Stream and lambda expression, so to realize a very elegant solution for that.
I am going to show you my proposal solution. The only issue is that you cannot actually have a proper cycle variable, as the variable you access inside the lamba expression must be final or effective final, so I used a sort of trick for it.
That is just to give you an idea, you can actually personalize, make it reusable, and improve it as you wish:
public class MyStringTest {
public static void main(String args[]) {
String s = "yourString";
initializeCycleVariable();
s.chars().forEach(c ->
{System.out.print( MyStringTest.getAndIncrement() %2 == 0 ?
(char)Character.toUpperCase(c) :
(char)Character.toLowerCase(c));
});
}
private static int i = 0;
public initializeCycleVariable() { i = 0; }
public static int getAndIncrement() { return i++; }
}
And here is the output:
YoUrStRiNg
You should iterate over the string char by char. You could do upper case for the even indexes, and lower case for the odd ones. Sorry for not providing more detail, but it is clear that this is an assignment.
Try this one out,
String s = "yourString", x = "";
for(int i = 0; i < str.length(); i++){
if(i % 2 == 0)
x += Character.toUpperCase(s.charAt(i));
else
x += Character.toLowerCase(s.charAt(i));
}
System.out.println(x);
I start learning programming about 4 days ago by myself and iam a lil bit stuck with 2d arrays. I try to challenging myself with tasks, like get from 2d array column with most zeros or atleast just count zeros, so far i get this far
public class b {
public static void main(String[] args) {
int a[][] = new int [5][5];
int i,j;
int s = 0;
for(i= 0;i<a.length; i++)
for(j = 0; j<a[i].length; j++){
a[i][j] = (int)(Math.random()*10);
}
for(i=0;i<a.length;i++){
for(j=0;j<a[i].length;j++) {
System.out.print(a[i][j] + "\t");
}
System.out.println();
}
for(j=0;j<a[0].length;j++) {
for(i=0;i<a.length;i++) {
if(a[i][j] >-1 || a[i][j]<1) {
s++;
System.out.println(s +"\t");
s = 0;
}
}
}
}
}
Can somebody explain me why result is always 1 and why it counts columns and rows in one row?
Suppose the condition enters into if(a[i][j] >-1 || a[i][j]<1) then you increase s by 1 then print it which gives 1 then you reassign it to s=0 so it gives same 1 each time.So remove the s=0 and place the printing line after end of loop
public class b {
public static void main(String[] args) {
int a[][] = new int [5][5];
int i,j;
int s = 0;
for(i= 0;i<a.length; i++)
for(j = 0; j<a[i].length; j++){
a[i][j] = (int)(Math.random()*10);
}
for(i=0;i<a.length;i++){
for(j=0;j<a[i].length;j++)
System.out.print(a[i][j] + "\t");
System.out.println();
}
for(j=0;j<a[0].length;j++){
for(i=0;i<a.length;i++)
if(a[i][j] >-1 && a[i][j]<1){
s++;
}
System.out.println("Zero in column no. "+j+" is "+s +"\t");
s=0;
}
}
}
Demo
Result will be 1 because you're re-assigning 0 to s everytime. But the issue is not only that.
Firstly your condition is using wrong indices. Instead of a[i][j] you should use a[j][i] as you're traversing column-wise. Secondly:
if(a[j][i] >-1 || a[j][i]<1){
can be simply written as:
if(a[j][i] == 0) {
So the structure is the outer for loop will iterate over each column number. And for each column number, inner for loop will find count of 0. You've to maintain a max variable outside both the loops, to track the current max. Also, you've to use another variable inside the outer for loop to store the count for current column.
Everytime the inner for loop ends, check if current column count is greater than max. If yes, reset max.
int max = 0;
for(j=0;j<a[0].length;j++){
int currentColumnCount = 0;
for(i=0;i<a.length;i++) {
if(a[j][i] == 0) {
currentColumnCount++;
}
}
if (currentColumnCount > max) {
max = currentColumnCount;
}
}
I have numbers like: 1,7,1,5 and I want to sort them without gaps between them (i.e.) 1,7,1,5 gets sorted to 1,1,2,3. (5 turns into 2; 7 turns into 3).
My code looks like this (works fine), but in some cases returns null pointer ex, or something like that :/
public void shake(Car[] c){
for(int i = 1; i < MaxPriority; i++)
if(!isCarWithPriority(i, c))
for(int j = i; j < 10; j++)
if(isCarWithPriority(j, c))
for(int k = 0; k < getCarsWithPriority(j, c).length; k++)
getCarsWithPriority(j, c)[k].setPriority(i);
}
Can you help me?
You can try iterating through the numbers after sorting them. subtract 1st from 2nd if result is 0 then dont do anything else replace 2nd by first + 1 then compare 3rd one in the same way with second.. keep on till last number. you will get the desired output. This can be achieved by a single loop in java.
This will do the trick
public static void main(String[] a) {
Integer [] arr = {1,7,1,5};
Arrays.sort(arr);
for (Integer integer : arr) {
System.out.println(integer);
}
for(int i=0; i< arr.length-1 ;i++){
if(arr[i+1]-arr[i] ==0){
continue;
}else{
arr[i+1] =arr[i]+1;
}
}
System.out.println("--------------------");
for (Integer integer : arr) {
System.out.println(integer);
}
}
public class trothBrthdays {
public static void main ( String args [] ) {
Random day = new Random();
int days[] = new int[366];
int smallest = 0;
int largest = 885000;
for (int i = 1; i <= 885000; i++)
{
int persons = day.nextInt(365) + 1;
days[persons] += 1;
}
for (int a = 1; a <= 365; a++)
{
System.out.printf ( " \nDay %d: %d ", a, days[a]);
}
Here program finds day with most birthdays on it
for (int b = 0; b < days.length;)
{
if(days[b] > smallest)
{
largest = days[b];
System.out.printf ( "\nLargest: %d ", days[b]);
}
}
Here program finds day with least birthdays on it
for (int c = 0; c > days.length;)
{
if (days[c] < largest)
{
smallest = days[c];
System.out.printf ( "\nSmallest: %d ", days[c]);
}
}
}
}
The problem is when the program gets to finding the largest number it infinitely loops the largest number and I can't figure out why. I'm still a Beginner program and would love constructive criticism on how to format and type this program.
The reason this is happening is because of your for loops:
for (int b = 0; b < days.length;)
The construction of a for loop is in three parts. Part one is the iterator's declaration:
(int b = 0;
part two is the break condition. That is, what condition must be met, else the loop breaks.
b < days.length;
finally, the third part determines what should change between each iteration. But your for loop is missing that part. It should be...
b++)
Edit:
The second problem that you have is that this will not work with the code as it is written. But I suppose that will be an exercise for you to figure out why.
There are many symbol games working in this way so this should sound familiar to you.
Facts:
I have two arrays with same length of 4.
(A[4] and B[4])
I fill them with random integers from 1 to 6.
I can NOT sort them in any way (they must stay the same).
Problems:
I need to compare them and after that I need to have 3 values. FIRST one needs to count how many elements are the same and in the same place. I do it like this and it is working:
int first = 0;
int k = 0;
for (int j=1; j<=4; j++)
{
k++;
if (A[k] == B[j])
{
first++;
}
}
SECOND one needs to count how many elements are the same BUT not at the same place. THIRD one needs to count how many elements are not the same at all.
I need a solution to count either SECOND or THIRD number, because after that I can just subtract like 4-(first+second) or 4-(first+second).
Here's the logic you should use: loop over the first array; for each element, check if the corresponding element of the second array is the same - if yes, increment your first counter. If they are not the same, then check whether the second array contains the corresponding element of the first array. If it does, then it's definitely not in the same position (you just checked same positions) - increment your second count. Otherwise, increment your third count. The code can be as following:
int[] A = {...};
int[] B = {...};
List<Integer> lstB = new ArrayList<Integer>(B.length);
for (int index = 0; index < B.length; index++) {
lstB.add(B[index]);
}
int first = 0, second = 0, third = 0;
for(int i=0; i<4; i++) {
if(A[i] == B[i]) {
first++;
}
else if(lstB.contains(A[i]) {
second++;
}
else {
third++;
}
}
SOLUTION
Eventually I made the right algorithm. In general, the solution is to keep track of what fields you used when counting FIRST value. And here is the code:
int first = 0;
int second = 0;
int third = 0;
boolean[] codeUsed = new boolean[4];
boolean[] guessUsed = new boolean[4];
//same value and same place
for (int i = 0; i < 4; i++)
{
if (A[i] == B[i])
{
first++;
codeUsed[i] = guessUsed[i] = true;
}
}
//same value but not right place
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
if (!codeUsed[i] && !guessUsed[j] && A[i] == B[j])
{
second++;
codeUsed[i] = guessUsed[j] = true;
break;
}
}
}
//not the same value
third = 4 - first - second;