Efficient way to get average string in list - java

Having a List that could contain an undefined number of "A", "B", "C" or "D", I have to calculate the average letter in the list.
For example, having [A, C] the average is B.
This is my approach:
public static String calculateAverage(final List<String> letters) {
int numberOfA = 0;
int numberOfB = 0;
int numberOfC = 0;
int numberOfD = 0;
for (String letter : letters) {
if (letter.equalsIgnoreCase("A")) {
numberOfA++;
}
if (letter.equalsIgnoreCase("B")) {
numberOfB++;
}
if (letter.equalsIgnoreCase("C")) {
numberOfC++;
}
numberOfD++;
}
int average =
(numberOfA * 1 + numberOfB * 2
+ numberOfC * 3 + numberOfD * 4)
/ letters.size();
if (average>=1 && average<2) return "A";
if (average>=2 && average<3) return "B";
if (average>=3 && average<4) return "C";
return "D";
}
Is there a more efficient way to do this?

If they are single characters, just sum them and divide by the count:
char averageCharacter(List<String> cs) {
int sum = 0;
for (String c : cs) {
sum += c.charAt(0);
}
return (char) (sum / cs.size()); // Potentially with different rounding.
}
You might want to round the integer division differently:
Floor is just sum / cs.size()
Ceil is (sum + cs.size() - 1) / cs.size()
Round is (sum + cs.size() / 2) / cs.size()

First:
You have an error in your code:
numberOfD++; is always called, because you don't use an if clause.
My approach would be (without writing it, this looks like a Homework you should do yourself):
Assign a int for A-D (lets say 65-68, what would be their char value)...
Loop through your String, add the value of the current Character to an counter
Afterwards divide the counter by the number of characters in your string
Result would be the ascii value of the "avarage" character, which you can cast to char.

Assuming you have validated your input (ie, all entries in the list are a valid 1-character letter):
int count = 0;
int total;
for(String s : letters) {
total += (int) s.charAt(0);
count++;
}
int average = total / count; //Watch out here, this is integer division.
//convert back to char:
return (char) average;

First, your code is incorrect. You are incrementing numberOfD each time, no matter what the letter is. At least make this correction:
for (String letter : letters) {
if (letter.equalsIgnoreCase("A")) {
numberOfA++;
} else if (letter.equalsIgnoreCase("B")) {
numberOfB++;
} else if (letter.equalsIgnoreCase("C")) {
numberOfC++;
} else
numberOfD++;
}
How about just averaging the unicode values:
char[] letters = {'A','B','C','D'};
int sum = 0;
for (char c : letters) {
sum += (int)c;
}
System.out.println((char)(sum/letters.length));

Related

Return the count how many digits are 7 in the given number n

I'm writing a method for my CS151 class called countSevens(n). It Returns count how many digits are 7 in the given number n. This is what I have so far but I'm doing something wrong that I can't figure out.
public int countSevens(int n){
int count = 0;
String strI = Integer.toString(n);
for (int i = 0; i < strI.length(); i++){
if(strI.substring(i).equals("7")){
count++;
}
}
return count;
}
You can do it with java streams
public int countSevens(int n) {
return (int) String.valueOf(n).chars().filter(ch -> ch == '7').count();
}
(int) - cast to an int type, in this particular case it safe to cast long to int, because we can't get a conversation error. In other cases it's better to use Math.toIntExact(long)
String.valueOf(n) - convert to string
chars() - return stream of chars
filter(ch -> ch == '7') - filter all chars that equals to 7
count() - returns the count of elements in this stream
strI.substring(i)
Will return the part of string from i-character to the end.
Use strI.charAt(i) instead
From the definition of String.substring(int):
Returns a string that is a substring of this string. The substring begins with the character at the specified index and extends to the end of this string.
So this will only count the last instance of a 7 in your number, and only if it's the last digit in the number.
Instead, try this:
if(strI.substring(i, i+1).equals("7"))
Or, since you're dealing with ints, you can avoid using strings altogether. n % 10 will get you the last digit, and n /= 10 will bump the entire number right by one digit. That should be enough to get you started on doing this without Strings.
To count the number of 7s in an integer:
int counter = 0;
int number = 237123;
String str_number = String.valueOf(number);
for(char c : str_number.toCharArray()){
if(c == '7'){
counter++;
}
}
You can just use simple arithmetics:
public static int countSevens(int i) {
int count = 0;
for (i = i < 0 ? -i : i; i != 0; count += i % 10 == 7 ? 1 : 0, i /= 10);
return count;
}
But who can read this? Not many, so here is a cleaner solution, applying the same logic:
public static int countSevens(int i) {
int count = 0;
// ignore negative numbers
i = Math.abs(i);
while(i != 0) {
// if last digit is a 7
if(i % 10 == 7) {
// then increase the counter
count++;
}
// remove the last digit
i /= 10;
}
return count;
}

Convert number in a certain base to a decimal number using recursion

My assignment is to create a recursive method makeDecimal that when passed a number (that is represented by a String) and its base, converts the number to base 10. You will need to use the method Integer.parseInt(str). (Hint: use substrings.) This method takes a String and returns the integer form of it.
For example, Integer.parseInt("21"); will return the int 21.
Here are some examples of how makeDecimal works:
makeDecimal("11", 2) will return 3.
makeDecimal("100", 4) will return 16.
Here was my attempt at it:
public static double makeDecimal(String number, int base){
int len = number.length();
double f = 0;
if(len <= 0)
return 0;
else{
makeDecimal(number,base);
double temp = Integer.parseInt(number.substring(len - 1, len + 1));
f = f + temp * Math.pow(3, len-1);
}
len--;
return f;
}
However, I get an "overflow error", and I don't know if it even is written correctly.
You are recursing with exactly the same arguments that were passed in. As a result, the call will itself recurse the same way, until the stack overflows. That's not how recursion is supposed to work. Instead, you need to figure out how to do one piece of the problem in the current call and then recurse to do a smaller problem.
In your code, it's not even clear what logic you are using. (What's the point of computing 3len-1?) Try this instead:
If the input string has length 0, the answer is 0 (that part you got right)
Otherwise, take the last digit and parse it in the current base. Then the answer is that value plus base times the value of everything up to but not including the last digit of the input. (Hint: this is a good place to use recursion.)
You should be able to translate that description into the appropriate method calls and use of substring().
Oh, one other thing: there's no reason to be using double values here. Just stick with int variables throughout. You won't be needing Math.pow().
Here is simplest solution using recursion, substring and Integer.parseInt:
public int makeDecimal(String value, int base) {
// exit from recursion
if (value.length() < 1)
return 0;
//parsing last character of string
int charValue = Integer.parseInt(value.substring(value.length() - 1), base);
//calling recursion for string without last character
return makeDecimal(value.substring(0, value.length() - 1), base) * base + charValue;
}
Here's my solution after writing the prototype in Python (if you are interested, I can also include the Python source code):
import java.util.HashMap;
import java.util.Map;
public class MakeDecimal {
public static final Map<Character, Integer> alphabet = buildAlphabetTable();
public static void main(String[] args) {
// System.out.println(alphabet);
System.out.println(makeDecimal("af10bb1", 16));
}
// pos refers to the position of the character in the string.
// For example, if you have the following binary string 100
// then 1 at the left is at position 2,
// the 0 in the middle is at position 1,
// and the right most 0 is at position 0
// (you start counting from the right side).
// In general, you would convert that string in the following way:
// 2^2 * 1 + 2^1 * 0 + 2^0 * 0 = 4
// If the base was n, then you would have
// first * n^{pos + "length of string - 1"} + ... + penultimate * n^{pos + 1} + last * n^{pos}
// Note that pos starts from 0.
private static int makeDecimal(String s, int base, int pos) {
if (s.length() == 0) {
return 0;
} else {
int last = (int) Math.pow(base, pos) * alphabet.get(s.charAt(s.length() - 1));
return makeDecimal(s.substring(0, s.length() - 1), base, pos + 1) + last;
}
}
public static int makeDecimal(String s, int base) {
if (s.length() == 0) {
return 0;
}
if (base < 2 || base > 36) {
throw new IllegalArgumentException("not base >= 2 and base <= 36");
}
return makeDecimal(s.toLowerCase(), base, 0);
}
// Creates a table that maps characters to their decimal value
// the characters can be also '0' or '2' (or any other character number)
// or they can be a character of the English alphabet
private static Map<Character, Integer> buildAlphabetTable() {
Map<Character, Integer> a = new HashMap<>(36);
int i = 0;
for (char c = '0'; c <= '9'; c++, i++) {
a.put(c, i);
}
for (char c = 'a'; c <= 'z'; c++, i++) {
a.put(c, i);
}
return a;
}
}
My solution is based on the following post, which you should definitely read to refresh your ideas on how to convert between bases.
http://www.purplemath.com/modules/numbbase.htm
It does not accept bases that are smaller than 2 or greater than 36. It handles also when you pass English characters in upper case.
Edit: At first I've misted that recursion is obligated for this solution so my original answer without it could me four below.
Here is solution with recursion and without substring and Math.pow:
public double makeDecimal(String value, int base) {
makeDecimal(value, base, value.length() - 1);
}
public double makeDecimal(String value, int base, int index) {
double result = 0;
if (index < 0)
return result;
double charValue = 0;
char currentChar = values.get(Character.toUpperCase(value.charAt(index));
if (currentChar >= 0 && currentChar <= '9') {
charValue = currentChar - '0';
} else if (currentChar >= 'A' && currentChar <= 'Z') {
charValue = currentChar - 'A';
} else {
throw new InvalidValueException("Unsupported character '" + currentChar + "'.");
}
if (charValue >= base) {
throw new InvalidValueException("Wrong character '" + currentChar + "' for base '" base + "'.");
}
return makeDecimal(value, base, index - 1)) * base + charValue;
}
Original Answer: Something like this should work for any base starting from 2 till 36:
private Map<Character, Integer> getCharValues(int base)
{
Map<Character, Integer> values = new HashMap<Character, Integer>();
for (int i = 0; i < base; i++){
if (i < 10) {
values.put('0' + i, i);
} else if (i < 36) {
values.put('A' + i - 10, i);
} else {
throw new InvalidValueException("Base '" + base + "' not supported");
}
}
return values;
}
public double makeDecimal(String value, int base)
{
Map<Character, Integer> charValues = getCharValues(base);
double result = 0;
for (int i = 0; i < value.length(); i++){
result = result * base + charValues.get(Character.toUpperCase(Character.toUpperCase(value.charAt(i))));
}
return result;
}
If you need base more then 36 you can extend char set in method getCharValues. Also it will be a good idea do not create HasMap every time but just store it for maximum base and throw exception if char value exceed given base.

How to add numbers(integers) that are stored inside a string

I have to create a program that uses Luhn's algorithm to check to see if a credit card is valid.
The algorithm is this:
Form a sum of every other digit, including the right-most digit; so
5490123456789128 sums to 8+1+8+6+4+2+0+4 = 33
Form double each remaining digit, then sum all the digits that creates it; the remaining digits in our example (5 9 1 3 5 7 9 2) double to 10 18 2 6 10 14 18 4, which sums to 1+0+1+8+2+6+1+0+1+4+1+8+4 = 37
Add the two sums above (33+37 = 70)
If the result is a multiple of 10 (i.e., its last digit is 0) then it was a valid credit card number.
I made a Scanner and saved the credit card number into String card number
Then I created a while loop to save every other character starting from the right into a string. So now, I have a string filled with every other digit of the credit card number, starting from the right. However, I need to add up all of the digits within that string, which I can't figure out.
For example, if the user entered 1234 as the card number, the string everyotherdigit = 42. How can I add up 4 and 2 within the string?
There are numerous ways to do that. You can actually find your own solution by doing a bit of googling.
Anyway, this is what you can do:
Get individual characters from your string, and convert them to int.
String cardNumber = "5490123456789128";
int value = cardNumber.charAt(0) - '0';
Using a for loop and changing 0 to x(loop counter) will solve everything.
Get single String and convert to int.
String cardNumber = "5490123456789128";
int value = Integer.parseInt(cardNumber.substring(0,1));
I'd treat the string as an array of chars, and use Character.digit(int, int) to convert each character to the corresponsing int:
public static boolean isValidCreditCard (String s);
char[] arr = s.toCharArray();
int everyOtherSum = 0;
for (int i = arr.length - 1; i >= 0; i -= 2) {
everyOtherSum += Character.digit(arr[i], 10);
}
int doubleSum = 0;
for (for (int i = arr.length - 2; i >= 0; i -= 2) {
int currDigit = Character.digit(arr[i], 10);
int doubleDigit = currDigit * 2;
while (doubleDigit > 0) {
doubleSum += (doubleDigit % 10);
doubleDigit /= 10;
}
}
int total = everyOtherSum + doubleSum;
return total % 10 == 0;
}
So something like this would work for you:
public static void main(String[] args)
{
String cardNum = "5490123456789128";
String others = null;
int evenDigitSum = 0;
int oddDigitTransformSum = 0;
for (int pos = 0; pos < cardNum.length(); pos++)
{
if ((pos%2) != 0)
{
evenDigitSum += (cardNum.charAt(pos) - '0');
}
else
{
others = Integer.toString((cardNum.charAt(pos)-'0')*2);
for (char c : others.toCharArray())
{
oddDigitTransformSum += (c-'0');
}
}
}
System.out.println("Odds: " + oddDigitTransformSum);
System.out.println("Evens: " + evenDigitSum);
System.out.println("Total: " + (evenDigitSum+oddDigitTransformSum));
System.out.println("Valid Card: " + ((evenDigitSum+oddDigitTransformSum)%10==0));
}
public int cardCount(String numbers){
Stack<Integer> stack = new Stack<>();
int count = 0;
for(char c : numbers.toCharArray()){
stack.push(Character.getNumericValue(c));
}
int size = stack.size();
for(int i=1;i <= size; i++){
if(i%2 != 0){
count = count + stack.pop();
}else{
stack.pop();
}
}
return count;
}
This just does what you asked, not the entire algorithm

Is there a function in java that works like SUBSTRING function but for integers?

is there a function in java that works like SUBSTRING function but for integers. Like for example the user's input is 456789, I want to break it into two part and put them into different variable. and divide them. for example,
user's input : 456789
the first 3 numbers will be in variable A.
the last 3 numbers will be in variable B.
pass = A/B;
can someone help me how can I do this,
thanks.
Use integer division and the modulus operator:
int input = 456789;
int a = input / 1000;
int b = input % 1000;
Here is a mathematical based implementation for positive and negative integers (probably can be optimized):
public static void main(String[] args) {
System.out.println(substring(2, 0, 1)); // prints "2"
System.out.println(substring(2523, 2, 2)); // prints "23"
System.out.println(substring(-1000, 0, 2)); // prints "-1"
System.out.println(substring(-1234, 0, 4)); // prints "-123"
System.out.println(substring(-1010, 2, 1)); // prints "0"
System.out.println(substring(-10034, 3, 2)); // prints "3"
System.out.println(substring(-10034, 2, 4)); // prints "34"
}
public static int substring(int input, int startingPoint, int length) {
if (startingPoint < 0 || length < 1 || startingPoint + length > size(input)) {
throw new IndexOutOfBoundsException();
}
if (input < 0 && startingPoint == 0 && length < 2) {
throw new IndexOutOfBoundsException("'-' can not be returned without a digit");
}
input /= (int) Math.pow(10, size(input) - length - startingPoint); // shift from end by division
input = input % (int) Math.pow(10, length); // shift from start by division remainder
if (input < 0 && startingPoint > 0) {
input = Math.abs(input); // update sign for negative input
}
return input;
}
private static int size(int input) {
int size = 1;
while (input / 10 != 0) {
size++;
input /= 10;
}
return input < 0 ? ++size : size; // '-'sign is a part of size
}
Splitting a "number" is not what you want to do. You want to split the NUMERAL, which is the string representing a quantity (number). You can split the numeral just like any other literal (string): don't parse the user's input and use substring. If you want to make sure the literal is an actual numeral, parse it to see if an exception is thrown. If not, you have a numeral. But don't hold on to the integers, keep the strings instead.
Here you go:
You give the method a number, start, and end indexes.
public static void main(String[] args) {
System.out.println(getPartOfInt(93934934, 3, 7));`
}
public static int getPartOfInt(int number, int start, int end){
Integer i = new Integer(number);
char[] chars = i.toString().toCharArray();
String str = "";
for(int j = start; j < end && j < chars.length; j++){
str += chars[j];
}
return Integer.parseInt(str);
}
OR:
public static int getPartOfInt(int number, int start, int end){
String str = new Integer(number).toString();
return Integer.parseInt(str.substring(start, Math.min(end, str.length())));
}
You could also first convert the number to String, like so:
int num = 456789;
String strNum = String.valueOf(num);
String part1 = strNum.substring(0, strNum.length() / 2 - 1);
String part2 = strNum.substring(strNum.length() / 2);
Then, you could convert it back to int, like so:
int part1Num = Integer.parseInt(part1);
int part2Num = Integer.parseInt(part2);
Now you can do all the arithmetic you want with those two int's.
#DeanLeitersdorf Here's the function ( #clcto s solution)
int subinteger(int input, int from, int size)
{
while (input > pow(10, size + from) - 1)
input /= 10;
return input % (int)pow(10, size);
}
This is a c++ solution but i hope that you can convert it to Java easily

Accessing single letters in String / digits in numbers - Java

I have numeric input (11 digits), and I need to perform some operations on each digit (example: multiply 1st by 5, 2nd by 3, etc.). How can I do so in Java? Is there a simple way to access single letter / digit? Is there another way to do it?
If you don't want to convert the number to a string, then there is a simple trick.
digit = number % 10
will give you the right most digit.
number = number / 10
Will remove the right most digit from the number.
So you can run in a loop until the number reaches 0.
while(0 < number)
{
int digit = number % 10;
number = number / 10;
// do here an operation on the digits
}
You can use a for loop to help you count. For example
for(int index = 0; 0 < number; ++index, number /= 10)
{
int digit = number % 10;
// do an operation on the number according to the 'index' variable
}
Here is a similar StackOverFlow question on a similar question
Well there are many ways you can do it like :
int a = 12345;
int b;
while(a>0)
{
b = a%10;
System.out.print(b + " ");
a = a/10;
}
Here it gives you the digits in reverse order like you will get b=5 then b=4....
You can just manipulate them
Other way
int d = 12345;
String str = String.valueOf(d);
for(int i=0;i<str.length();i++)
{
char c = str.charAt(i);
System.out.print(Character.getNumericValue(c) * 10 + " ");
}
Or
char c[] = str.toCharArray();
for(Character ch : c)
{
System.out.print(Character.getNumericValue(ch) * 2 + " ");
}
You can use .charAt() to get a character from a string. Then using Character.getNumericValue() you can convert the character to an integer.
Like this:
String string = "1434347633";
int digit1 = Character.getNumericValue(string.charAt(1));
Convert that number input to String data type so that you can interpret it as a String.
int numbers = 1122334455; // integer won't be able to save this much data,
// just for example ok,
String numberString = numbers.toString();
foreach (char number in numberString) {
// do work on each of the single character in the string.
}
You should work them out, depending on the some condition.
If you want to access the digits by index without converting to a string, you can use these two functions length and digitAt:
public class DigitAt {
public static int length(long v) {
return (int) Math.ceil(Math.log10(v));
}
public static int digitAt(long v, int digit) {
return (int) ((v / (long) Math.pow(10, length(v) - digit - 1)) % 10);
}
public static void main(String[] args) {
System.out.println("Digits: " + length(1234567));
System.out.println(digitAt(1234567, 0));
System.out.println(digitAt(1234567, 1));
System.out.println(digitAt(1234567, 6));
}
}
public String stringAfterOperations(String digits) {
ArrayList<Integer> z = new ArrayList<Integer>();
for(Character c: digits.toCharArray()) {
z.add(Character.getNumericValue(c));
}
//TODO Set your own operations inside this "for"
for(int i=0; i<z.size(); i++){
if(i == 1){
z.set(i, z.get(i)*4);
}
else if(i == 7){
z.set(i, z.get(i)/3);
}
else {
z.set(i, z.get(i)+2);
}
}
String newString = "";
for(Integer i: z){
newString += i;
}
return newString;
}

Categories

Resources