BIT is not showing the correct value - java

I am having a String , i am creating a BIT of String based on the frequency of the element present
String:
abcdbcaab
Code:
class Test{
static int[][] dp;
public static void update(int i , int val ,int[] dpp){
while(i<=100000){
dpp[i]+=val;
i+= (i&-i);
}
}
public static int value(int i ,int[] dp){
int ans =0;
while(i>0){
ans+=dp[i];
i-= (i&i);
}
return ans;
}
public static void main(String args[] ) throws IOException {
Scanner in = new Scanner(new InputStreamReader(System.in));
dp = new int[27][1000001];
String s = in.next();
for(int i=0;i<s.length();i++){
update(i+1,1,dp[s.charAt(i)-'a']);
}
System.out.println(dp[0][7]); // Should show 2 as the frequency of 'a' at 7 position is 2
}
}
Where i am doing wrong . i could not get it but dp[0][8] is showing me 3Please Help i could not figure it out where i have commit mistake

Negativity should be avoided in life !!! but i think a little more negativity can improve you'r code:
value function you are doing wrong decrement of value of i
public static int value(int i ,int[] dp){
int ans =0;
while(i>0){
ans+=dp[i];
i-= (i&i); // Should be (i&-i);
}
return ans;
}

Related

Why this method doesn't return the value

public class Main {
public static void main(String []args){
Scanner reader = new Scanner(System.in);
System.out.print("Enter word: ");
String text = reader.nextLine();
System.out.println(calculateCharacters(tex));
reader.close();
}
public static int calculateCharacters(String text, int tex){
tex = text.length();
return tex;
}
}
So I receive a string from String text, then I send it to the method to calculate it's length and return a number which should be intercepted by System.out.println(calculateCharacters(tex)); and the probram should show me the number of letters in the string that was entered, the problem is: nothing reaches System.out.println(calculateCharacters(tex)); why ? where is this return tex; returning it then ?
Well I'm not entirely sure why you've got an int texvariable, but removing it lets this work perfectly. Try rewriting your method:
public static int calculateCharacters(String text) {
int tex = text.length();
return tex;
}
or if you're ready to be snazzy:
public static int calculateCharacters(String text) {
return text.length();
}
Java is pass-by-value (Is Java "pass-by-reference" or "pass-by-value"?), so keeping an extra int in there that you only use to store things locally won't actually change your value of tex.
Also, you instantiate the String text, but then pass tex to calculateCharacters(). Since you haven't created a texvariable before this, your compiler doesn't know what to pass to calculateCharacters(). Try changing that to:
System.out.println(calculateCharacters(text));
instead.
public class Main {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.print("Enter word: ");
String text = reader.nextLine();
System.out.println(calculateCharacters(text));
reader.close();
}
public static int calculateCharacters(String text) {
int tex = text.length();
return tex;
}
}
It works
For counting the string use below code...
public class Main {
static int stringCount;
public static void main(String []args){
Scanner reader = new Scanner(System.in);
System.out.print("Enter word: ");
String text = reader.nextLine();
calculateCharacters(text);
System.out.println(stringCount);
reader.close();
}
public static int calculateCharacters(String text){
stringCount = text.length();
return stringCount;
}
}

Find all available combinations

How can I find all available combinations of some digits. For example I have 0, 1, 2. In the output I should receive something like this:
0
01
02
012
021
1
10
12
102
120
2
20
21
201
210
The problem is in algorithm. I think here should be recursion, but how to to write it?
I have one done the same with strings. However, I just swapped random digits until I get all combinations(which is the factorial of the length of the string). I then print out the non-recurring ones.
Here is how I did it, just change the String you input to the allpos() method and it will work for any number.
import java.util.Random;
import java.util.Scanner;
public class shift {
public static void main(String[] args) {
//Change "012" to anything, even a String.
allpos("012");
}
public static int unbin(String s){
int ans=0;
for(int x=0;x<s.length();x++){
char c=s.charAt(x);
if(c=='1'){
ans+=Math.pow(2, s.length()-1-x);
}
}
return ans;
}
public static String bin(int n){
int[] ans=new int[32];
int a=n;
for(int x=31;x>=0;x--){
if(Math.pow(2, x)<=a){
a-=Math.pow(2, x);
ans[x]=1;
}
}
String s="";boolean zero=false;
for(int x=ans.length-1;x>=0;x--){
if(ans[x]==1){
s+="1";
zero=true;
continue;
}else if(zero){
s+="0";
}
}
return s;
}
public static boolean ispresent(String[] words,String s){
for(int x=0;x<words.length;x++){
if(words[x]==null){return false;}
if(words[x].equals(s)){return true;}
}
return false;
}
public static void allpos(String s){
int fac=1;
for(int x=1;x<=s.length();x++){
fac*=x;
}
int len=s.length();
String[] values=new String[fac];
values[0]=s;
System.out.println(s+" (1)");
int id1=0,id2=0;
Random r=new Random();
for(int x=1;x<fac;){
s=inchange(s,r.nextInt(len),r.nextInt(len));
if(ispresent(values,s)==false){
values[x]=s;
x++;
System.out.println(s+" ("+x+")");
}
}
}
public static String inchange(String s,int id1,int id2){
char[] chars=new char[s.length()];
for(int x=0;x<s.length();x++){
chars[x]=s.charAt(x);
}
char temp=chars[id1];
chars[id1]=chars[id2];
chars[id2]=temp;
String ans="";
for(int x=0;x<s.length();x++){
ans+=chars[x];
}
return ans;
}
}
I know that it is inefficient but it gets the job done for smaller numbers. I hope this helped.

Java Error; array required, but java.lang.String found

I am currently trying to complete this program and I'm having trouble with this error. I've done many things trying to fix it so I can compile it but it won't work. It seems that the "String alphabet" is getting the error. Can someone help me solve this please?
import java.util.Scanner;
public class Period
{
private static String phrase;
private static String alphabet;
public static void main(String [] args)
{
Scanner keyboard = new Scanner(System.in);
String userInput;
int[] letter = new int [27];
int number = keyboard.nextInt();
System.out.println("Enter a sentence with a period at the end.");
userInput = keyboard.nextLine();
userInput.toLowerCase();
}
public void Sorter(String newPhrase)
{
phrase=newPhrase.substring(0,newPhrase.indexOf("."));
}
private int charToInt(char currentLetter)
{
int converted=(int)currentLetter-(int)'a';
return converted;
}
private void writeToArray()
{
char next;
for (int i=0;i<phrase.length();i++)
{
next=(char)phrase.charAt(i);
sort(next);
}
}
private String cutPhrase()
{
phrase=phrase.substring(0,phrase.indexOf("."));
return phrase;
}
private void sort(char toArray)
{
int placement=charToInt(toArray);
if (placement<0)
{
alphabet[26]=1;
}
else
{
// here is one spot that mainly the error pops up?
alphabet[placement]=alphabet[placement]+1;
}
}
public void entryPoint()
{
writeToArray();
displaySorted();
}
private void displaySorted()
{
for (int q=0; q<26;q++)
{
System.out.println("Number of " + (char)('a'+q) +"'s: "+alphabet[q]);
}
}
}
Your sort method is treating alphabet (the String) as an array. String is not a char[] but you can call String.toCharArray() like
private void sort(char toArray)
{
char[] alpha = alphabet.toLowerCase().toCharArray();
int placement=charToInt(toArray);
if (placement<0)
{
alpha[26]=1;
}
else
{
alpha[placement]=alpha[placement]+1;
}
alphabet = new String(alpha, "UTF-8");
}
But modifying a String is not possible, because they are immutable. For the same reason your raw call alphabet.toLowerCase() doesn't modify the alphabet in your other method.
The variable alphabet is defined as a String data type, but you need to define it as an array if you want to reference it using the bracket notation [] you have in your code. The error message is pretty clear in this case.
String[] example = new String[3];
example[0] = "Hello";
example[1] = "ETC...";

Beginner; Methods and Strings

Here is the code:
import java.util.Scanner;
public class sending {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
String text = giveMe(first);
System.out.println(text);
int x = scanner.nextInt();
x = number(x);
skrivUt(x);
}
//method for printing on screen
public static String giveMe(String first, String second){
first = ("Give me a number and I run down and add five to it");
second = ("Lol");
return first;
}
//method for doing math
public static int number(int x){
x = x + 5;
return x;
}
//method for printing out
public static void skrivUt(int x){
System.out.println(x);
}
}
As you can see I am new to this and I am having a problem with the main method and the method giveMe.
I want to have giveMe work as a collection of strings that I can call when I need them.
But when I try the above example I eclipse tells me that "first cannot be resolved to a variable" on line six String text = giveMe(first);
What am I doing wrong?
You are trying to use an enum and you never declared one... declare your enum like this outside your Main.
enum s {FIRST, SECOND} //add this
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
String text = giveMe(s.FIRST); //add the s. so it knows to use your enum
System.out.println(text);
int x = scanner.nextInt();
x = number(x);
skrivUt(x);
}
Then you want to modify your method to take an enum instead like this
public static String giveMe(s string) {
switch (string) {
case FIRST:
return "Give me a number and I run down and add five to it";
case SECOND:
return "Lol";
}
return "invalid string";
}
Beginner, your problem is resolved.
Firstly declaration is important in java. "First" variable is not intailzed in your block of code. Ideally it is not necessary for your scenario.
Try this
import java.util.Scanner;
public class Test2 {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
String text = giveMe();
System.out.println(text);
int x = scanner.nextInt();
x = number(x);
skrivUt(x);
}
//method for printing on screen
public static String giveMe(){
String first = ("Give me a number and I run down and add five to it");
return first;
}
//method for doing math
public static int number(int x){
x = x + 5;
return x;
}
//method for printing out
public static void skrivUt(int x){
System.out.println(x);
}
}

Parsing string to accept other inputs

General info.
A mixed number is one of 3 forms:
1).An integer such as 12.
2).Fraction = int/int such as ¾
3.Mix of forms 1 and 2: 1 ¾ In this case one of more blanks act as a separator between integer and the fraction.
Question: 1.Treat the 1st and the 2nd forms as the special input and enhance the method parse to include these two cases.
* **I have already done the 3rd form of a mixed number and i am confused on how to parse the string to include an integer and a fraction alongside the mixed number in Mix.java . Output should be in gcd form. The following three programs run together.Some help me please thank you.
Here is my Mixed number code:
import java.util.Scanner;
class Mix extends Fraction{
public Mix(int n, int m) {super(n,m); }
public String displayMix() {
String str="";
if (first < second) str=first+"/"+second;
else str= first/second +" "+ first%second+"/"+second;
return str;
}//display
public Mix(String str) {
int[] iA= parse (str);
int top=iA[0]*iA[2]+iA[1];
int bot= iA[2];
int gcd = gcd(top,bot);
first=top/gcd;
second =bot/gcd;
}//Mix
public static Mix add (Mix s, Mix s2){
int gtop=s.first * s2.second
+ s2.first * s.second;
int gbottom= s.second * s2.second;
return (new Mix(gtop,gbottom));
}//add
public static String get (){
Scanner scan = new Scanner (System.in);
String userInput = scan.nextLine();
userInput =userInput.trim();
return (userInput);
} //get
public static int[] parse (String userInput){
int pos = userInput.indexOf(" ");
String sNum=userInput.substring(0,pos);
int iNum = Integer.parseInt(sNum);//first integer
String sNum2=userInput.substring(pos+1);
pos= sNum2.indexOf("/");
String sTop=sNum2.substring(0,pos);
int iTop = Integer.parseInt(sTop);//second integer
String sBot=sNum2.substring(pos+1);
int iBot = Integer.parseInt(sBot);//third integer
int[] sA = {iNum,iTop,iBot};
return (sA);
} //parse
public static void main(String[] args) {
System.out.print("Please enter mixed-format number :");
String userInput = Mix.get();
System.out.println("Input is: "+userInput);
Mix s = new Mix(userInput);
s.displayMix();
System.out.print("Please enter mixed-format number :");
userInput = Mix.get();
System.out.println("Input is: "+userInput);
Mix s2 = new Mix(userInput);
s2.displayMix();
Mix h= Mix.add(s,s2);
System.out.print(h.displayMix());
}//main
}//class
Here is the Fraction code:
public class Fraction extends Pair {
//attributes: NONE
public Fraction() { first=0; second=1;}
public Fraction(int n, int m) {
super(n,m);
int g=gcd(n,m);
first = first/g;
second=second/g;
}//Fraction
public String display2() {
String str = first+"/"+second;
return str;
}//display
public static Fraction add (Fraction f1, Fraction f2){
int gtop=f1.first * f2.second
+ f2.first * f1.second;
int gbottom= f1.second * f2.second;
return (new Fraction(gtop,gbottom));
}
public static int gcd (int n, int m){
while ( n!=m) {
if (n>m) n=n-m;
else m=m-n;
}//while
return (n);
}//gcd
//test the class
public static void main(String[] args) {
//pseudo-code is here
Fraction f= new Fraction();
f.display();
System.out.print(f.display2());
}//main
} //class
Finally here is pair:
import java.util.Arrays;
public class Pair {
int first;
int second;
public Pair (){first=0; second=0;}
public Pair(int n, int m) {
first=n;
second=m;
}//Pair
public int[] display() {
//pseudo_code is here
int[] c = {first, second};
return c;
}//display
public static void main(String[] args) {
//pseudo-code is here
Pair f= new Pair();
f.display();
System.out.println(Arrays.toString(f.display()));
}//main
} //class
You would have to make your own methods to do that using methods like str.split("/"), I don't know of any other way.

Categories