Iterate each digit in an integer and do mod 11 [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am trying to do some program and need of some help. For example, I entered this number on a textbox: 00669253, then for each number i want to multiply it with the number 87654321 so for example
(0x8) + (0x7) + (6x6).... and so on and then get the sum of all the number and do a mod of 11. How can I do this?
Thanks for your advance help.

You can first convert the number into String and then you can do it like this :
String no1="00669253";
String no2="87654321";
int sum=0;
for(int i=0;i<no1.length();i++){
sum+=Integer.parseInt(""+no1.charAt(i))*Integer.parseInt(""+no2.charAt(i));
}
After that you can do any operation on sum

You can try something like that:
public class TestMult {
public static void main(String[] args) {
String first = "00669253";
String second = "87654321";
long sum = 0L;
if (first.length() == second.length()) {
for (int i = 0; i < first.length(); i++) {
int firstInt = Character.getNumericValue(first.charAt(i));
int secondInt = Character.getNumericValue(second.charAt(i));
sum += firstInt * secondInt;
}
System.out.println("result: " + sum % 11);
} else {
System.err.println("lengths are not equal.");
}
}
}

try this,
public class Dummy {
public static void main(String[] args) {
String s = "112211";
String s2 = "010101";
char[] sDummy = s.toCharArray();
char[] s2Dummy = s2.toCharArray();
int sum = 0;
for (int i = 0; i < sDummy.length; i++) {
System.out.println("multiplying..." + sDummy[i] + "with " + s2Dummy[i] + "and adding prev sum " + sum + " to it");
sum = sum + (Integer.parseInt(sDummy[i] + "") * Integer.parseInt(s2Dummy[i] + ""));
}
sum = sum % 11;
System.out.println("sum with mod is = " + sum);
}
}
You need to add some checks in case if length of both string differs

Try this,
String inputValue = "00669253";
String multipleValue="87654321";
int result = 0;
for (int i = 0; i < inputValue.length(); i++)
{
result += Integer.parseInt(Character.toString(inputValue.charAt(i))) *
Integer.parseInt(Character.toString(multipleValue.charAt(i)));
}

Related

I am trying to understand the following code below [duplicate]

This question already has answers here:
What is a debugger and how can it help me diagnose problems?
(2 answers)
Closed 3 years ago.
I am getting a different value when I am performing the iteration manually on
"welcometojava"
when the value of i=5
I am getting following value of variable
when i=5;
substring =MET
smallest="com"
largest="ome"
At this point, the value that I am getting is not validating both the if conditions
I want help with the values of all 3 variables on each iteration so that I can know where I am getting
wrong.Thankyou
public class Solution {
public static String getSmallestAndLargest(String s, int k) {
String smallest = "";
String largest = "";
smallest = largest = s.substring(0, k);
for (int i=1; i<s.length()-k+1; i++) {
String substr = s.substring(i, i+k);
if (smallest.compareTo(substr) > 0)
smallest = substr;
if (largest.compareTo(substr) < 0)
largest = substr;
}
return smallest + "\n" + largest;
}
If you are not using a debugger, you can trace the values by printing them e.g. I've added System.out.println("i=" + i + ", substring=" + substr + ", smallest=" + smallest + ", largest=" + largest); into your code as follows and also shown the output below it to help you understand how your code is behaving:
public class Solution {
public static void main(String[] args) {
getSmallestAndLargest("welcometojava", 3);
}
public static String getSmallestAndLargest(String s, int k) {
String smallest = "";
String largest = "";
smallest = largest = s.substring(0, k);
for (int i = 1; i < s.length() - k + 1; i++) {
String substr = s.substring(i, i + k);
if (smallest.compareTo(substr) > 0)
smallest = substr;
if (largest.compareTo(substr) < 0)
largest = substr;
System.out.println("i=" + i + ", substring=" + substr + ", smallest=" + smallest + ", largest=" + largest);
}
return smallest + "\n" + largest;
}
}
Output:
i=1, substring=elc, smallest=elc, largest=wel
i=2, substring=lco, smallest=elc, largest=wel
i=3, substring=com, smallest=com, largest=wel
i=4, substring=ome, smallest=com, largest=wel
i=5, substring=met, smallest=com, largest=wel
i=6, substring=eto, smallest=com, largest=wel
i=7, substring=toj, smallest=com, largest=wel
i=8, substring=oja, smallest=com, largest=wel
i=9, substring=jav, smallest=com, largest=wel
i=10, substring=ava, smallest=ava, largest=wel
In a similar way, you can add some more print statements e.g. to print the value of smallest.compareTo(substr) > 0 and so on to trace your code to a deeper level. However, I strongly recommend you use a debugger to do so.

Applying the operators on digits of number to get the desired number [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
Following is the google interview question, Can someone please solve or provide the logic to find the answer. Operators [+,-,*]
Output should be the list of all the possible strings which generates the target number.
Ex1:
Input = 1234
Desired number = 6
Expected Output = [2+4,3+4-1,2*3,1+2+3... etc]
Ex2:
Input = 105
Desired number = 5
Expected Output = [10-5,1*5... etc]
Here is quick fix for you.
Please check following code.
public static void main(String arg[]) {
String num = "105";
int target = 5;
getValue(num, target);
}
static void check(double sum, double previous, String digits, double target, String expr) {
if (digits.length() == 0) {
if (sum + previous == target) {
System.out.println(expr + " = " + target);
}
} else {
for (int i = 1; i <= digits.length(); i++) {
double current = Double.parseDouble(digits.substring(0, i));
String remaining = digits.substring(i);
check(sum + previous, current, remaining, target, expr + " + " + current);
check(sum, previous * current, remaining, target, expr + " * " + current);
check(sum, previous / current, remaining, target, expr + " / " + current);
check(sum + previous, -current, remaining, target, expr + " - " + current);
}
}
}
static void getValue(String digits, double target) {
for (int i = 1; i <= digits.length(); i++) {
String currentValue = digits.substring(0, i);
check(0, Double.parseDouble(currentValue), digits.substring(i), target, currentValue);
}
}
Output :
1 * 0.0 + 5.0 = 5.0
1 * 5.0 = 5.0
10 - 5.0 = 5.0
Hope this example is help you to understand the concept.

Is it possible to loop a method with different parameters? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
so this is the case.
I'm doing an excercise where I have to compare each random number with all my static numbers from an external file lotto.dat
I have to make a method doCompare() which returns either true or false. My question will appear after my code:
public static void drawNumbers()throws Exception{
Random rnd = new Random();
int rndN1 = rnd.nextInt(19)+1;
int rndN2 = rnd.nextInt(19)+1;
int rndN3 = rnd.nextInt(19)+1;
int rndN4 = rnd.nextInt(19)+1;
int rndN5 = rnd.nextInt(19)+1;
int rndN6 = rnd.nextInt(19)+1;
System.out.println();
System.out.println("Winner numbers: " + rndN1 + " " + rndN2 + " " + rndN3 + " " + rndN4 + " " + rndN5 + " " + rndN6);
String match = doCompare(rndN1);
if(match.equals("true")){
System.out.println("Match on the number: " + rndN1);
}
}
So is it possible somehow loop the "doCompare" with parameters "doCompare(rndN1)" then rndN2, rndN3 and so on or what else should I do to make this work?
Use a proper data structure, like an array or a List to store the random numbers and loop over them:
List<Integer> numbers = new ArrayList<>();
for(int cout = 0 ; count < 6 ; ++count) {
numbers.add(rnd.nextInt(19)+1);
}
// ...
for(int n : numbers) { // go through all the numbers in the list
doCompare(n);
}
Create a List which can collect your integers. Create a loop which create the integers and add them to a list. While creating the random integers, you can create the output string in the loop too. And at the end use another loop for the method call doComapre() and pealse change the return value of doCompare() method to boolean. Then you can use it in the if statement and have not to check if the return value is equals "true".
Random rnd = new Random();
List<Integer> rndNumbers = new ArrayList<>();
String outputString = "Winner numbers:";
for(int i = 0; i < 6; i++)
{
rndNumbers.add(rnd.nextInt(19) + 1);
outputString = outputString + " " + rndNumbers.get(i);
}
System.out.println();
System.out.println(outputString);
for(Integer curNumb : rndNumbers)
{
String match = doCompare(curNumb );
if (match.equals("true"))
{
System.out.println("Match on the number: " + curNumb );
}
}
Maybee you can use an array because you are always want to generate six numbers. And for the String creation you can replace the String with a Stringbuilder.
The simplest solution would be to create array or list and store rnd number and then loop over it
Yes, you can, but not as you want to do it.
you have to create a list of your rndNX values
Like so:
List<Integer> rndList = new ArrayList<Integer>();
fill it like so :
rndList.add(rnd.nextInt(19)+1);
rndList.add(rnd.nextInt(19)+1);
...
And use the list :
for(final Integer rndI : rndList)
{
String match = doCompare(rndI );
}
Random rnd = new Random();
System.out.println();
for(int i = 0; i < 6; i++)
{
int rndN = rnd.nextInt(19)+1;
String match = doCompare(rndN);
if(match.equals("true")){
System.out.println("Match on the number: " + rndN1);
}
}
You could do something like this. Instead of initializing all your random numbers first initialize them in a loop as needed.
Store the int values into the array or a list and loop through it.

My Java program seems to get...stuck (?) at a point during execution. I'm baffled.

So, I'm trying to create a driver for my method. I apologize in advance, I know very little about what I'm talking about. What the program does, is it calculates sine, cosine, and the exponential function by means of taylor series for a number that the user inputs. The use of Math.pow and Math.fact were not allowed. My compiler isn't giving me any errors, and I'm all out of ideas at this point. In addition, the scanner doesn't seem to stop accepting input after I press enter. It continues to take numbers, but doesn't do anything else. It gives an exception when I type a letter. High possibility of ID10T error. I know that the output isn't well formatted yet, but that's because I haven't had a chance to see it yet. If someone could help me figure this out, I would be very greatful. Thanks in advance!
-An aspiring code monkey
Driver (Lab4.java)
/*
This program is being created to solve Lab 4.
*/
import java.util.*;
public class Lab4
{
public static void main(String[] args)
{
String again, more = "y";
while (more.toUpperCase().charAt(0) == 'Y')
{
Scanner keyboard = new Scanner (System.in);
System.out.println("Input X: ");
Function number = new Function();
double x = number.x();
System.out.println("x = " + x);
Function sine = new Function();
double mySin = sine.funcSine();
Function cosine = new Function();
double myCos = cosine.funcCos();
Function expo = new Function();
double myExp = expo.funcExp();
System.out.println("\t\t\t\tLibraryResult My Result");
System.out.println("\n\t\tsin(" + Function.x() + ")" + " = " + "\t\t\t" + Math.sin(Function.x()) + "\t" + mySin);
System.out.println("\n\t\tcos(" + Function.x() + ")" + " = " + "\t\t\t" + Math.cos(Function.x()) + "\t" + myCos);
System.out.println("\n\t\texp(" + Function.x() + ")" + " = " + "\t\t\t" + Math.exp(Function.x()) + "\t" + myExp);
System.out.println("\n\t\t\tDo more (Y/N) ? ");
more = keyboard.next();
String junk = keyboard.nextLine();
}
}
}
Method (Function.java)
/*
This class provides the information for the parent to use in order to solve Lab 4.
*/
import java.util.*;
public class Function
{
Scanner keyboard = new Scanner(System.in);
public static int number;
private double temp = 1;
private double last = 1;
public static double x()
{
Scanner keyboard = new Scanner(System.in);
double x = keyboard.nextDouble();
return x;
}
public static double pow(double value, double power)
{
if(power == 0)
{
return 1;
}
double result = value;
for(int i = 0; i < power -1; i++)
{
result = result * value;
}
return result;
}
public static double getFact()
{
while (number < 0)
{
number =(number * -1);
}
double factorial = 1;
if (0 == (number % 1))
{
do
{
factorial = factorial * number;
--number;
} while (number >= 1);
}
else //Stirling's Approximation
{
double e = 2.718281828459;
double part1 = Math.sqrt(2 * 3.141592653589 * number);
double part2a = (number / e);
double part2b = (pow(part2a,number));
factorial = (part1 * part2b);
}
return factorial;
}
public static double funcSine()
{
int place = 0;
double next = x()*1;
for(number = 3; number <= 30; number = number + 2)
{
next = next + ((pow((-1),place))*((pow(x(),number))/(getFact())));
place = place + 1;
}
double mySin = next * 1;
return mySin;
}
public static double funcCos()
{
int place = 0;
double next = 1;
for(number = 2; number <= 30; number = number + 2)
{
next = next + ((pow(-1,place))*((pow(x(),number))/(getFact())));
place = place + 1;
}
double myCos = next * 1;
return myCos;
}
public static double funcExp()
{
int place = 0;
double next = 1 + x();
for(number = 1; number <= 30; number++)
{
next = next + ((pow(-1,place))*((pow(x(),number))/(getFact())));
place = place + 1;
}
double myExp = next * 1;
return myExp;
}
}
Check the syntax of your while loop:
while (more.toUpperCase().charAt(0) == 'Y')
Think about when the program will ever not satisfy this expression.
Also you have multiple Scanners all over your code. ITs not clear why you need to keep reading inout over and over again.

Counting Characters in a Text File [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
Hey guys i'm trying to write a code that will count the characters in a text file.
ex : AAABBbbcC
3A 2B 2b 1c 2C
but i don't know how to count the characters like (AAA) if they are not separated.
i'm trying this but it doesn't work like a recursion
String s = "aasjkkk";
int count1 = 0;
int count2 = 0;
char karakter1 = 0;
char karakter2 = 0;
for(int i = 0; i < s.length(); i++){
if(s.charAt(i) == s.charAt(i+1)) {
karakter1 = s.charAt(i);
count1 += 1;
System.out.print(count1 + " " + karakter1 + " ");
}
else if(s.charAt(i) != s.charAt(i+1)) {
karakter1 = s.charAt(i);
karakter1 = 1;
karakter2 = s.charAt(i+1);
karakter2 = 1;
System.out.print(count1 + " " + karakter1 + " " + count2 + " " + karakter2 + " ");
}
}
Since this looks like a homework, I can suggest a way for you to do this:
Create a HashMap
Loop from the beginning to the end of the file. If you have a new character, then set a new key to the HashMap with 1 as the value; if not, just plus one to the current value of the old character
Have fun !!
It's true that you should and must show what you've tried before.
I think that you could have already thought about taking the String into a char array, iterating, etc...
Well, #bubuzz advise is a good one, here it comes an implementation:
public class ClasesObjetos {
public static void main(String[] args) {
String s = "This is a single String";
HashMap<Character, Integer> m = new HashMap();
for (Character c : s.toCharArray()) {
if (!c.equals(" ")) {
if (m.get(c) == null )
m.put(c, 1);
else {
int i = (int) m.get(c) + 1;
m.put(c, i);
}
}
}
for (Character c : m.keySet()) {
System.out.println(c + " ---> " + m.get(c));
}
}
}
Try it out you'll see it ignores spaces. It will count any symbols though, you should you add up if checks.

Categories

Resources