Java Programming Challenge Code Not Working [closed] - java

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 9 years ago.
Improve this question
I have been given a challenge to do witH Java and one of the questions I keep getting the wrong answer the question is:
What is the sum of all of the palindromic numbers that are the products of two 2-digit or 1-digit numbers?
Edit:
So I basically need code that will work out the sum of all palindromes who can be made from 2 numbers either 2-digit or 1-digit.
package projects;
import java.util.ArrayList;
public class Project3 {
public static void main(String[] args) {
new Project3();
}
public Project3(){
ArrayList<Integer> numbers = new ArrayList<Integer>();
//generate 1-9
for(int i = 1; i < 10; i++){
numbers.add(i);
}
//generate 11-99
for(int i = 10; i < 100; i+=10){
numbers.add(i + (i / 10));
}
//generate 100-999
for(int i = 100; i < 1000; i+=100){
for(int j = 1; j < 10; j++){
numbers.add(i + (j*10) + (i / 100));
}
}
//generate 1000 - 9999
for(int i = 1000; i < 10000; i+=1000){
for(int j = 1; j < 10; j++){
numbers.add(i + (j * 100) + (j * 10) + (i / 1000));
}
}
boolean product = false;
for(int i = 0; i < numbers.size(); i++){
product = false;
for(int j = 99; j >= 1; j--){
if(numbers.get(i).intValue() % j == 0){
product = true;
break;
}
}
if(product == false){
numbers.remove(i);
}
}
int total = 0;
for(int i = 0; i < numbers.size(); i++){
total += numbers.get(i);
System.out.println(numbers.get(i) + "\t\t" + total);
}
System.out.println(total);
}
public String reverse(String thing){
String reversed = "";
char[] array = thing.toCharArray();
for(int x = thing.length() - 1; x >= 0; x--){
reversed += array[x];
}
return reversed;
}
}
Edit:
I am trying to ask what/where my program is going wrong and what I could do to get a program that will give me th right answer.

Your logic goes wrong when you are checking for divisibility in the following loop:
for(int j = 99; j >= 1; j--){
if(numbers.get(i).intValue() % j == 0){
product = true;
break;
}
Here you are just checking if the palindrome is divisible by a number between 1-99 but you are not worried about the other factor of the palindrome.
Example:
Let the palindrome be 2222.
When checking for its divisibility (inside 'j' loop), it is divisible by 22 and hence you are including it in the list, where as the other factor is 101 which is not a 2-digit/1-digit number.
You have to eliminate all such cases.
So instead of following this algorithm, it is better if you follow the algorithm in a reverse way as mentioned by few users above.

You try to create all the palindromic numbers and then check whether they are a product of some numbers. Instead, try it the other way around. You already have a reverse function, so just do this:
int counter = 0;
for (int i = 0; i < 100; i++) {
for (int k = i; k < 100; k++) {
String s = String.valueOf(i * k);
if (s.equals(reverse(s))) counter++;
}
}

Just one potential problem:
for(int i = 0; i < numbers.size(); i++){
...
if(product == false){
numbers.remove(i);
}
}
This might skip numbers. Consider the list N,P,* (where N is a non-product palidrome, P is a product palindrome and * is any palindrome). i is 0 and since N is a non-product palidrome it will be removed and your list now is P,*. Now i will be increased to 1 and thus the i-th element is *. P will be skipped - ouch.
To fix that, you might collect the palindromes into another set/list/collection and leave numbers unchanged.
Alternatively iterate backwards, i.e. for( i = numbers.size(); i >= 0; i--).
A thirds option would be to use an iterator, e.g. for( Iterator<Integer> itr = numbers.iterator(); itr.hasNext(); ) { ... } and then itr.next() and itr.remove().
Btw, you might want to use for a foreach loop whenever the value of i is not relevant, e.g. for(Integer number : numbers )
Edit: changed the example from 10,11,12 to 65,66,67 to reduce confusion. Please note that it's still an example and not necessarily based on your actual data.
Edit 2: I changed the example to something more abstract to avoid (or generate? ;) ) further confusion. Since I can't currently think of a sequence of a non-product palindrome followed by a product palindrome (product here means matching the requirement of being a product of 2 one- or two-digit numbers), I changed it to N,P,*.
I'll restate the point of my potential bug answer: when you iterate forward using indices and remove elements at the current or a lower index, you would skip elements, so don't do that unless you want that exact behavior.

Related

Find minimum sum from given array

I have an array of numbers [3,4,5,1,2,3,1] find 3 pairs sub sequence say sub[] such that sub[0] < sub[1] > sub[2], sum those 3 elements and get the minimum sum.
Example:
For [3,4,5,1,2,3,1], I can select [1,2,1] here 1<2>1 so sum is 1+2+1 = 4 which is minimum.
Constraints:
array size upto 1,00,000
each element size is 1 to 1,00,00,00,000
My approach is using 3 nested for loops and getting the minimum sum which is not an efficient way.
public long process(List<Integer> list) {
int n = list.size();
long output = Long.MAX_VALUE;
for(int i=0; i<n; i++) {
for(int j=i+1; j<n; j++) {
if(list.get(i) < list.get(j)) {
for(int k=j+1; k<n; k++) {
if(list.get(j) > list.get(k)) {
output = Math.min(output, list.get(i)+list.get(j)+list.get(k));
}
}
}
}
}
return output;
}
How do solve this program efficiently with less time complexity?
Let me provide a solution whose time complexity is O(n) and space complexity is O(n). You have to iterate through the array thrice and also store two arrays for the minimum elements. I was inspired by the comment made by #Someone. Please keep in mind that this solution makes the assumption that for any sub[i] < sub[j] > sub[k] this must hold: i < j < k.
Solution can be modified easily to cover the cases where i <= j <= k. If it's not compulsory for this equation to hold, then question becomes more trivial. Just find first three minimum element and we know that sub[i] < sub[j] > sub[k] holds. Make sure that the third one (largest one) is different than the others. Although you didn't specify the rule I mentioned above, I believe question wants you to comply with that rule - otherwise that would be very trivial.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Stackoverflow {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<>(Arrays.asList(3,4,5,1,2,3,1));
System.out.println(process(numbers));
}
public static long process(List<Integer> list) {
if(list.size() < 3) return -1; // not enough elements
int n = list.size();
int[] minLeft = new int[n];
int[] minRight = new int[n];
minLeft[0] = list.get(0);
minRight[minRight.length - 1] = list.get(list.size() - 1);
// store the minimum elements from left up to current index
for(int i=1; i<n; i++) {
minLeft[i] = Math.min(list.get(i), minLeft[i - 1]);
}
// store the maximum elements from right up to current index
for(int i=n - 2; i>=0; i--) {
minRight[i] = Math.min(list.get(i), minRight[i+1]);
}
long sum = Integer.MAX_VALUE;
for(int i=1; i<n-1; i++) {
sum = Math.min(sum, minLeft[i - 1] + list.get(i) + minRight[i + 1]);
}
return sum;
}
}
Output:
4

How do I get a unique number in array [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 1 year ago.
Improve this question
number = {5,3,5,5,5,6,6,9,3,3};
How do I get a unique number which is not duplicated in array?
What I want to get
9
My code is below
int[] list = {5,3,5,5,5,6,6,9,3,3};
Arrays.sort(list);
for(int i = 0; i < list.length; i++){
for(int j = i+1; j < list.length; j++){
if(list[i] == list[j]){
break;
}
}
}
This is a brute force approach but can solve you problem.
public static int GetUnique(int val){
int count = 0;
int[] list = {5,3,5,5,5,6,6,9,3,3};
for(int i = 0; i < list.length; i++){
for(int j = i+1; j < list.length; j++){
if(list[i] == list[j]){
count++;
}
}
if(count == 1)
return list[i];
count = 0;
}
return 0
}
Efficient way of finding non repeating elements from given array would be by using hash tables:
Construct a hash table consisting of element and it's occurrence count by traversing the given array
Map<Integer, Integer> hashTable = new HashMap<>();
for(int i = 0; i < list.length; i++) {
if(hashTable.containsKey(list[i])) {
hashTable.put(list[i], hashTable.get(list[i]) + 1);
} else {
hashTable.put(list[i], 1);
}
}
Once the hash table is ready, then any desired operations on it can be performed. For example: If first non repeating number is to be found, then a simple iteration on the given list would suffice:
for(int i = 0; i < list.length; i++) {
if(hashTable.get(list[i]) == 1) {
System.out.println(list[i]);
break;
}
}
Time complexity of this approach is O(n)
You can also use Java Stream API:
Integer[] list = {5,3,5,5,5,6,6,9,3,3,13};
Map<Integer, Long> counts = Arrays.stream(list)
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
int[] uniqueValues = counts.entrySet().stream().filter(e -> e.getValue().equals(1L)).mapToInt(Map.Entry::getKey).toArray();
Output:
[9, 13]
This is what happened:
First, numbers have been grouped by occurrences in format: number: occurrences of number:
3: 3 occurrences
5: 4 occurrences
6: 2 occurrences
9: 1 occurrence
13: 1 occurrence
In next step we filter above groups by leaving only numbers with 1 occurrence and mapping result into final array
If list[i-1] != list[i] and list[i]!=list[i+1] Then, it's necessary to manage start and end of the array, otherwise arrayIndexOutOfBoundsException raise.
int[] list = {3,3,5,6,6,9,9,15};
Arrays.sort(list);
for(int i = 0; i <list.length; i++){
if( (i==0 && (list[i]!=list[i+1])) || ((i>0) && (list[i]!=list[i-1]) && (( i==list.length-1) || (list[i+1]!=list[i]))) ){
System.out.println(list[i]);
break;
}
}

Generating non-duplicate numbers using Arrays, not ArrayList<> in Java

I'm doing the old Lotto exercise and I need to specifically use an Array[] of integers and not an ArrayList. I have what I thought would work, but I seem to be wrong. I looked for posts similar to these and all of them involved an ArrayList<>. Here is a partition of my code.
Integer[] lottoNums;
lottoNums = new Integer[7];
for(int i = 0; i < lottoNums.length; i++){
lottoNums[i] = randomNums.nextInt((59)+1);
if(i <= 5) {
if(lottoNums[i].equals(lottoNums[i+1])){
if(lottoNums[i] < 58 && lottoNums[i] > 1)
lottoNums[i] = lottoNums[i] +1;
}
}
else if(i >= 1) {
if(lottoNums[i].equals(lottoNums[i-1])){
if(lottoNums[i] < 58 && lottoNums[i] > 1)
lottoNums[i] = lottoNums[i] +1;
}
}
}
Arrays.sort(lottoNums);
System.out.print("Winning numbers: "+lottoNums[0]);
for (int i = 1; i < 6; i++) {
System.out.print(", " + lottoNums[i]);
}
System.out.print(System.getProperty("line.separator"));
System.out.println("Bonus Number: "+lottoNums[6]);
I need to get it to generate a number in between 1 and 59 and not duplicate. I was trying to pair it up with the value stored in the element before and after it (if it had one) and if it was equal to it, it would add 1 to it. I run it a few times and every once in a while im still getting duplicate numbers. How can i do this efficiently, using Arrays[] of integers ONLY?
EDIT:
Initialized array to remove NullPointerException.
Updated Code:
for(int i = 0; i < lottoNums.length; i++){
lottoNums[i] = randomNums.nextInt((59)+1);
}
for (int i = 0; i < 6; i++) {
int rnd = randomNums.nextInt((lottoNums).length-i);
int k = lottoNums[lottoNums.length-i-1];
lottoNums[lottoNums.length-i-1] = lottoNums[rnd];
lottoNums[rnd] = k;
}
Arrays.sort(lottoNums);
System.out.print("Winning numbers: "+lottoNums[0]);
//PRINTING LOTTO NUMBERS
for (int i = 1; i < 6; i++) {
System.out.print(", " + lottoNums[i]);
}
System.out.print(System.getProperty("line.separator"));
System.out.println("Bonus Number: "+lottoNums[6]);
You can do this by switching the selected number with the last number in the array each time, and then selecting the next from the prefix you have not yet stored:
for (int i = 0; i < 6; i++) {
int rnd = randomNums.nextInt(numbers.length-i);
int k = numbers[numbers.length-i-1];
numbers[numbers.length-i-1] = numbers[rnd];
numbers[rnd] = k;
}
At the end of this loop your selected numbers will be in numbers[numbers.length-7..numbers.length-1], etc.
I would use two arrays. Each time you draw a number see if it exists in the second array. If not use it and add it to the second array.

Java Union array of 2 int arrays using nested loops [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I want to create a union array for two integer arrays using nested loops.
This is my attempt so far:
import java.util.Scanner ;
public class array4 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter first array size:");
int size = input.nextInt();
int x[] = new int[size];
System.out.println("Enter first array elements:");
for (int i = 0; i < size; i++) {
x[i] = input.nextInt();
}
System.out.print("Enter second array size:");
int size2 = input.nextInt();
int y[] = new int[size2];
for (int i = 0; i < size2; i++) {
y[i] = input.nextInt();
}
System.out.println("Union");
for (int i = 0; i < size; i++) {
System.out.println(x[i]);
}
for (int i = 0; i < size2; i++) {
for (int z = 0; z < size; z++) {
if (y[i] != x[z]) {
System.out.println(y[i]);
}
}
}
}
}
Lets assume that we will print all numbers from second array, and only these numbers from first array which don't exist in second one. So
for each element in first array
test if it exist in second array (iterate over elements in second array and set some boolean flag like exists to true if x[i]==y[j])
if element doesn't exist in second array print it
iterate over elements from second array
and print them
Algorithm can look like
for (int i = 0; i <= x.length; i++) {// "<=" is not mistake,
// in last iteration we print all elements
// from second array
boolean exist = false;
for (int j = 0; j < y.length; j++) {
if (i < x.length) {
if (x[i] == y[j])
exist = true;
} else
System.out.println(y[j]);
}
if (!exist && i < x.length)
System.out.println(x[i]);
}
This algorithm can be probably rewritten to something simpler but I will leave it in this form for now.
For the lack of requirements, here is my answer for now... just basing on your current code.
for (int i = 0; i < size2; i++) {
for (int z = 0; z < size; z++) {
if (y[i] != x[z]) {
System.out.println(y[i]);
break; //added break
}
}
}
The problem was you're printing array elements without duplicate multiple times, to avoid that, you should add a break after you print the element with no duplicate.
By the way, your code is just printing the elements on both arrays, I thought you're suppose to combine them? Shouldn't you have a new array that contains both of the elements on the two arrays?
EDIT 2:
Add these lines of code after you get the two set of arrays without duplicate:
I also added comments to explain what's happening.
System.out.println("Union");
int[] unionArray = new int[size + size2]; //created a new array that will contain two arrays
for (int i = 0; i < size; i++) { //put the first set of int in the new array
unionArray[i] = x[i];
}
for (int i = size; i < unionArray.length; i++) { //put the second set
unionArray[i] = y[i-size]; //i = size : started with the last index of the first array
//y[i-size] : we are getting the elements on the second array
}
for (int i = 0; i < unionArray.length; i++) { //output
System.out.println(unionArray[i]);
}
Hope this helps. :)
If it's just to play with arrays and you don't need to use loops - try using a Java collection for that task, that's how most people would probably implement it:
init collection 1 from array 1
init collection 2 from array 2
add collection 2 to collection 1
convert collection 1 back to an array
That can be a (more or less) neat one-liner.

Prime Numbers Java - Wheres my mistake [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
public class primzahlen {
public static void main(String[] args) {
System.out.println(2 % 1);
calculate_primenumber(10);
}
static void calculate_primenumber(int a) {
int zahl = 1;
boolean isprimenumber = false;
for (int i = 1; i <= a; i++) {
for (int j = 1; j <= i; j++) {
if (i % j > 0) {
// No PrimeNumber
isprimenumber = false;
} else {
// Is PrimeNumber
isprimenumber = true;
zahl = i;
System.out.println(zahl);
}
}
}
}
}
I don't know why this doesn't work.
I want to calculate 10 prime numbers.
But somehow it only prints counts up to 10 3 times and thats it.
I don't know wheres my mistake.
I have 2 for loops. That's how I learned the prime numbers calculation that I have to use 2 for loops for it but it don't work. I thought first it is the % (the rest) but when I do it on paper it should work.
There are at least four things wrong with your code.
First, you have the % condition backwards. If you're testing the number i, and you want to see if it has a divisor j, then you need to test i % j == 0. If this is true, the number is not prime. The way you tested it, though, you told it that if i % j is not zero, then the number is not prime.
Second, when you test to see if something divides i, you cannot test 1, and you cannot test i itself. Therefore,
for (int j = 1; j <= i; j++) {
should look more like
for (int j = 2; j < i; j++) {
although it's usually
for (int j = 2; j < Math.sqrt(i); j++) {
since once you get past the square root of i you don't need to search any more.
Third: your inner loop sets isprimenumber to either true or false on every iteration. That isn't right. If we find a case where i has a divisor, we know that isprimenumber is false, and we should never set it to true again, for that i. So a loop like this would work:
isprimenumber = true;
for (int j = 2; j < i; j++) {
if (i % j == 0) {
// No PrimeNumber
isprimenumber = false;
}
// If it's non-zero, don't set isprimenumber to true, because if we
// set it to false earlier, then it still should be false!
}
// And wait until we've tested all the j's before we can tell if it's true.
if (isprimenumber) {
}
You can also put break after isprimenumber = false, because once we've found a divisor we don't need to keep looking.
for (int j = 2; j < i; j++) {
if (i % j == 0) {
// No PrimeNumber
isprimenumber = false;
break;
}
Without the break, the loop will go on a few more times but it won't do anything useful. (But it won't be harmful, either.)
Fourth, you said you want to print 10 primes, but your logic tested all the numbers from 1 to 10, and there aren't 10 primes in that range. If you want the first 10 primes, where your parameter a is 10, you can't stop the loop at i <= a:
for (int i = 1; i <= a; i++) {
Instead, you'll need to declare another counter to count the number of primes.
int count = 0;
and when you find a prime and print it:
count++;
Then you could write your for loop like this:
for (int i = 1; count < a; i++) {
and it will stop when the number of primes reaches a.
EDIT: There's one more error I missed: the code I suggested will find that 1 is a prime number, but technically it isn't (so say the mathematicians). So you should start at i = 2:
for (int i = 2; count < a; i++) {
"I want to check for 10 prime numbers"
When you say
for (int i = 1; i <= a; i++)
You are saying "the numbers from 1 to a," which in this case is 1 to 10. Thus, you can only check 1 through 10 for primality. a is the upper bound you place on the numbers to check for primality.
If you want to get the first 10 prime number instead, you are going to have to use a condition which checks for the number of primes you have discovered (and keep count of that).
"It only prints counts up to 10 3 times and thats it"
Your modulus check should be (i % j == 0) - this means that j evenly divides i, and is therefore a factor of i. As you stand, you are saying that if any j is not a factor of i, the number is immediately composite. Not only is this not a correct conclusion, but it jumps the gun on your decision. You should assume it is prime until you can prove it is composite - then you can decide early.
One thing to keep in mind is the fact that a number, mod itself, is always 0. The same goes for a number mod 1. So, you will have to make sure you do not compare any i with itself or with 1. Change the second for loop to stop when j < i and to start with j = 2.
for (int i = 1; i <= a; i++) {
isprimenumber = true;
for (int j = 2; j < i; j++) {
// check each number less than this one for factors
if (i % j == 0) {
// found an even divisor, so the number is composite
isprimenumber = false;
break;
}
}
if (isprimenumber) {
System.out.println(i);
}
}
You can make other optimizations by noting that 1 is generally not considered a prime number, so you can have your first loop be for (int i = 2; i <= a; i++) and also considering that there are no even divisors of a number greater than one half of that number, so you can have your second loop be for (int j=2; j < i/2; j++).
This is one way
public class Primzahlen {
public static void main(String[] args){
calculate_primenumber(10);
}
static void calculate_primenumber(int a) {
int primesFound = 0;
boolean isprimenumber;
for(int i = 2; primesFound < a; i++){
isprimenumber = true;
for(int j = 2; j < i ; j++){
if(i % j == 0){
isprimenumber = false;
break;
}
}
if(isprimenumber){
primesFound++;
System.out.println(i);
}
}
}
}
but you can make it more efficient. This is only one way : klick
You must do the true thing on the end of the loop like this:
for (int i = 1; i <= a; i++) {
for (int j = 1; j <= i; j++) {
if (i % j > 0) {
// No PrimeNumber
isprimenumber = false;
} else {
// Is PrimeNumber
isprimenumber = true;
}
}
if(isprimenumber)
System.out.println(i);
}
you can only tell its a prime if you tested all numbers.

Categories

Resources