public class randomdemo {
public static void main(String[] args)
{
Random rand = new Random();
int [] varArray = new int[rand.nextInt(10)];
System.out.println(varArray.length);
int d = rand.nextInt(1999)-1000;
for (int i=0;i<varArray.length;i++)
{
varArray[i]= rand.nextInt(1999)-1000;
System.out.println(varArray[i]);
if(d==varArray[i])
{
System.out.println(d);
System.out.println(i+1);
}
else
{
System.out.println(d);
System.out.println(0);
}
}
}
}
Problems in code:
It executes the if-else statement multiple times and displays the if-else output multiple times since it is in for loop.
The code should execute the if-else statement only once but the rest of the for loop should be executed multiple times.
Since the if statement is using value of varArray[i] I cannot exclude the code from the for loop.
When break statement is used it is terminating the for loop. and the complete output is not shown.
output: currently
7
-710
-249
0
-693
-249
0
172
-249
0
-488
-249
0
-48
-249
0
955
-249
0
869
-249
0
As you can see the length of array is 7
it displays array element then value of variable d and value 0 in a loop.
expected output:
7
-710
-693
172
-488
-48
955
869
-249
0
the output of array with 7 elements should be 7 array values followed by variable d and 0.
May be you can set a boolean flag to track execution of your if else code .. see code below.
boolean flag = false; // flag to track the if else
System.out.println(varArray.length);
int d = rand.nextInt(1999)-1000;
for (int i=0;i<varArray.length;i++)
{
...
if(!flag){
if(d==varArray[i])
{
flag =true;
System.out.println(d);
System.out.println(i+1);
}
else
{
flag =true;
System.out.println(d);
System.out.println(0);
}
}
Please identify the exact scenario in which you want to execute the if-else and make changes in the existing if-else condition so that it executes only once in the loop. Or you can wrap the existing if-else inside other if-else,for which the condition can be the scenario in which you have to execute the inner if-else.
For eg: Let the scenario is like only for a particular value of i(say when i=10) you want to execute the loop.Please modify the code as below.
if(i==10){
if(d==varArray[i])
{
System.out.println(d);
System.out.println(i+1);
}
else
{
System.out.println(d);
System.out.println(0);
}
}
Try this.
public class randomdemo {
public static void main(String[] args) {
Random rand = new Random();
int[] varArray = new int[rand.nextInt(10)];
System.out.println(varArray.length);
int d = rand.nextInt(1999) - 1000;
int foundIdx = -1; // mark index if you find one!
for (int i = 0; i < varArray.length; i++) {
varArray[i] = rand.nextInt(1999) - 1000;
System.out.println(varArray[i]);
if (d == varArray[i]) {
foundIdx = i + 1; // only the last match is saved
}
}
if (foundIdx != -1) {
System.out.println(d);
System.out.println(foundIdx);
} else {
System.out.println(d);
System.out.println(0);
}
}
}
Related
Give one point to A[i] if either A[i]%A[j] ==0 or A[j]%A[i] == 0
Calculating the total points received by every element.
Input: A={2,3,4,5,6}
Output: 2,1,1,0,2
I am getting this error message: Exception in thread "main" java.lang.ArithmeticException: / by zero
at Main.main(Main.java:29)
class Main {
public static void main(String args[])
{
ArrayList<Integer> al
= new ArrayList<>();
al.add(2);
al.add(3);
al.add(4);
al.add(5);
al.add(6);
int c=al.size()-1;
while(c>=0){
int count=0;
for (int i=0; i<al.size(); i++){
if(i==c){
break;
}
else{
if(al.get(c)>al.get(i)){
if(al.get(c)%al.get(i) == 0){
count++;
}
}
else{
if(al.get(i)%al.get(c) == 0){
count++;
}
}
}
}
al.set(1,count);
--c;
}
for(int i : al){
System.out.print(i);
}
}
}
When you are running the code, this line:
al.set(1,count);
Can set count = 0. So when the value at slot 1 will be used, it will throw the error.
For "where is the error", java has pretty error informations, and it will return something like:
Exception in thread "main" java.lang.ArithmeticException: / by zero
at com.me.myprogram.MainClass.main(MainClass.java:61)
And you will see that the line 61 is:
if(al.get(c) % al.get(i) == 0){
I suggest you to check when it's 0, or to don't set 0 count like check if it's 0, and set 1, for example:
if(count != 0) {
al.set(1, count); // here the value will change only if we could use it after
} /* With this part, it will change the value but also preventing all issue with /0
else {
al.set(1, 1);
}
*/
Even though my method operationsNeeded prints the correct value for my return-int "count1", the very next line it returns something else to my main method. I did not include the rest of my code, if needed I'd gladly provide it.
For example if operationsNeeded is executed 4 times, count1 is on 4 which is printed out as well. But for reasons unknown to me the System.out.println("check: " +count1); Statement is executed 4 times like this:
check: 4
check: 4
check: 3
check: 2
I would expect my program to execute this only once and then continue to the return statement.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int testcases = sc.nextInt();
int count =0;
while (count<testcases){
int numberOfColleagues = sc.nextInt();
sc.nextLine();
String startPieces = sc.nextLine();
int[] listOfcolleagues = listOfColleagues(numberOfColleagues, startPieces);
int count2 = operationsNeeded(listOfcolleagues, 1);
count++;
System.out.println(count2);
}
}
public static int operationsNeeded (int[] listOfColleagues, int count1){
//remove duplicates first
ArrayList<Integer> relevantList=removeDuplicatesAndSort(listOfColleagues);
System.out.println("relevantlist" + relevantList);
//check for smallestdelta & index
int [] deltaAndIndex = smallestDeltaHigherIndex(relevantList);
int delta = deltaAndIndex[0];
int index = deltaAndIndex[1];
if (delta==1){
for (int i=0;i<relevantList.size();i++){
if (i!=index){
relevantList.set(i,relevantList.get(i)+1);
}
}
}
if (delta>1 && delta<5){
for (int i=0;i<relevantList.size();i++){
if (i!=index){
relevantList.set(i,relevantList.get(i)+2);
}
}
}
if (delta>4){
for (int i=0;i<relevantList.size();i++){
if (i!=index){
relevantList.set(i,relevantList.get(i)+5);
}
}
}
System.out.println(count1);
int[] updatedList = new int[relevantList.size()];
for (int i=0; i<relevantList.size();i++){
updatedList[i]=relevantList.get(i);
}
if (!isAllTheSame(relevantList)) {
count1 +=1;
operationsNeeded(updatedList,count1);
}
System.out.println("check: " + count1);
return count1;
}
Your method is recursive. The "check: " line is printed on each level of that recursion, with the value that it currently has on that level. It first prints the "inner-most" value (4), than that of the level above (also 4), and finally hte value in the top-level, which is 2 after being incremented in the if above. And the value it returns is always the value from to top-level.
If you want to print it only once, you could print it on the inner-most level only, using else. However, that will still return the value from the top-level iteration; instead, keep track of the value returned from the recirsive call and update count1 accordingly.
if (! isAllTheSame(relevantList)) {
// we have to go deeper!
count1 = operationsNeeded(updatedList, count1 + 1);
} else {
// phew, finally done
System.out.println("check: " + count1);
}
This is a homework question.
The code compiles, but in the test case, 2 is outputting as perfect, which it is not.
I cannot use an array. I cannot use Math.min() or Math.max(). Purely conditionals and loops.
My professor says I need to only test for divisors up to and including n/2 but when I do that, I still get the 2 as a perfect number.
Any help would be appreciated.
// Project2.java
import java.io.*; // BufferedReader
import java.util.*; // Scanner
public class Project2
{
public static void main (String args[]) throws Exception
{
// ALWAYS TEST FIRST TO VERIFY USER PUT REQUIRED CMD ARGS
if (args.length < 3)
{
System.out.println("\nusage: C:\\> java Project2 <input file name> <lo> <hi>\n\n");
// i.e. C:\> java Project2 P2input.txt 1 30
System.exit(0);
}
String infileName = args[0]; // i.e. L2input.txt
int lo = Integer.parseInt( args[1] ); // i.e. 1
int hi = Integer.parseInt( args[2] ); // i.e. 30
// STEP #1: OPEN THE INPUT FILE AND COMPUTE THE MIN AND MAX. NO OUTPUT STATMENTS ALLOWED
Scanner infile = new Scanner( new File(infileName) );
int min,max;
min=max=infile.nextInt(); // WE ASSUME INPUT FILE HAS AT LEAST ONE VALUE
while ( infile.hasNextInt() )
{
// YOUR CODE HERE FIND THE MIN AND MAX VALUES OF THE FILE
// USING THE LEAST POSSIBLE NUMBER OF COMPARISONS
// ASSIGN CORRECT VALUES INTO min & max INTHIS LOOP.
// MY CODE BELOW WILL FORMAT THEM TO THE SCREEN
// DO NOT WRITE ANY OUTPUT TO THE SCREEN
int number = infile.nextInt();
if ( number < min )
{
min = number;
}
else if ( number > max )
{
max = number;
}
}
System.out.format("min: %d max: %d\n",min,max); // DO NOT REMOVE OR MODIFY IN ANY WAY
// STEP #2: DO NOT MODIFY THIS BLOCK
// TEST EVERY NUMBER BETWEEN LO AND HI INCLUSIVE FOR
// BEING PRIME AND/OR BEING PERFECT
for ( int i=lo ; i<=hi ; ++i)
{
System.out.print( i );
if ( isPrime(i) ) System.out.print( " prime ");
if ( isPerfect(i) ) System.out.print( " perfect ");
System.out.println();
}
} // END MAIN
// *************** YOU FILL IN THE METHODS BELOW **********************
// RETURNs true if and only if the number passed in is perfect
static boolean isPerfect( int n )
{
int sum = 0;
for(int i = 1; i <= n/2; i ++)
{
if(n%i == 0)
{
sum += i;
}
}
if (sum == n)
{
return true;
}
else
{
return false;
}
// (just to make it compile) YOU CHANGE AS NEEDED
}
// RETURNs true if and only if the number passed in is prime
static boolean isPrime( int n )
{
if (n < 3)
{
return false;
}
for(int i = 2; i <= n/2; i++)
{
if(n%i == 0)
{
return false;
}
}
return true;
}// (just to make it compile) YOU CHANGE AS NEEDED
}
OK, I found a bug, although it's not quite the bug you described.
static boolean isPrime( int n )
{
if (n < 3)
{
return false;
}
This will incorrectly list 2 as not prime, because it's less than 3.
I just discovered the project euler website, I have done challenges 1 and 2 and have just started number 3 in java... here is my code so far:
import java.util.ArrayList;
public class IntegerFactorise {
private static int value = 13195;
private static ArrayList<Integer> primeFactors = new ArrayList<Integer>();
private static int maxPrime = 0;
/**
* Check whether a give number is prime or not
* return boolean
*/
public static boolean isPrimeNumber(double num) {
for(int i = 2; i < num; i++) {
if(num % i == 0) {
return false;
}
}
return true;
}
/*Multiply all of the prime factors in the list of prime factors*/
public static int multiplyPrimeFactors() {
int ans = 1;
for(Integer i : primeFactors) {
ans *= i;
}
return ans;
}
/*Find the maximum prime number in the list of prime numbers*/
public static void findMaxPrime() {
int max = 0;
for(Integer i : primeFactors) {
if(i > max) {
max = i;
}
}
maxPrime = max;;
}
/**
* Find all of the prime factors for a number given the first
* prime factor
*/
public static boolean findPrimeFactors(int num) {
for(int i = 2; i <= num; i++) {
if(isPrimeNumber(i) && num % i == 0 && i == num) {
//could not possibly go further
primeFactors.add(num);
break;
}
else if(isPrimeNumber(i) && num % i == 0) {
primeFactors.add(i);
findPrimeFactors(num / i);
}
}
int sumOfPrimes = multiplyPrimeFactors();
if(sumOfPrimes == value) {
return true;
}
else {
return false;
}
}
/*start here*/
public static void main(String[] args) {
boolean found = false;
for(int i = 2; i < value; i++) {
if(isPrimeNumber(i) && value % i == 0) {
primeFactors.add(i);
found = findPrimeFactors(value / i);
if(found == true) {
findMaxPrime();
System.out.println(maxPrime);
break;
}
}
}
}
}
I am not using the large number they ask me to use yet, I am testing my code with some smaller numbers, with 13195 (their example) i get down to 29 in this bit of my code:
else if(isPrimeNumber(i) && num % i == 0) {
primeFactors.add(i);
findPrimeFactors(num / i);
}
}
int sumOfPrimes = multiplyPrimeFactors();
if(sumOfPrimes == value) {
return true;
}
It gets to the break statement then finally the check and then the return statement.
I am expecting the program to go back to the main method after my return statement, but it jumps up to:
findPrimeFactors(num / i);
and tries to finish the iteration...I guess my understanding is a flawed here, could someone explain to me why it is behaving like this? I can't wait to finish it of :) I'll find a more efficient way of doing it after I know I can get this inefficient one working.
You are using recursion, which means that a function will call itself.
So, if we trace what your function calls are when you call return, we will have something like that:
IntegerFactorise.main()
|-> IntegerFactorise.findPrimeFactors(2639)
|-> IntegerFactorise.findPrimeFactors(377)
|-> IntegerFactorise.findPrimeFactors(29) -> return true;
So, when you return in the last findPrimeFactors(), you will only return from this call, not from all the stack of calls, and the execution of the previous findPrimeFactors() will continue just after the point where you called findPrimeFactors().
If you want to return from all the stack of calls, you have to modify your code to do something like that:
else if(isPrimeNumber(i) && num % i == 0) {
primeFactors.add(i);
return findPrimeFactors(num / i);
}
So that when the last findPrimeFactors() returns, all the previous findPrimeFactors() which called it will return too.
I think the problem is that you are ignoring the return value from your recursive call to findPrimeFactors().
Let's walk through this. We start with the initial call to findPrimeFactors that happens in main. We then enter the for loop as it's the first thing in that method. Now let's say at some point we get into the else statement and thus recursively call frindPrimeFactors(num / i). This will suspend the looping, but as this recursive call starts to run you enter the for loop again (remember, the previous loop is merely paused and not finished looping yet). This time around you encounter the break, which allows this recursive call to finish out, returning true of false. When that happens you are now back to the original loop. At this point the original loop continues even if the recursive call returned true. So, you might try something like this:
if (findPrimeFactors(num / i))
return true;
I'm assuming that you need to continue looping if the recursive call returned false. If you should always finish looping upon return (whether true or false) then try this:
return findPrimeFactors(num / i);
I am working on an algorithm, and I need to be able to pass in a List and see if there are four numbers in a row at any point in the list.
I have been struggling with an easy way to do this... Here is the basic idea.. I would like the fourNumbersInARow() method to return true:
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class Numbers {
/**
* #param args
*/
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<Integer>();
for(int i = 0; i<10; i++){
numbers.add((new Random().nextInt()));
}
numbers.add(1);
numbers.add(2);
numbers.add(3);
numbers.add(4);
System.out.println(fourNumbersInARow());
}
private static boolean fourNumbersInARow() {
}
}
Use two variables: last_value and row_count. Going through the list one by one, always look whether the current value is exactly one bigger than the last_value; if yes, increase row_count, if no, reset it to 1. In any case, set last_value to the current value and loop. If at any point row_count becomes 4, return true. If you reach the end of the list, return false.
EDIT: changed counter range to start at 1
Here's an implementation in Java.
static boolean fourNumbersInARow(List<Integer> list) {
int last = 0xFACADE; // can be any number
int count = 0; // important!
for (int i : list) {
if (i == last + 1) {
if (++count == 4) return true;
} else {
count = 1;
}
last = i;
}
return false;
}
Unlike others, this resets the count of numbers in a row to 1 when the sequence is broken (because a number on its own is 1 number in a row). This allows for easier treatment of the first iteration where technically there is no previous number.
In pseudocode:
consecutiveCount = 1
lastNumber = firstElementInList(list)
for (number in list.fromSecondElement()):
if (number - lastNumber == 1):
consecutiveCount++
else:
consecutiveCount = 1
if (consecutiveCount == 4):
return true
lastNumber = number
return false
The bottom line is, you'll want to keep track of the last number in that was in the list, and compare it with the current number to see if the difference is 1. In order to remember the last number, a variable such as lastNumber is needed.
Then, in order to keep track of how many consecutive numbers there have been there should be a counter for that as well, which in the example about is the consecutiveCount.
When the condition where four consecutive numbers have occurred, then the method should return true.
This sounds a little like a homework question, so I don't want to write out a complete solution. But in your method just iterate through the list. Take the first number and see if the next number comes after the current, if so then set a variable flag with the start position and the current number, on the next iteration through the loop check to see if that value is before the previous the value etc... Once four in a row are found, break out of the loop and return true. If you encounter a number that is no chronologically correct then set a flag(start location) to null or negative and start the process over from the current location in the list.
Check this Code, this will return true if there a sequence of 4 numbers and else false otherwise
public class FindFourSequence {
public boolean isFourinRow(ArrayList seqList) {
boolean flag = false;
int tempValue = 0;
int tempValue2 = 0;
int tempValue3 = 0;
int tempValue4 = 0;
Iterator iter = seqList.iterator();
while(iter.hasNext()){
String s1 = (String)iter.next();
tempValue=Integer.valueOf(s1).intValue();
if(!(iter.hasNext())){
break;
}
String s2 = (String)iter.next();
tempValue2=Integer.valueOf(s2).intValue();
if(((tempValue2-tempValue)==1) || (tempValue-tempValue2)==1){
if(!(iter.hasNext())){
break;
}
String s3 = (String)iter.next();
tempValue3=Integer.valueOf(s3).intValue();
if((tempValue3-tempValue2)==1 || (tempValue2-tempValue3)==1){
if(!(iter.hasNext())){
break;
}
String s4 = (String)iter.next();
tempValue4=Integer.valueOf(s4).intValue();
if((tempValue3-tempValue4==1) || (tempValue4-tempValue3)==1){
flag = true;
return flag;
}
}
}
}
return flag;
}
public static void main(String[] args) throws Exception {
ArrayList aList = new ArrayList();
boolean flag = false;
FindFourSequence example = new FindFourSequence();
Random random = new Random();
for (int k = 0; k < 25; k++) {
int number = random.nextInt(20);
System.out.println(" the Number is :" + number);
aList.add("" + number);
}
/* aList.add("" + 1);
aList.add("" + 2);
aList.add("" + 3);
aList.add("" + 4);*/
flag = example.isFourinRow(aList);
System.out.println(" the result value is : " + flag);
}
}