I have to get input for a certain number of days and a starting number. With that, the number of days gets split in half, in first half starting number decremented by 2. Last half incremented by 1. If days is uneven, last half has one more day. Heres what I have:
int days;
int num;
int 1half;
int 2half;
int new_num;
System.out.print("Enter number of days: ");
days = keyboard.nextInt();
System.out.print("Enter number of first day: ");
num = keyboard.nextInt();
int half = days/2;
if (days %2 == 0){
1half = (half);
2half = (half);
} else {
1half = (half);
2half = (half) + 1;
}
int first_half[] = {1,(half)};
int last_half[] = {((half)+1), days};
while (1half > 1 || 1half < half) {
new_temp = temp - 2;
System.out.println("Day \t Num");
System.out.println(new_num);
first_half--;
}
while(2half >= (half + 1) && (2half <= days)) {
new_temp = temp++;
System.out.println("Day \t Num");
System.out.println(new_num);
last_half--;
}
Im stuck now though.
If you see anything Id be happy to hear about it. I just need some help/advice. I'll clarify anything if this is hard to understand. Thank you in advance
Edit:
The final output should look something like this:
Day Num
1 -10
2 -12
3 -14
4 -16
5 -18
6 -17
7 -16
8 -15
9 -14
10 -13
11 -12
If this makes sense.
Heres my output:
Day Temperature
8
Day Temperature
8
Day Temperature
8
Day Temperature
continues forever
I don't know why do you need those arrays and other stuff, but you may have a look at my code. It produces exactly what you want.
int days = 11;
int num = -10;
int output = num + 2;
System.out.println("Day \t Num");
int half = days / 2;
for (int i = 1; i <= half; i++) {
output -= 2;
System.out.println(i + "\t" + output);
}
for (int i = half + 1; i <= days; i++) {
output++;
System.out.println(i + "\t" + output);
}
Your endless loop is caused by your condition statement of your while:
while (1half > 1 || 1half < half).
If 1half is set to be any number greater than 1 then this will loop forever. You probably want to use an && instead of an || as well. But don't see anything in the body of the loop that would affect things to make it get out of the loop.
Related
I have numbers as x,y,z, and w.
I am trying to create max possible time in 24 hours format.
Example:
My approach is to sort the all numbers. Then for hours check the number less than equal 2, then for next digit in hour, check number less then equal to 4,
and so on for minutes also. (0-60 minutes)
Is any other efficient approach than bruteforce solution?
Simple approach would be to create all possible combinations of all the number from four digits. Then sort and pick out all the values less than 2359 (Max time allowed). After this you start with the max number and just validate if it is a correct time if not check the next biggest number.
Basically what you can do is instead of all permutations you create conditions for each value in the array. For example if we have a 2 we know the hour should be 2 for our ten spot but our ones spot for the hour can only be 3 at that point. If we have a 1 then we know our one spot for the hour can be 9. We know our minute ten spot is 5 and our max minute one spot is 9. createTime shows these conditions. The findMaxSpecific returns -1 if it isn't able to find a valid number in the given array. That way we know the time is invalid if we ever get an array returned by createTime with -1's in it. See example output.
public static int[] createTime(int[] numbers)
{
int[] time = new int[4];
time[0] = findMaxSpecific(numbers, 2);
time[1] = time[0] == 2 ? findMaxSpecific(numbers, 3) : findMaxSpecific(numbers, 9);
time[2] = findMaxSpecific(numbers, 5);
time[3] = findMaxSpecific(numbers, 9);
return time;
}
public static int findMaxSpecific(int[] arr, int valToFind)
{
if(arr.length != 4)
return -1;
int numToFind = -1;
int indexToRemove = -1;
for(int i = 0; i < arr.length; i++)
{
if(arr[i] <= valToFind)
{
if(arr[i] > numToFind)
{
numToFind = arr[i];
indexToRemove = i;
}
}
}
if(indexToRemove == -1)
return -1;
arr[indexToRemove] = -1;
return numToFind;
}
At the end of all this is if any value comes back as -1 we know we have an invalid time we were given
Example
int[] time = new int[4];
int[] numbers = {1,2,3,4};
time = createTime(numbers);
System.out.println(time[0] + "" + time[1] + ":" + time[2] + "" + time[3]);
int[] numbers2 = {0,9,7,1};
time = new int[4];
time = createTime(numbers2);
System.out.println(time[0] + "" + time[1] + ":" + time[2] + "" + time[3]);
int[] numbers3 = {9,9,9,9};
time = new int[4];
time = createTime(numbers3);
System.out.println(time[0] + "" + time[1] + ":" + time[2] + "" + time[3]);
Output is
23:41
19:07
-19:-19 //invalid numbers
For input 1 2 9 9, the only possibility is 19:29, but what you describe picks the two first and gets 21:99, an invalid time.
Unless this is indeed a bottleneck and not a programming exercise, the most straightforward solution is to try all possible permutations of the digits, for each one, check whether it constitutes a valid time, and take the lexicographically maximal valid string.
The point is, there are fast solutions and there are correct solutions.
Here, the fast solution is tricky, so if program running time is not critical, do consider the possibility to pick the slower but more obvious solution.
This will perhaps give you, as a programmer, more time to tackle the other problems where running time does matter.
Sadly, Java does not seem to provide a builtin nextPermutation method, but Stackoverflow sure does.
input = (1,2,3,4)
ans = None
for hour in range(0, 24):
for minute in range(0,60):
if possible(hour, minute, input):
ans = "%s:%s" % (hour, minute)
here your possible function should count the digits in hour, minute and input and make sure they equate.
I would have a method you can give a predicate which extract the highest value which matches the predicate.
e.g.
public static int highest(List<Integer> values, Predicate<Integer> test) {
Integer max = values.stream()
.filter(test)
.max(Comparator.natrualOrder())
.orElseThrow(() -> new InvalidStateException());
values.remove(max);
return max;
}
int digit1 = highest(list, i -> i < 3);
int digit3 = highest(list, i -> i < 6);
int digit2 = highest(list, i -> digit1 < 2 || i < 4);
int digit4 = highest(list, i -> true);
Interesting problem. Seems a little bit more complex than it appears. Here is a python script for the problem.
def getmin(num): # check if two digits are valid for minutes
min = -1
sum = num[0] * 10 + num[1]
if sum < 60:
min = sum
sum = num[1] * 10 + num[0]
if sum < 60 and min < sum:
min = sum
return min
def maxtime(num):
hour = -1
min = -1
h1 = 0
h2 = 0
for i in range(4):
for j in range(4): # these two loops are to get maxi hour, if possible
if i != j:
sum = num[i] * 10 + num[j]
if hour < sum and sum < 24:
c = num[:] # get a copy of input digits
if i > j: # delete numbers used in hour
del c[i]
del c[j]
else:
del c[j]
del c[i]
if getmin(c) > -1:
h1 = i
h2 = j
hour = sum
if hour > -1:
if h2 > h1: # delete numbers used in hour
del num[h2]
del num[h1]
else:
del num[h1]
del num[h2]
min = getmin(num)
if min > -1:
print(str(hour) + ':' + str(min))
if hour < 0 or min < 0:
print("no solution")
maxtime([4, 8, 1, 9])
maxtime([7, 3, 4, 2])
maxtime([9, 2, 2, 5])
maxtime([9, 2, 7, 3])
#19:48
#23:47
#22:59
#no solution
Beginner here. So I want to write a program that prints out all the prime numbers up to the number the user entered. E.g., user enters 5, program prints out 2 and 3. That part I understand, however what I am struggling with, is what if I want the program to print out whether the number the user entered is a prime or not (simple yes or no) IF the entered number is bigger than, let's say, 50. Here is code for first part:
public class Primes {
public static void main(String args[]) {
System.out.println("All primes up to: ");
int num = new Scanner(System.in).nextInt();
System.out.println("Prime numbers from 1 to " + num + " are: ");
for(int number = 2; number<=num; number++){
if(isPrime(number)){
System.out.println(number);
}
}
}
public static boolean isPrime(int number){
for(int i=2; i<number; i++){
if(number%i == 0){
return false;
}
}
return true;
}
}
I honestly can't wrap my around as to what I should be doing next. My first program ever ("Hello world" does not count ;P).
Edit :
Your current code seems to work fine.
As per your doubt as mentioned in one of the comments : Yes, but where do I add if statement that does the following: if the number entered is below 50, then the program prints out all the prime numbers up to the entered number. If the number the user entered is bigger than 50, it tells only whether the entered number is prime or not ( simply "It's a prime" or "No, it's not a prime"). Hope that made things clearer
The check you need to put is after you take the input :
int num = new Scanner(System.in).nextInt();
if( number > 50 )
{
if(isPrime(number))
{
// print out is prime
}
// print out it is not prime
}
else
{
System.out.println("Prime numbers from 1 to " + num + " are: ");
for(int number = 2; number<=num; number++){
if(isPrime(number)){
System.out.println(number);
}
}
}
SUGESTIONS :
However, just to touch upon the algorithmic part, I would recommend using Sieve of Eratosthenes for picking out all the prime numbers within a given range, as you need in your case.
Example :
To find all the prime numbers less than or equal to 30, proceed as follows:
First generate a list of integers from 2 to 30:
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
Strike (sift out) the multiples of 2 resulting in:
2 3 5 7 9 11 13 15 17 19 21 23 25 27 29
The first number in the list after 2 is 3; strike the multiples of 3 from the list to get:
2 3 5 7 11 13 17 19 23 25 29
The first number in the list after 3 is 5; strike the remaining multiples of 5 from the list:
2 3 5 7 11 13 17 19 23 29
The first number in the list after 5 is 7, but 7 squared is 49 which is greater than 30 so the process is finished. The final list consists of all the prime numbers less than or equal to 30.
Here's the code attached for reference ( Disclaimer : I'm picking up this code here from this site. Just pasted it here for more immediate visibility).
Code :
public class PrimeSieve {
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
// initially assume all integers are prime
boolean[] isPrime = new boolean[N + 1];
for (int i = 2; i <= N; i++) {
isPrime[i] = true;
}
// mark non-primes <= N using Sieve of Eratosthenes
for (int i = 2; i*i <= N; i++) {
// if i is prime, then mark multiples of i as nonprime
// suffices to consider mutiples i, i+1, ..., N/i
if (isPrime[i]) {
for (int j = i; i*j <= N; j++) {
isPrime[i*j] = false;
}
}
}
// count primes
int primes = 0;
for (int i = 2; i <= N; i++) {
if (isPrime[i]) primes++;
}
System.out.println("The number of primes <= " + N + " is " + primes);
}
}
Try this..
int j = 2; //variable
int result = 0; //variable
int number = 0; //variable
Scanner reader = new Scanner(System.in); //Scanner object
System.out.println("Please enter a number: "); //Instruction
number = reader.nextInt(); //Get the number entered
while (j <= number / 2) //start loop, during loop j will become each number between 2 and
{ //the entered number divided by 2
if (number % j == 0) //If their is no remainder from your number divided by j...
{
result = 1; //Then result is set to 1 as the number divides equally by another number, hergo
} //it is not a prime number
j++; //Increment j to the next number to test against the number you entered
}
if (result == 1) //check the result from the loop
{
System.out.println("Number: " + number + " is Not Prime."); //If result 1 then a prime
}
else
{
System.out.println("Number: " + number + " is Prime. "); //If result is not 1 it's not a prime
}
this is more efficient way tough:-
public boolean isPrime(int n) {
// fast even test.
if(n > 2 && (n & 1) == 0)
return false;
// only odd factors need to be tested up to n^0.5
for(int i = 3; i * i <= n; i += 2)
if (n % i == 0)
return false;
return true;
}
however what I am struggling with, is what if I want the program to print out whether the number the user entered is a prime or not (simple yes or no).
Your current isPrime function seems to work, so just ask for a number and test it.
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextInt()) {
System.out.println("Enter a number (is it prime): ");
int num = scanner.nextInt();
if (isPrime(num)) {
System.out.printf("%d yes%n", num);
} else {
System.out.printf("%d no%n", num);
}
}
Or with a ternary,
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextInt()) {
System.out.println("Enter a number (is it prime): ");
int num = scanner.nextInt();
System.out.printf("%d %s%n", num, isPrime(num) ? "yes" : "no");
}
Edit Based on your comment, move your print up sequence to a method
public static void primesUpTo(int num) {
System.out.println("Prime numbers from 1 to " + num + " are: ");
for (int number = 2; number <= num; number++) {
if (isPrime(number)) {
System.out.println(number);
}
}
}
Then
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextInt()) {
System.out.println("Enter a number (is it prime): ");
int num = scanner.nextInt();
if (num > 50) {
System.out.printf("%d %s%n", num, isPrime(num) ? "yes" : "no");
} else {
primesUpTo(num); // <-- call the method above.
}
}
If i understand the question right:
If user enteres number lesser than or equal to 50, then print all primes that are lesser than that number.
Otherwise, just write if inputted number is a prime.
With already existing isPrime() method:
int num = new Scanner(System.in).nextInt();
if (num <= 50) {
System.out.println("Prime numbers from 1 to " + num + " are: ");
for (int number = 2; number <= num; number++) {
if (isPrime(number)) {
System.out.println(number);
}
}
} else { //num > 50
if(isPrime(num)) {
System.out.println(num + " is prime.");
} else {
System.out.println(num + " isn't prime.");
}
}
I want this while loop to print every multiple of two below the number submitted(ex. if 100 was submitted it would print 2 4 8 16 32 64). Here's what I have(I'm only going to include a portion of the class because there was other things in it that don't pertain to this part)
i = 1;
Scanner myScanner = new Scanner(System.in);
System.out.print("Would thoughst be inclined to enter a number fair sir/madam: ");
String answer = myScanner.nextLine();
int number = Integer.parseInt(answer);
System.out.print("Your number set is: ");
while(i <= number)
{
i = 2*i;
System.out.print(" " + i + " ");
}
What this prints if I enter 100 is: 2 4 8 16 32 64 128
How do I get rid of that last number?
You would get rid of that number by modifying your logic to match. Your code is doing precisely what it says. One option is to start at 2, and increase i at the end of the loop instead of just before printing it. You could also use a for loop:
for (int i = 2; i < 100; i *= 2)
...
If you want to save the last power, you have a few options, e.g.:
int k = 2;
for (int i = k; i < 100; i *= 2) {
k = i;
...
}
Or undo the last operation:
int i;
for (i = 2; i < 100; i *= 2)
...;
i /= 2;
Or check the next one:
int i;
for (i = 2; i * 2 < 100; i *= 2)
...;
Checking the next one, in your original form:
while (i * 2 <= number)
...;
Etc.
By the way, your title says "factors", your description says "multiples", and your code says "powers"...
In your code
while(i <= number)
{
i = 2*i;
System.out.print(" " + i + " ");
}
the problem is that i, when it is equal to 64, is indeed less than 100, so the loop continues.
If you change it to
i = 2*i;
while(i <= number)
{
System.out.print(" " + i + " ");
i = 2*i;
}
it does as you wish, because it pre-computes the value before being analyzed as the while-loop terminator.
Try
while( i <= number / 2)
Those are powers of 2, not factors of 2.
"thoughst" is not a word. It should be "thou".
Update the value of i after you print it.
So my for loop causes a crash and I know exactly why, but I'm unsure of a way to rewrite this to get it to do what I'm trying to accomplish.
I'm trying to get it to take out money from a compounding interest each day and total it up for the month (which is set for ever 30 days). The user inputs the number of days they are trying to calculate for. So what is causing the crash is if they put in anything other than something divisible by 30.
I'm having difficulty coming up with a way to rewrite this and could use any suggestions. I would like it to do something if they put in 65 it calculates 2 months worth and then display like insuficiant days for month 3. Any help is always greatly appreciated. Thanks in advance.
for (int i = 0; i < numDays; i+=30){
double cash=0;
for (int n=1; n < 30; n++){
int currentDay;
currentDay= n+i;
cash=cash+dailyMoney[currentDay];
}
month++;
if(monthlyChecks == null)
monthlyChecks = "\nCheck on month "+month+": $"+df.format(cash)+"\n";
else
monthlyChecks = monthlyChecks+"\nCheck on month "+month+": $"+df.format(cash)+"\n";
}
numDays is the user inputted number of days....
monthlyChecks is a String....
dailyMoney[] is the array that holds the amount for each day.
Okay, sounds to me like what you are trying to do with your "insufficient days for month 3" is this: (Assuming numDays is an int)
numMonths = numDays / 30 //If numDays is an int, this will round down.
extraDays = numDays % 30
for (int i = 0; i < numMonths; i+=30){
double cash=0;
for (int n=1; n < 30; n++){
int currentDay;
currentDay= n+i;
cash=cash+dailyMoney[currentDay];
}
month++;
if(monthlyChecks == null)
monthlyChecks = "\nCheck on month "+month+": $"+df.format(cash)+"\n";
else
monthlyChecks = monthlyChecks+"\nCheck on month "+month+": $"+df.format(cash)+"\n";
}
}
//Then at some point
Systme.out.println("Insuffiecent days for " + numMonth + 1 " months. " + 30 - extraDays " days short).")
Given that user is required to enter days, maybe something like
int numMonths = numDays / 30;
int remainder = numDays % 30;
System.out.println ("Calculating for " + numMonths + " months");
if ( remainder != 0 ) {
numDays -= remainder;
System.err.println ("Insufficient days for month " + (numMonths + 1));
}
This should all be placed before the rest of your code, including (and especially) before the dailyMoney = new double[numDays] part.
Why doesn't this for loop count the right number of times? If I set the variable runs to 3, the loops runs 4 times. (One extra case.)
Thanks in advance!
for (int i = runs; i >= 0; i--)
{
System.out.println("Input Duration of Trip");
Scanner timeCalc = new Scanner(System.in);
System.out.print("Hours ==> ");
int hour = timeCalc.nextInt();
System.out.print("Minutes ==> ");
int minute = timeCalc.nextInt();
System.out.println("You entered: " + hour + " hour(s) and " + minute + " minutes");
System.out.println();
time = convertHoursMinutesToDouble(hour, minute);
totalTime += time;
}
The loop runs for values:
3
2
1
0
That's 4 times.
If you want it to run for values 3, 2 and 1, you can change your for loop to:
for (int i = runs; i > 0; i--)
or
for (int i = runs; i >= 1; i--)
Your mistake is in
i>=0
What the code is doing is going "Ok, i is going to be equal to three. Now, let's see, ok, back up again, subtract one, i =2... subtract one i=1... Now tricky tricky it SKIPS the termination part of the code because it looks at it first BEFORE substracting one so i=0, ok WAIT i=0 so STOP."
Solution?
for (int i = runs; **i >= 1**; i--)
This mistake always messes me up.
Hope the whole "through the mind of the computer thing" doesn't bother you. That's how I tend to think.
Happy coding!
i == 3
i >= 0
println
i--
i == 2
i >= 0
println
i--
i == 1
i >= 0
println
i--
i == 0
i >= 0
println
That was 4 times. You need your condition to be: i > 0
Because you have set greater than or equal to...
So starts at 3 and goes, 2,1,0.