This is a brute force attempt to solve the problem, but it is not giving the right answer. The program runs, but its not producing desired output. I believe the logic and program is correct.
This is problem of a famous site (don't want to a spoiler)
It asks for the number that produces the longest Collatz chain under one million.
class Euler
{
public static void main (String args[])
{
long len,longLength=0;
for(long i =3;i<=1000000;i++)
{
len = Euler14.numFucs(i);
System.out.println("Ans"+len+"\t"+i);
if(len>longLength)
longLength=len;
}
System.out.println(longLength);
}
public static long numFucs(long num)
{
long count=1,$test=0;
while(num>1)
{
if(num%2==0)
{
num=num/2;
}
else
{
num=3*num+1;
}
count++;
}
//System.out.println("\tEnd");
return count;
}
}
Well, I feel like it'd be cheating to give you the code for the right answer, as a fellow Project Euler fan. You're outputting the length of the longest chain, not the number that obtains it. If you really want, I can show you the one line that needs to change, but, honestly, this is a simple fix, and I challenge you to do it yourself.
If the program is suppose to compute the number of steps in the Collatz Conjecture the implementation looks fine to me.
The sequence of numbers in described by OEIS Sequence A008908.
Here's is your program together with some debug output.
class Test {
public static void main(String args[]) {
long len, longLength = 0;
System.out.println(Test.numFucs(13));
String[] correct = ("1, 1, 2, 8, 3, 6, 9, 17, 4, 20, 7, 15, 10, 10, 18,"
+ " 18, 5, 13, 21, 21, 8, 8, 16, 16, 11, 24, 11, 112, "
+ "19, 19, 19, 107, 6, 27, 14, 14, 22, 22, 22, 35, 9, "
+ "110, 9, 30, 17, 17, 17, 105, 12, 25, 25, 25, 12, "
+ "12, 113, 113, 20, 33, 20, 33, 20, 20, 108, 108, 7,"
+ " 28, 28, 28, 15, 15, 15, 103").split(", ");
for (int i = 0; i <= 70; i++) {
len = Test.numFucs(i);
System.out.printf("i = %2d, Correct %3s, Computed: %3d%n", i,
correct[i], len);
if (len > longLength)
longLength = len;
}
System.out.println(longLength);
}
public static long numFucs(long num) {
long count = 1;
while (num > 1) {
if (num % 2 == 0) {
num = num / 2;
} else {
num = 3 * num + 1;
}
count++;
}
// System.out.println(count);
return count;
}
}
Output:
i = 0, Correct 1, Computed: 1
i = 1, Correct 1, Computed: 1
i = 2, Correct 2, Computed: 2
i = 3, Correct 8, Computed: 8
i = 4, Correct 3, Computed: 3
i = 5, Correct 6, Computed: 6
i = 6, Correct 9, Computed: 9
i = 7, Correct 17, Computed: 17
i = 8, Correct 4, Computed: 4
i = 9, Correct 20, Computed: 20
i = 10, Correct 7, Computed: 7
i = 11, Correct 15, Computed: 15
i = 12, Correct 10, Computed: 10
i = 13, Correct 10, Computed: 10
i = 14, Correct 18, Computed: 18
i = 15, Correct 18, Computed: 18
i = 16, Correct 5, Computed: 5
...
As you can see it follows the OEIS sequence.
The error must be some where else.
Related
While looping through a for loop which is randomly 1-10 long. I also go through a while loop. I am trying to find 6 random numbers between 1-42. I then do that again (1-10) times. Currently, these 6 random numbers stay the same. I suspect it has something to do with the seed but I could not solve it.
I tried to use both SecureRandom, Random, and via Math.random()
Nothing has worked.
The model:
public static final int MAX_TIPS = 10;
public static final int MIN_TIPS = 1;
public static final int REQUIRED_NUMBERS = 6;
public static final int RANGE_NUMBER_MIN = 1;
public static final int RANGE_NUMBER_MAX = 42;
public static final int RANGE_LUCKY_NUMBER_MIN = 1;
public static final int RANGE_LUCKY_NUMBER_MAX = 6;
private Random random = new Random();
private int getRandomInt(int min, int max) {
return random.nextInt((max - min) + 1) + min;
}
public ArrayList<LottoTip> createOpponentTips() {
ArrayList<Integer> opponentChosenNumbers = new ArrayList<>();
ArrayList<LottoTip> lottoTips = new ArrayList<>();
//1-10
int amountOfTips = getRandomInt(MIN_TIPS, MAX_TIPS);
for (int i = 0; i < amountOfTips; i++) {
int[] arrayOpponentChosenNumbers = new int[REQUIRED_NUMBERS];
while (opponentChosenNumbers.size() < REQUIRED_NUMBERS) {
//1-42 This here is the problem zone
int randomNumber = getRandomInt(RANGE_NUMBER_MIN, RANGE_NUMBER_MAX);
if (!opponentChosenNumbers.contains(randomNumber)) {
opponentChosenNumbers.add(randomNumber);
}
}
//1-6 ---This here works
int opponentLuckyNumber = getRandomInt(RANGE_LUCKY_NUMBER_MIN, RANGE_LUCKY_NUMBER_MAX);
for (int j = 0; j < opponentChosenNumbers.size(); j++) {
arrayOpponentChosenNumbers[j] = opponentChosenNumbers.get(j);
}
lottoTips.add(new LottoTip(arrayOpponentChosenNumbers, opponentLuckyNumber));
}
return lottoTips;
}
LottoTip:
public class LottoTip {
private int[] numbers;
private int luckyNumber;
public LottoTip(int[] numbers, int luckyNumber) {
this.numbers = numbers;
this.luckyNumber = luckyNumber;
}
public String getNumbers() {
return numbers[0] + ", " + numbers[1] + ", " + numbers[2] + ", " + numbers[3] + ", " + numbers[4] + ", " + numbers[5];
}
public void setNumbers(int[] numbers) {
this.numbers = numbers;
}
public int[] getNumbersArray() {
return numbers;
}
public int getLuckyNumber() {
return luckyNumber;
}
public void setLuckyNumber(int luckyNumber) {
this.luckyNumber = luckyNumber;
}
#Override
public String toString() {
return "\nNumbers: " + getNumbers() + " Lucky Number: " + luckyNumber;
}
}
Here is a System.out.println as you can see the Numbers are staying the same. Could you help me find a way to create a getRandomInt method which works all the time?
Thank you very much for your help.
Kerry York [
Numbers: 6, 4, 30, 15, 25, 5 Lucky Number: 2,
Numbers: 6, 4, 30, 15, 25, 5 Lucky Number: 4,
Numbers: 6, 4, 30, 15, 25, 5 Lucky Number: 5,
Numbers: 6, 4, 30, 15, 25, 5 Lucky Number: 1,
Numbers: 6, 4, 30, 15, 25, 5 Lucky Number: 3,
Numbers: 6, 4, 30, 15, 25, 5 Lucky Number: 6]
Don Dickinson [
Numbers: 23, 29, 34, 18, 16, 19 Lucky Number: 6,
Numbers: 23, 29, 34, 18, 16, 19 Lucky Number: 5,
Numbers: 23, 29, 34, 18, 16, 19 Lucky Number: 3,
Numbers: 23, 29, 34, 18, 16, 19 Lucky Number: 2,
Numbers: 23, 29, 34, 18, 16, 19 Lucky Number: 4,
Numbers: 23, 29, 34, 18, 16, 19 Lucky Number: 1,
Numbers: 23, 29, 34, 18, 16, 19 Lucky Number: 1,
Numbers: 23, 29, 34, 18, 16, 19 Lucky Number: 4,
Numbers: 23, 29, 34, 18, 16, 19 Lucky Number: 3]
Clifford Weinstein [
Numbers: 6, 33, 13, 2, 37, 38 Lucky Number: 6,
Numbers: 6, 33, 13, 2, 37, 38 Lucky Number: 3,
Numbers: 6, 33, 13, 2, 37, 38 Lucky Number: 2,
Numbers: 6, 33, 13, 2, 37, 38 Lucky Number: 1,
Numbers: 6, 33, 13, 2, 37, 38 Lucky Number: 4,
Numbers: 6, 33, 13, 2, 37, 38 Lucky Number: 3,
Numbers: 6, 33, 13, 2, 37, 38 Lucky Number: 5,
Numbers: 6, 33, 13, 2, 37, 38 Lucky Number: 6,
Numbers: 6, 33, 13, 2, 37, 38 Lucky Number: 3,
Numbers: 6, 33, 13, 2, 37, 38 Lucky Number: 3]
Angela Spencer [
Numbers: 12, 39, 8, 25, 40, 15 Lucky Number: 6,
Numbers: 12, 39, 8, 25, 40, 15 Lucky Number: 3,
Numbers: 12, 39, 8, 25, 40, 15 Lucky Number: 2,
Numbers: 12, 39, 8, 25, 40, 15 Lucky Number: 4,
Numbers: 12, 39, 8, 25, 40, 15 Lucky Number: 5,
Numbers: 12, 39, 8, 25, 40, 15 Lucky Number: 4,
Numbers: 12, 39, 8, 25, 40, 15 Lucky Number: 2,
Numbers: 12, 39, 8, 25, 40, 15 Lucky Number: 2,
Numbers: 12, 39, 8, 25, 40, 15 Lucky Number: 3]
Leroy McIntosh [
Numbers: 5, 23, 2, 24, 28, 3 Lucky Number: 1]
You reuse the opponentChosenNumbers list between iterations of the outer for loop.
As such, on the second iteration, the while loop guard
while (opponentChosenNumbers.size() < REQUIRED_NUMBERS) {
is immediately false, so you don't pick new random numbers.
Move the declaration of opponentChosenNumbers into the for loop (or ensure it is empty before the while loop, e.g. by invoking opponentChosenNumbers.clear()).
i got below mentioned error when run code:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 1, Size: 0
at java.util.LinkedList.checkPositionIndex(Unknown Source)
at java.util.LinkedList.addAll(Unknown Source)
at Collection.Dynamycmaasiv.Collecktionaddlist.main(Collecktionaddlist.java:36)
code
public static void main(String[] args) {
LinkedList<Integer> num = new LinkedList<Integer>();
LinkedList<Integer> numodd = new LinkedList<Integer>();
LinkedList<Integer> numeven = new LinkedList<Integer>();
LinkedList<Integer> sumoffevenandodd = new LinkedList<Integer>();// help
// me
// to
// solve
for (double i = 0; i < 50; i++) {
num.add((int) i);
if (i % 2 == 0) {
numeven.add((int) i);
} else {
numodd.add((int) i);
}
}
System.out.println(num);
System.out.println("-----------------");
System.out.println(numodd);
System.out.println("-----------------");
System.out.println(numeven);
for (int i =0; i<numeven.size(); i++){
sumoffevenandodd.addAll(numeven.get(i)+ numodd.get(i), null);
}
System.out.println(sumoffevenandodd);
}
}
addAll() is not about adding up numbers. It is about adding all the elements of the method parameter to the collection itself.
So, you need to loop, like
int sum = 0;
for (Integer numberFromList : numeven) {
sum = sum + numberFromList;
Or, if you have Java8, you can use streams:
int sumEven = numeven.stream().sum();
Sum, done.
And for the record: the real lesson to be learned here: read the javadoc. Don't assume that method called addAll() does what you suppose it does. Turn to the javadoc and inform yourself what reality thinks about your assumptions.
But just to be clear; as I got carried away with your question, too.
In your code, if you change
sumoffevenandodd.addAll(numeven.get(i)+ numodd.get(i), null);
to
sumoffevenandodd.add(numeven.get(i)+ numodd.get(i));
it should work, too.
Long story short: if you intended to really have a list with 50 sums within, then my first paragraphs do not really help with your problem.
But it isn't exactly clear what you wanted to do; so I leave my answer as is - to address both possible explanations what is "wrong" in your logic.
if the intention of the question is
num odd
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49]
num even
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48]
sum of odd and even
[1, 5, 9, 13, 17, 21, 25, 29, 33, 37, 41, 45, 49, 53, 57, 61, 65, 69, 73, 77, 81, 85, 89, 93, 97]
then
for (int i =0; i< numeven.size(); i++){
sumoffevenandodd.add(numeven.get(i)+ numodd.get(i));
}
having this issue with a decryption program I am writing in Java. Here is the code in question
public static int int_to_int(int input)
{
int[] value_array = {0, 1, 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};
int[]bin_array= {00000, 00001, 00010, 00011,
00100, 00101, 00110, 00111,
01000, 01001, 01010, 01011, 01100,
01101, 01110, 01111, 10000, 10001,
10010, 10011, 10100, 10101, 10110,
10111, 11000,11001, 11010, 11011};
for(int i=0; i <27; i++)
{
System.out.println("hello");
if(input==value_array[i])
{
System.out.println("returning: " + bin_array[i] + "at: " + i);
return bin_array[i];
}
}
return -1;
}
And here is the issue highlighted in a line
double temp = 00010;
System.out.println("returning: " + temp);
This will output
returning: 8
but I want to see
returning: 00010
thoughts?
The 00010 is octal number, i.e., 8. Remove all the leading zeroes.
Integers prefixed with 0 are treated as octal, not binary. Prefix with 0b or 0B to indicate binary, like 0B00010. To print as binary, use
System.out.println("returning: " + Integer.toBinaryString(temp));
or,
System.out.println("returning: " + Integer.toString(temp, 2));
That is, assuming temp is an integer, like in your bin_array.
public static int int_to_int(int input)
{
int[] value_array = {0, 1, 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};
int[]bin_array= {00000, 00001, 00010, 00011,
00100, 00101, 00110, 00111,
01000, 01001, 01010, 01011, 01100,
01101, 01110, 01111, 10000, 10001,
10010, 10011, 10100, 10101, 10110,
10111, 11000,11001, 11010, 11011};
for(int i=0; i <27; i++)
{
System.out.println("hello");
if(input==value_array[i])
{
System.out.println("returning: " + Integer.toOctalString(bin_array[i]) + "at: " + i);
return bin_array[i];
}
}
return -1;
}
I use Integer.toOctalString
I have a code but I want to avoid using java streams because streams are not supported in android. Here is my code:
import java.util.Arrays;
import static java.util.Arrays.stream;
import java.util.concurrent.*;
public class VogelsApproximationMethod {
final static int[] demand = {30, 20, 70, 30, 60};
final static int[] supply = {50, 60, 50, 50};
final static int[][] costs = {{16, 16, 13, 22, 17}, {14, 14, 13, 19, 15},
{19, 19, 20, 23, 50}, {50, 12, 50, 15, 11}};
final static int nRows = supply.length;
final static int nCols = demand.length;
static boolean[] rowDone = new boolean[nRows];
static boolean[] colDone = new boolean[nCols];
static int[][] result = new int[nRows][nCols];
static ExecutorService es = Executors.newFixedThreadPool(2);
public static void main(String[] args) throws Exception {
int supplyLeft = stream(supply).sum();
int totalCost = 0;
while (supplyLeft > 0) {
int[] cell = nextCell();
int r = cell[0];
int c = cell[1];
int quantity = Math.min(demand[c], supply[r]);
demand[c] -= quantity;
if (demand[c] == 0)
colDone[c] = true;
supply[r] -= quantity;
if (supply[r] == 0)
rowDone[r] = true;
result[r][c] = quantity;
supplyLeft -= quantity;
totalCost += quantity * costs[r][c];
}
stream(result).forEach(a -> System.out.println(Arrays.toString(a)));
System.out.println("Total cost: " + totalCost);
es.shutdown();
}
i would be grateful if anyone can help me with this because i can't understand how stream works.
Well that is quite easy, you can use for loop as Mike M suggested in his comment see examples below:
int supplyLeft = 0;
int[] supply = {50, 60, 50, 50};
for (int i : supply) {
supplyLeft += i;
}
System.out.println(supplyLeft);
to replace
int supplyLeft = stream(supply).sum();
if you don't want foreach either then
int supplyLeft = 0;
for (int i = 0; i < supply.length; i++) {
supplyLeft += supply[i];
}
System.out.println(sum);
As far as iterating through 2D array and replacing the java-8 stream as shown below is concerned
stream(result).forEach(a -> System.out.println(Arrays.toString(a)));
you can use a for loop or Arrays.deepToString() as per your needs see below example:
//assume your array is below, you can replace it with results everywhere
int[][] costs= { { 16, 16, 13, 22, 17 }, { 14, 14, 13, 19, 15 },
{ 19, 19, 20, 23, 50 }, { 50, 12, 50, 15, 11 } };
for (int i = 0; i < costs.length; i++) {
System.out.println(Arrays.toString(costs[i]));
}
Above for loop will print you the array in the following manner
[16, 16, 13, 22, 17]
[14, 14, 13, 19, 15]
[19, 19, 20, 23, 50]
[50, 12, 50, 15, 11]
If you use Arrays.deepToString(costs) then you get an output as shown below:
[[16, 16, 13, 22, 17], [14, 14, 13, 19, 15], [19, 19, 20, 23, 50], [50, 12, 50, 15, 11]]
Above to replace
I am attempting to make a QuickSort program and while I feel like it should be outputting as desired, it is not. I feel the problems lies in how I have constructed my loops but that may not be the case. As you can see, the first test with the runner prints out as I want and everything eventually gets sorted right. Any help would be greatly appreciated.
My main program:
import static java.lang.System.*;
import java.util.Arrays;
//use Arrays.toString() to help print out the array
public class QuickSort
{
private static int passCount;
public static void quickSort(Comparable[] list)
{
passCount=0;
quickSort(list, 0, list.length-1);
}
private static void quickSort(Comparable[] list, int low, int high)
{
if(low >= high)
return;
int a = partition(list, low, high);
quickSort(list, low, a-1);
quickSort(list, a+1, high);
}
private static int partition(Comparable[] list, int low, int high)
{
int x = low + 1;
int y = high;
while(x <= y)
{
if(list[x].compareTo(list[low]) <= 0)
{x++;}
else if(list[y].compareTo(list[low]) > 0)
{y--;}
else if(y < x)
{break;}
else
exchange(list, x, y);
}
exchange(list, low, y);
out.println("pass " + passCount++ + " " + Arrays.toString(list) + "\n");
return y;
}
private static void exchange(Object[] list, int x, int y) {
Object temporary = list[x];
list[x] = list[y];
list[y] = temporary;
}
}
My runner:
public class QuickSortRunner
{
public static void main(String args[])
{
QuickSort.quickSort(new Comparable[]{9,5,3,2});
System.out.println("\n");
QuickSort.quickSort(new Comparable[]{19,52,3,2,7,21});
System.out.println("\n");
QuickSort.quickSort(new Comparable[]{68,66,11,2,42,31});
System.out.println("\n");
}
}
My output:
pass 0 [2, 5, 3, 9]
pass 1 [2, 5, 3, 9]
pass 2 [2, 3, 5, 9]
pass 0 [2, 7, 3, 19, 52, 21]
pass 1 [2, 7, 3, 19, 52, 21]
pass 2 [2, 3, 7, 19, 52, 21]
pass 3 [2, 3, 7, 19, 21, 52]
pass 0 [31, 66, 11, 2, 42, 68]
pass 1 [11, 2, 31, 66, 42, 68]
pass 2 [2, 11, 31, 66, 42, 68]
pass 3 [2, 11, 31, 42, 66, 68]
Desired output:
pass 0 [2, 5, 3, 9]
pass 1 [2, 5, 3, 9]
pass 2 [2, 3, 5, 9]
pass 0 [7, 2, 3, 52, 19, 21]
pass 1 [3, 2, 7, 52, 19, 21]
pass 2 [2, 3, 7, 52, 19, 21]
pass 3 [2, 3, 7, 21, 19, 52]
pass 4 [2, 3, 7, 19, 21, 52]
pass 0 [31, 66, 11, 2, 42, 68]
pass 1 [2, 11, 66, 31, 42, 68]
pass 2 [2, 11, 66, 31, 42, 68]
pass 3 [2, 11, 42, 31, 66, 68]
pass 4 [2, 11, 31, 42, 66, 68]
The x++ and y-- to skip exchanges need to be in while loops so that exchange happens only when it is called for.