I have created a program which compares different search methods which search for a random int value 0-999 from a sorted array which is 0-999. I have created a binary search which works perfectly and after doing this I decided to try to create a search which, instead of splitting the values into half, splits them into 1/3 and 2/3 depending.
So basically if I have
{1,2,3,4,5,6,7,8,9,10,11,12,13,14,15}
and I was looking for 10 I would go from above to
{6,7,8,9,10,11,12,13,14,15}
to
{10,11,12,13,14,15}
to
{10,11}
then
simple {10} and return the index of this value.
I currently have:
int loopTotal3 = 0;
for(int y = 0; y < 1000; y++){
System.out.println("Reference1");
int first = 0;
int last = array0Through999.length - 1;
int third = (array0Through999[0] + array0Through999[999]) / 3;
int findThis3 = rand.nextInt(1000);
int loop3 = 0;
while(first <= last){
System.out.println("Reference2");
loop3++;
if (array0Through999[third] < findThis3){
System.out.println("Reference3");
first = third + 1;
}
else if(array0Through999[third] == findThis3){
System.out.println("Reference4");
break;
}
else{
System.out.println("Reference5");
last = third-1;
}
third = (first + last) / 3;
}
loopTotal3 = loopTotal3 + loop3;
}
int loopAverage3 = loopTotal3 / 1000;
System.out.println("The average number of times for a Binary Search is: " + loopAverage3 + "\n");
The code is currently getting stuck running through the first if statement and I am not positive of why.
Any ideas about my issue or if this logic is close to correct?
Using the same algorithm on a smaller data set, I can see an issue. Use an array with only 3 members: 0 1 2. Try to find 2. Third will get stuck on 1, and never get up high enough to find 2.
This will infinitely loop never getting third up to 2. You may be hitting a similar window somewhere else in the code. Because it enters the first if, it does first = third + 1 which yields first = 2. third=(first+last)/3=4/3=1.
import java.util.Random;
public class weqfgtqertg {
public static void main(String args[]) {
int array0Through999[] = {0,1,...,999};
int loopTotal3 = 0;
Random rand = new Random();
for(int y = 0; y < 1000; y++){
//System.out.println("Reference1");
System.out.println(y);
int first = 0;
int last = array0Through999.length - 1;
int third = (first + last) / 3;
int findThis3 = rand.nextInt(1000);
int loop3 = 0;
while(first <= last) {
//System.out.println("Reference1");
loop3++;
if (array0Through999[third] < findThis3){
//System.out.println("Reference3");
first = third+1;
}
else if(array0Through999[third] == findThis3){
//System.out.println("Reference4");
break;
}
else{
//System.out.println("Reference5");
last = third-1;
}
int calc = last - first;
third = first + (calc/3);
}//end while
loopTotal3 = loopTotal3 + loop3;
}//end for
int loopAverage3 = loopTotal3 / 1000;
System.out.println("The average number of times for a Tertiary Search is: " + loopAverage3);
}
}
It has been a while since I posted this question but I finally got around to solving my issue. Here is the correct code for anyone who may stumble upon this.
edit: The array includes the "..." to make this not obnoxious to read or put out onto the screen. I had all 0-999 within my array hard coded.
Related
I am trying to figure out how to write my code that it reads from the right to left, not left to right
public static int sumofEvenSpot(long number)
{
int sumEvenSpot = 0;
String stringLength = Long.toString(number);
for (int i = 0; i< stringLength.length(); i += 2)
sumEvenSpot += (getDigit(Character.getNumericValue(stringLength.charAt(i)) * 2));
return sumEvenSpot;
}
Just do for(int i = stringLength.length() - 1; i = 0; i = i - 2)
( for(start, end, increment) )
OR
You can reverse your string and do a normal for but it takes more code
You can start summing from the rightmost digit, and every iteration divide the number by 100 in order to remove the current digit and the next one (in the odd place) in order to keep summing the following even digit:
int sum = 0;
while(number > 0) {
sum += number % 10;
number /= 100;
}
One advantage of doing it this way is that you don't have to convert the long to string and then back to int.
I have an integer in java "1234567" and my program finds middle digit in a set of integer, is there more optimized way than below code?. Recently asked in java interview.
What I have done is first find no of digits, first, last and middle indexes. Then find middle digit again iterating on same integer. Please advice some optimization.
int a1 = 1234567;
int a = a1;
// calculate length
int noOfDigits = 0;
while(a!=0)
{
a = a/10;
noOfDigits++;
}
int first = 0;
int last = noOfDigits-1;
int middle = (first+last)/2;
boolean midExists = ((a1%2)==1);
System.out.println(" digits: "+a1);
System.out.println(" no of digits "+noOfDigits);
System.out.println(" first "+first);
System.out.println(" last " + last);
if(midExists)
{
System.out.println(" middle " + middle);
int i = last;
int middleDigit = 0;
a = a1;
while(i != middle)
{
a = (a / 10);
middleDigit = (a%10);
i--;
}
System.out.println("middle digit: " + middleDigit);
}
else
System.out.println(" Mid not Exists.. ");
Program Output:
digits: 1234567
no of digits 7
first 0
last 6
middle 3
middle digit: 4
You can also do this in one pass. Idea is that first store the integer in the another variable. Then move two digits to the left in one integer while only one digit in the another one.
int a1 = 1234567;
int a2 = a1;
int flag=0;
while(a2>0)
{
a2/=10; //Moves to the left by one digit
if(a2==0) //If there are odd no. of digits
{
flag=1;
break;
}
a2/=10; //Moves to the left by one digit
a1/=10; //Moves to the left by one digit
}
System.out.print(flag!=1?"No Mid Exists":a1%10);
Your "math" is working correctly. The one thing you can: compute the length (number of digits) within your number upfront, to avoid "iterating" the number twice - so you can determine if that number of digits is even or odd without "iterating" the number:
int n = 1234;
int length = (int)(Math.log10(n)+1);
should give you 4 for 1234, and 5 for 12345.
But beyond that: you can express information in different ways. For example: you can turn an int value into a string.
String asStr = Integer.toString(123456);
And now: you can easily check the length of that string; and you can directly access the corresponding character!
The only thing to keep in mind: characters representing numbers like '1', '2', ... have different numerical values as int 1, 2, ... (see an ASCII table; as '1' is 49 when regarding its numerical value)!
this answer has less code, but wouldn't take much in performance i think:
int a1 = 12334;
int a = a1;
int middle = 0;
int noOfDigits = 0;
while (a1 != 0) {
a1 = a1 / 10;
noOfDigits++;
}
if (noOfDigits % 2 == 1) {
for (int i = 0; i < (noOfDigits / 2) + 1; i++) {
middle = a % 10;
a = a / 10;
}
System.out.println(middle);
} else {
System.out.println("No mid existing");
}
Using only math
int num = 123406789;
int countDigits = (int)Math.ceil(Math.log10(num));
int midIndex = (int)Math.ceil(countDigits/2);
int x = num / (int)Math.pow(10, midIndex);
int middleDigit = x % 10;
System.out.println(middleDigit);
I am working on a project and am stuck on what to do next. I need to write a Java program that accepts from a user ten values and place those numbers in an array. The numbers in the array will be added together and the result displayed to the user. (I got that part)
Here is the problem: The program should compare the values for elements 1 and 2 (in the array) and divide the larger number by the smaller number. It should compare the values for all odd/even elements and divide the larger by the smaller value.
I do not know how to do this at all. I started with if-else statements but I am getting errors. It know it's a mess right now, but any help with dividing the array pairs would be very helpful. Send me links too, I have been unsuccessful finding any, so I can learn more.
Thanks!
Here is what I have so far:
/import java.util.Scanner;
public class ExceptionHandler {
/**
* #param args the command line arguments10
* 10
*/
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Please enter ten values:");
System.out.println();
// Input the data from the user.
int[ ] digit = new int[11];
int sum = 0;
//Declare an array
for (int i = 1; i < digit.length; i++) {
System.out.print("Value " + i + ": ");
digit[i] = in.nextInt();
sum += digit[i];
}
System.out.println("Total Values in Array:"+ sum);
// Calculate the sum and print the total
System.out.println("Would you like to divide values?");
// Fix this later
int result= digit[i];
if (digit[i] > digit[i + 1])
result = digit[i] / digit[i + 1];
else {
(digit[i + 1] / digit[i]);
}
// Compare element 0 with 1, divide larger element by smaller element
if (digit[i])> digit[i + 3])
result = digit[i] / digit[ i+ 3];
else{
(digit[i +3])/ digit[i];
}
}
You are using int for the division. Use a double instead, as it can divide two integers with decimal point precision.
// needed for division
double[] digit = new double[11];
for (int i = 0; i < digit.length; i++)
{
digit[i] = (double)in.nextInt;
sum += (int)digit[i];
}
//you can use this variable if needed, if not, ignore it
double[] divisionResult = new double[digit.length / 2];
for(int i = 1; i < digit.length; i += 2) {
double result = digit[i];
if (result > digit[i + 1])
result = result / digit[i + 1];
else {
result = digit[i + 1] / result;
}
divisionResult[i / 2] = result;
System.out.println(result);
}
EDIT: I'm also not sure why you're using
for(int i = 1; i < 11; i++)
Because you used that, I used it similarly above, but the actual convention should be:
for(int i = 0; i < 10; i++)
Doesn't make a huge difference, but better to follow good coding conventions :)
You can just use a for loop:
for (int i = 0; i < 10; i += 2) {
if (digit[i] > digit[i + 1]) {
result = digit[i] / digit[i + 1];
}
else {
result = digit[i + 1] / digit[i];
}
System.out.println(result);
}
This should work if I got it right what you want:
for (int i = 0; i < array.length; i = i+2) {
int firstDigit = array[i];
int secondDigit = array[i+1];
if (firstDigit > secondDigit) {
return firstDigit / secondDigit;
} else {
return secondDigit / firstDigit;
}
}
You iterate over the array and compare the first with the second element. By increasing your counterVariable (i) by two you always compare the 1st / 2nd, 3rd / 4th and so on numbers of the array.
Hope this helps :)
You variable i is local to the for loop in your code. If you want to use i again, you need to declare it outside of the loop to for you to use it outside the scope of the for loop. In addition, the last value of "i" here is the last array index, which would throw on array out of bound exception anyway (in other words you need to make another loop where you initialize "i" to 0 again under your "Would you like to divide values?" statement). Lastly, you need to do an assignment, so
(digit[i + 1] / digit[i]);
is not a valid statement. If you want to write it into result, you need to write:
result = (digit[i + 1] / digit[i]);
and if you want to override in place you can use
digit[i+1] = (digit[i + 1] / digit[i]);
or
digit[i + 1] /= digit[i];
Attached is the problem: http://puu.sh/42QtI/ea955e5bef.png
In terms of code, this is what I have so far
The question asks to "calculate the simulated percentage of three tails," which is the part I am stuck on. Could someone give me some insight on what to progress next?
public static boolean isThreeTails(){
Random rand = new Random();
int numberOfTosses = 3;
int numberOfHeads = 0;
int numberOfTails = 0;
for(int i = 1; i <= numberOfTosses; i++){
int value = rand.nextInt(2);
if(value == 0){
numberOfTails++;
}else{
numberOfHeads++;
}
}
if(numberOfTails == 3){
return true;
}
else{
return false;
}
}
double numTosses = 1000000; //choose whatever here
double threeTails = 0;
for(int i =0; i < numTosses; i++){
if(isThreeTails()){
threeTails++;
}
}
System.out.println("Theoretical probability of 3 Tails: " + (double) 1/8);
System.out.println("Actual results for " + numTosses + " tosses = " + threeTails/numTosses);
EDIT: Here, I am creating a counter for when there are triple tails. It would increment the numberOfTripleTails counter. If it rolls a "H", the numberOfTails would simply go back to zero. However, my code seems to only give '3' as an answer.
EDIT 2: Done!
Alright - you've run your simulation and you have your value for number of heads and number of tails. Now you'll need to run a few more.
Each time you run a simulation, increment a variable that tracks the total amount of times you've run it. If number of tails comes out to three, you increment another variable: let's call it successes.
The outcome to the problem are the successes over the total times the simulation was run.
The method that you have already written simulates three tosses. I've modified that method so that it is now a callable function isThreeTails()
public static boolean isThreeTails(){
Random rand = new Random();
int numberOfTosses = 3;
int numberOfHeads = 0;
int numberOfTails = 0;
for(int i = 1; i <= numberOfTosses; i++){
int value = rand.nextInt(2);
if(value == 0){
numberOfTails++;
}else{
numberOfHeads++;
}
}
if(numberOfTails == 3){
return true;
}
else{
return false;
}
}
Now you will want to call this method from the main method of ThreeTosses.java
double numTosses = 100; //choose whatever here
double threeTails = 0;
for(int i =0; i < numTosses; i++){
if(isThreeTails()){
threeTails++;
}
}
System.out.println("Theoretical probability of 3 Tails: " + (double) 1/8);
System.out.println("Actual results for " + numTosses + " tosses = " + threeTails/numTosses);
The question is saying, "in theory, you should get 3 tails 1/8th of the time". Now it's saying, "OK, you know the theory, now actually do this on a computer and see what you really get."
What you want to do is run this code a bunch of times and keep track of the number of times you got 3 tails. Take that number and divide it by the total number of times you ran the code. That should be the simulated percentage.
Just in case you can't tell, I'm saying to do this in code, not by manually running your current code over and over again. Here's some pseudo code:
threeTailsCount = 0
for i = 0; i < 1000; i++
if currentCodeReturns3Tails
threeTailsCount += 1;
print (threeTailsCount / 1000)
This is a homework problem
How would I reverse an integer in Java with a for loop? The user will input the integer (I don't know how long it will be) and I need to reverse it. ie: If they enter 12345, my program returns 54321.
Here's the catch, you can't use String, StringBuffer, arrays, or other advanced structures in this problem.
I have a basic idea of what I need to do. My problem is...in the for loop, wouldn't the condition need to be x < the length of the integer (number of digits)? How would I do that without String?
Thanks for any input, and I'll add more information if requested.
EDIT:
Of course, after introspection, I realized I should use another for loop to do this. What I did was create a for loop that will count the digits by dividing by 10:
int input = scan.nextInt();
int n = input;
int a = 0;
for (int x = 0; n > 0; x++){
n = n/10;
a = a + 1;
}
EDIT 2:
This is what I have
int input = scan.nextInt();
int n = input;
int a = 0;
int r = 0;
for (int x = 0; n > 0; x++){
n = n/10;
a = a + 1;
}
for (int y = 0; y < n; y++) {
r = r + input%10;
input = input/10;
}
System.out.println(input);
When I run it, it isn't reversing it, it's only giving me back the numbers. ie: if I put in 1234, it returns 1234. This doesn't make any sense to me, because I'm adding the last digit to of the input to r, so why wouldn't it be 4321?
While your original number is nonzero, take your result, multiply it by 10, and add the remainder from dividing the original by 10.
For example, say your original number is 12345. Start with a result of 0.
Multiply result by 10 and add 5, giving you 5. (original is now 1234.)
Multiply result by 10 and add 4, giving you 54. (original is now 123.)
Multiply result by 10 and add 3, giving you 543. (original = 12.)
Multiply result blah blah 5432. (original = 1.)
Multiply, add, bam. 54321. And 1 / 10, in int math, is zero. We're done.
Your mission, should you choose to accept it, is to implement this in Java. :) (Hint: division and remainder are separate operations in Java. % is the remainder operator, and / is the division operator. Take the remainder separately, then divide the original by 10.)
You will need to use math to access each of the digits. Here's a few hints to get your started:
Use the % mod operator to extract the last digit of the number.
Use the / division operator to remove the last digit of the number.
Stop your loop when you have no more digits in the number.
This might not be the proper way but
public static int reverseMe(int i){
int output;
String ri = i + "";
char[] inputArray = ri.toCharArray();
char[] outputArray = new char[inputArray.length];
for(int m=0;m<inputArray.length;m++){
outputArray[inputArray.length-m-1]=inputArray[m];
}
String result = new String(outputArray);
output = Integer.parseInt(result);
return output;
}
public static void reverse2(int n){
int a;
for(int i = 0; i < n ; i ++){
a = n % 10;
System.out.print(a);
n = n / 10;
if( n < 10){
System.out.print(n);
n = 0;
}
}
}
here is the Answer With Correction of Your Code.
import static java.lang.Math.pow;
import java.util.*;
public class MyClass {
public static void main(String args[]) {
Scanner scan=new Scanner(System.in);
int input = scan.nextInt();
int n = input;
int a = 0;
int r = 0;
for (; n > 0;){
n = n/10;
a = a + 1;
}
for (int y = 0; y < input;a--) {
r =(int)( r + input%10*pow(10,a-1));
input = input/10;
}
System.out.println(r);
}
}