I would like to ask you a question, I want to count how many times a specified number is in a given numer (long) from the user and print it as an int.
Could you please help me with this code?
Apologize for my english.
Example:
< number specified = 4; number given = 34434544; result = 5. >
Check whether the least-significant digit is equal to the digit you are searching for; then divide by ten and check again; keep going until you reach zero.
int cnt = 0;
while (value != 0) {
if (value % 10 == digit) ++cnt;
value /= 10;
}
Where you are trying to count the occurrences of digit in the big number value.
If you're using Java 8:
long count = String.valueOf(givenNumber).chars()
.filter(c -> c == (specifiedNumber + '0'))
.count();
Make a Scanner to get input from System.in. Then, iterate through the String returned by turning it into a char[]. Then analyse each char and count original characters. Probably use a Map<Character, Integer> for this. For each element in the Map, iterate by one if it is in the Map. Query the Map for your desired character and print the result when finished.
public static void main(String[] args) {
CharacterFinder cf = new CharacterFinder();
Scanner scan = new Scanner(System.in);
String input = scan.nextLine();
Map<Character, Integer> resultsMap = cf.countChar(input);
System.out.println(resultsMap.get('g'));
}
// Note that 'null' means that it does not appear and if it is null, you ought print 0 instead.
// Also note that this method is case sensitive.
private Map<Character, Integer> countChar(String input) {
Map<Character, Integer> resultsMap = new HashMap<Character, Integer>();
for (int i = 0; i < input.length(); i++) {
Character element = input.charAt(i);
if (resultsMap.containsKey(element)) {
Integer cCount = resultsMap.get(element);
resultsMap.put(element, cCount + 1);
} else {
resultsMap.put(element, 1);
}
}
return resultsMap;
}
Well, unless you already know the char you want. In that case, analyse for that exact char.
public static void main(String[] args) {
CharacterFinder cf = new CharacterFinder();
Scanner scan = new Scanner(System.in);
String input = scan.nextLine();
// Call counting method and print
System.out.println(cf.countChar(input, '5'));
}
// Counting method
private int countChar(String input, char c) {
int x = 0;
for (int i = 0; i < input.length(); i++) {
if (input.charAt(i) == c) {
x++;
}
}
return x;
}
Related
I am trying to print all the unique characters from a string but I am not getting proper output. Also, I want to check if someone enters integer in string, I want to print Invalid String. How can I achieve this?
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
char[] ch = new char[20];
System.out.println("Enter the sentence:");
String sent = sc.nextLine().replaceAll(" ", "");
int count = 0;
for (int i = 0; i < sent.length(); i++) {
int j = (sent.length() - 1);
count = 0;
while (j > i) {
if (sent.charAt(j) == sent.charAt(i)) {
sent = deleteCharAt(sent, i);
sent = deleteCharAt(sent, j - 1);
break;
}
j--;
}
}
for (int i = 0; i < sent.length(); i++) {
System.out.println(sent.charAt(i));
}
}
private static String deleteCharAt(String strValue, int index) {
return strValue.substring(0, index) + strValue.substring(index + 1);
}
Enter the sentence:
java is good object oriented programming language
a
v
i
s
o
d
b
c
r
e
e
d
p
g
m
m
n
l
u
You are probably going to want to use a Set. These data structures are like Lists, except:
They do not have an ordering (meaning you cant call set.get(3))
They do not allow duplicates
You can think of them as a Map without any values.
If you have a String and you want to get all the unique chars from it. The steps are as follows:
String string = "hello"; // 4 unique characters
Set<Character> uniqueChars = new HashSet<>(); // create an empty set to put the unique chars into
// split into char[]
char[] chars = string.toCharArray();
Arrays.stream(chars).forEach(c -> {
// the following code will be run once for every char in the array
uniqueChars.add(c);
// adding the same char twice does not insert it twice
});
This can be written more concisely as:
String string = "hello";
Set<Character> uniqueChars = new HashSet<>();
Arrays.stream(string.toCharArray()).forEach(uniqueChars::add); // using a Java 8 method reference
If you want to reject any char that is a numerical digit, you can use the following line:
boolean containsDigit = Arrays.stream(string.toCharArray())
.filter(Character::isDigit) // filter out all the non digit characters
.findAny() // check if there are any remaining
.isPresent();
It would be more efficient and easier to read code to use a HashSet:
HashSet<Character> h = new HashSet<Character>();
for (int i = 0; i <= (sent.length() - 1); i++)
h.add(sent.charAt(i));
Iterator<Character> i = h.iterator();
while (i.hasNext())
System.out.println(i.next());
To avoid duplicate you can use a Set: is a collection that doesn't allow duplicates. You have to use a specific implementation of that interface, such as HashSet. You can do something like this:
public class UniqueChar {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the sentence:");
String withoutSpaces = sc.nextLine();
withoutSpaces = "asc34csf"; // mock example
Set<Character> goodChars = new HashSet<>();
String sent = withoutSpaces.replaceAll(" ", "");
int count = 0;
for (int i = 0; i < sent.length(); i++) {
char currChar = sent.charAt(i);
// do not add a character if is a digit
if(Character.isDigit(currChar))
System.out.println("Digit!");
else
goodChars.add(currChar); // add a character only if not present
}
String output = "";
for (Character character : goodChars) {
output += character; // concat in a single output string
}
System.out.println(output);
}
So you simply jump characters that are digits, if it's a character it'll be added to the collection (and the Set manages internally the fact that if it's a duplicate, it will not be added), then concat the elements of the Set in a single String.
You can find more information about HashSet in the Java documentation.
You can write your code something like this:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] alpha = new int[26];
System.out.println("Enter the sentence:");
String sent = sc.nextLine().replaceAll(" ", "");
for (int i = 0; i < sent.length(); i++) {
int temp = sent[i] - 'a';
if (temp >= 0 && temp <= 25) {
alpha[temp] = 1;
} else {
System.out.println("Invalid String");
return;
}
}
for (int i = 0; i < 26; i++) {
if (alpha[i] == 1)
System.out.println((char) (i + 'a'));
}
}
This uses an array of length 26 as the workaround if you don't want to use any SET like data structure.
This code can bring you problem if your sentence have capital letters as well. You can avoid that problem by using toLowercase like function just before the loop.
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("type the sentence you want to find the letters of");
String sentence = s.nextLine();
getLetters(sentence);
}
public static void getLetters(String sentence) {
int count;
char ch[] = sentence.toCharArray();
for (int i = 0; i < sentence.length(); i++) {
System.out.print(ch[i]);
}
}
I am trying to display the occurrence of each letter (letter only) in a sentence, and I am lost. I have converted the string into a char array, but I am now lost.
For instance, if I typed the sentence: "Hello, how are you?"
The result would be:
Occurrence of h: 1
Occurrence of e: 2
Occurrence of l: 2
Occurrence of o: 3
etc..
I know I need to utilize my int count, but I am not sure how to do that. Our professor is having us use this:
c[26];
c[ch - 'a']++;
And I'm not sure where to use those for this little project.
Edit: Update
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("type the sentence you want to find the letters of");
String sentence = s.nextLine();
getLetters(sentence);
}
public static void getLetters(String sentence) {
sentence = sentence.toLowerCase();
int count[];
char ch[] = sentence.toCharArray();
for (int i = 0; i < sentence.length(); i++) {
System.out.print(ch[i]);
}
char alphabet[] = "abcdefghijklmnopqrstuvwxyz".toCharArray();
System.out.println();
}
}
Use a HashMap<Character, Integer> to keep track. The key is a unique character, and the integer counts the number of times you see it.
import java.util.HashMap;
public class J {
public static void main(String[] args) {
String string = "aaaabbbccd";
HashMap<Character, Integer> map = frequency(string);
System.out.println(map);
}
public static HashMap<Character, Integer> frequency(String string) {
int length = string.length();
char c;
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
// loop thru string
for (int i = 0; i < length; i++) {
c = string.charAt(i);
// If u have already seen that character,
// Increment its count
if (map.containsKey(c)) {
map.put(c, map.get(c) + 1);
// otherwise this is the first time u
// have seen it, so set count to 1
} else {
map.put(c, 1);
}
}
return map;
}
}
Output:
{a=4, b=3, c=2, d=1}
I don't see reason to use HashMap here. HashMaps are used to map some values into places in memory for faster access, using HashFunction. In this case he will have same, or very similar thing with array and this mapping function that is given to him(ch-'a') . Also, for someone who is doing this, it is maybe too soon for HashMap.
Your problem is that you haven't understood idea.
Letters in java have values (You can check ASCII table). You have 26 letters in alphabet, first one is 'a' and last is 'z'. So you want to have array of 26 elements. Every time when you have 'a' into your string, you want to increment element in place 0 in array, when you come into 'b' you want to increment element in place 1.... when you come to 'z' element 25. So, in fact with (ch-'a') you map your letter in place in array where is count of its ocurrence.
You take string, do .toLowerCase() case on it, pass it once to count letters, then print what you found.
I need a String array with the following attributes:
4 digits numbers
No repeating digits ("1214" is invalid)
No 0's
Is there an easier way to do this than manually type it? Like:
String[] s = {"1234","1235",1236",1237",1238",1239","1243","1245"};
Sorry for my English!
The following code will generate an array with your specifications.
public class Test {
public static void main(String[] args) {
List<String> result = new ArrayList<>();
Set<Character> set = new HashSet<>();
for (int i = 1234; i <= 9876; i++) {
set.clear();
String iAsString = Integer.toString(i);
char[] chars = iAsString.toCharArray();
boolean valid = true;
for (char c : chars) {
if (c == '0' || !set.add(c)) {
valid = false;
break;
}
}
if (valid) {
result.add(iAsString);
}
}
String[] yourStringArray = result.toArray(new String[result.size()]);
System.out.println(Arrays.toString(yourStringArray));
}
}
****edit****
Just saw that it is in Java. So use this function: String.valueOf(number) to convert integer to string if none of the digits are repeats in the loop.
Not sure what language you are doing but I am assuming no repeats not replies.
So what you can do is have a loop from 0 to 9999 and then run through all the numbers while checking if each digit has repeats if so discard number (do not store it into array).
You can convert integers to strings in many languages in their function so you can do that then store it into array.
Good luck.
Hope this helped (fastest solution from my head...there could be more efficient ones)
Try this method for creating Random number with your structure :
ArrayList<Integer> rawNumbers = new ArrayList<Integer>(Arrays.asList(1,2,3,4,5,6,7,8,9));
public String createRandomNumberSring()
{
String result = "";
ArrayList<Integer> numbers = new ArrayList<Integer>();
numbers.addAll(rawNumbers);
for(int i = 0; i < 4; i++)
{
int index = (int)(Math.random() * (numbers.size() + 1));
result += numbers.get(index).toString();
numbers.remove(index);
}
return result;
}
This was my online interview question, and I already submitted the answer. However, the compilation was terminated due to time so I just submitted. Could I get feedback from you? Thanks in advance.
Problem:
Given N numbers , [N<=10^5] we need to count the total pairs of numbers that have a difference of K
Input Format:
1st line contains N & K (integers).
2nd line contains N numbers of the set. All the N numbers are assured to be distinct.
Output Format:
One integer saying the no of pairs of numbers that have a diff K.
Sample Input #00:
5 2
1 5 3 4 2
Sample Output #00:
3
My code:
import java.io.*
import java.util.*;
public class DiffNumbers {
public static void main(String[] args) throws Exception {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String line1 = in.readLine();
String line2 = in.readLine();
int n = Integer.parseInt(line1.split(" ")[0]);
int diff = Integer.parseInt(line1.split(" ")[1]);
Hashtable table = new Hashtable();
int[] arr = new int[n];
for(in i=0; i<n; i++) {
arr[i] = Integer.parseInt(line2.split(" ")[i]);
table.put(Integer.parseInt(line2.split(" ")[i]));
}
int count = 0;
for(in i=0; i<n; i++) {
if(table.containsKey(arr[i]+diff) {
count++;
}
}
system.out.println(count);
}
}
Using HashMap/Table needs extra space. If you want to avoid it you can do it this way
1) Sort the array
2) initialize outputCount as 0
3) Let there be two pointers. "first" start with 0 and "Other" pointer start with 1.
4)
while(arr[other]-arr[first] <requiredDifference)
other ++;
if(arr[other]-arr[first] == requiredDifference)
outputCount++;
else // no match for arr[first]
first++;
5)
return outputCount;
explanation :-
When difference is more than requiredDifference you stop moving ahead "other" poiner. So there is no match for arr[first]. So move ahead first counter. Now do the same logic for new arr[first]. This time you will continue checking from current position of "other" as array is sorted; lower number will not have required match.
public static void main(String[] args) throws Exception{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String line1 = in.readLine();
String line2 = in.readLine();
int diff = Integer.parseInt(line1.split(" ")[1]);
Map<Integer, Object> nMap = new HashMap<Integer, Object>();
Map<Integer, Boolean> uMap = new HashMap<Integer, Boolean>();
Map<Integer, Boolean> lMap = new HashMap<Integer, Boolean>();
String[] numbers = line2.split(" ");
//init maps
for(String number : numbers){
Integer intValue = Integer.valueOf(number);
nMap.put(intValue, new Object()); //original set, N
uMap.put(intValue + diff, false); //upper-bound map
lMap.put(intValue - diff, false); //lower-bound map
}
int count = 0;
for(Integer nKey : nMap.keySet()){
//Do if the lower-bound of n exists in N and if n hasn't used as an upper-bound?
if(nMap.get(nKey - diff) != null && !uMap.get(nKey)){
count++;
//Mark the lower-bound as used.
lMap.put(nKey - diff, true);
}
//Do if the upper-bound of n exists in N and if n hasn't used as an lower-bound?
if(nMap.get(nKey + diff) != null && !lMap.get(nKey)){
count++;
//Mark the upper-bound as used.
uMap.put(nKey + diff, true);
}
}
System.out.println(count);
}
There's not much reason to store the integers in both an array and a hashtable. We can modify your code to do the all of the work in a single for loop.
for(int i=0; i<n; i++) {
int j = Integer.parseInt(line2.split(" ")[i]) //probably not how I would go about this
table.put(j);
if(table.containsKey(j+diff)) {
count++;
}
if(table.containsKey(j-diff)) {
count++;
}
}
I've got this bit of code here:
public class Project1 {
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
System.out.println("Input a binary number");
String binary = input.nextLine();
System.out.println(Conversion(binary));
}
public static int Conversion(String binary)
{
StringTokenizer st = new StringTokenizer(binary, " ");
int n = st.countTokens() - 1; // Used as the power number in b^n for conversion
int result = 0;
while(st.hasMoreTokens()){
int binaryInt = Integer.parseInt(st.nextToken());
result += binaryInt * (1 << n);
n--;
}
return result;
}
}
And it works beautifully... if the input has spaces in between the binary numbers. For example, if the input is 1 1 1 1, then it will rightfully return 15. Cool, but how do I change the tokenizer to not require spaces to split each digit? I tried doing StringTokenizer(binary, ""); and StringTokenizer(binary);, but neither properly split each digit into it's own token.
You will notice that, while StringTokenizer obviously only works with Strings, I've converted the Strings into ints inside my conversion method before returning the result.
# Tony I think you tried to add the ascii values of the digits here
for input value 10
for first run
int binaryInt = binary.char(i) ; so binaryInt would get the value = 49(aski value of char '1')
hence result = 49*2 = 98
in second run
result = 98 + 48 *1 = 146
following function will serve your purpose, for input String "1101" , it returns 13
public int getDecimal(String binaryString){
//binaryString = "1101";
int result = 0;
int n = binaryString.length()-1;
for(int i=0;i<binaryString.length();i++)
{
int num = binaryString.charAt(i);
if(num>=48 && num <=57){
result+=(num-48) * Math.pow(2, n) ;
n --;
}
}
return result;
}
}
How about something like this:
// remove everything that is not a digit
String digitsOnly = binary.replaceAll("[^\\d]","");
//iterate over every digit
for(char digit:digitsOnly.toCharArray()) {
int n = Character.getNumericValue(digit);
// do stuff...
}
If you get a string like "10011010", you don't need a tokenizer, you can just iterate over the string and use charAt:
for (int i = 0; i < s.length(); i++) {
char currentDigit = s.charAt(i);
// Do stuff with the digit
}