Java: generate all number combitations to a bound - java

I have the digits 1 3 5 7 and 9 (odds)what I want is a method type long[] that takes as parameter int digits
the digits paremater is supposed to be the maximum digits that the number could have.
this method is suppose to add all the possible combinations with 1 3 5 7 and 9 to the array.
What I've done so far:
Figured out the size of the array
int size = 0
for(int i = 0; i < digits; i++){
size += (int) Math.pow(5,i+1);
I've tried many for-loops but none of them seem to work.
The goal of this is that i'm trying to find some sort of a prime number and making this table will make my program a lot faster.

If i understand you correctly i think this might work. Maybe there is a cleaner way, it's been a while since i worked in JAVA.
long[] expand(int digits) {
int[] a = {1, 3, 5, 7, 9};
long[] b = long[5];
for(int i=0; i<5; i++){b[i] = a[i];}
int it_left = digits;
while(it_left > 0) {
it_left--;
long[] c = long[(b.length()*5)];
for(int i=0; i<5; i++){
long tmp = a[i]*Math.pow(10, (digits-it_left));
for(int j=0; j<b.length(); j++){
c[(i*b.length())+j] = tmp + b[j];
}
}
b = long[c.length()];
for(int i=0; i<c.length(); i++){
b[i]=c[i];
}
}
return b;
}

Related

Filling rest of Array

I am writing a two's complement program where I convert decimal to binary using an array. I also want to have 8 Bits binary.
Since, for example, 22 is 10110 in binary, I want to fill the rest of the array with zeros, but I wasn't able to find a way how to do this.
Any help is appreciated.
Edit:
static void toBin(int number){
int[] bin = new int[8];
int i =0;
while (number > 0){
bin[i] = number % 2;
number = number/2;
i++;
}
// Here is where I would like to add zeros if the size of the array is below 0
for (int j = i-1; j>=0;j--){
System.out.println(bin[j]); //Array gets reserved
}
}
There is a class called "Arrays" that has a method called "fill()".
The syntax is "Arrays.fill()".
Inside the round brackets, after "fill", you have to put the value that will fill the rest of the array.
The example below fills the elements which have index from 0 to 5 (without 6) with the value 1.
int[] intArray = new int[8];
Arrays.fill(ints2, 0, 6, 1) ;
System.out.println(Arrays.toString(intArray));
Here is the output:
[1, 1, 1, 1, 1, 1, 0, 0]
Look at this code:
int number =22;
int bits[]= new int[8];
for(int i=0;i<=7;i++){
if(number>0){
bits[7-i]=number%2;
number/=2;
}
else{
bits[7-i]=0;
}
}
for(int i=0;i<=7;i++){
System.out.print(bits[i]);
}
I think, I have resolved your problem.
First initialize the whole string and reserve some space, like eight characters.
String binaryStr = "00000000";
for (int i = 0; i < binaryStr.Length (); i++)
{
if (binaryShouldBeOne)
{
binaryStr[i] = '1';
} else
{
binaryStr[i] = '0';
}
}
This may help.
int out[] = new int[8];
int in = 22;
int i = out.length - 1;
while (i >= 0 && in > 0) {
out[i] = in % 2;
in /= 2;
i--;
}
for (int j = 0; j < out.length; j++) {
System.out.print(out[j] + " ");
}
System.out.println("");
The array is initialized with zeros when it is created. You need just to change the required digits with 1 and rest will remain zeros. Try to start filling the array from 8th digit then decrement your counter so you may reach the most left digit.

printing a 2d array java

The program I need to write is a square 2d array made of numbers, like this
0 1 2
3 4 5
6 7 8
or this
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
The program reads the number "d" (side of the square 2d array- above are examples of d=3 and d=5), number "n" (how many inputs there will be next) and these n inputs (eg. if n=3, the program should let me insert three numbers, like from the first example, let's say I'd choose 1 and 4 and 3. So the input looks like:
3
3
1 4 2
Then, it needs to calculate the distance between the first and second, second and third input and sum them up. That sum is then the output. Here is the program
if(b==2) {
int d=sc.nextInt();
int n=sc.nextInt();
int[][] array=new int[d][d]; //length and heigth of array
int c=0;
int manhattanDistanceSum=0;
for (int i = 0; i < n; i ++){ //for inserting values
for (int j = 0; j < n; j ++){
if (i < n){
i++;
array[i][j] = sc.nextInt();
}
else {
break;
}
for( i=0; i<array.length;i++) {
for( j=0;j<array[0].length;j++) {
array[i][j]=c; //actual locations of numbers
//numbers in array
c++;
if(manhattanDistanceSum != 0) {
int dx= c / d;
int dy= c % d;
c=Math.abs(dx) + Math.abs(dy);
manhattanDistanceSum+=c;
}
}
}
System.out.print(array[i][j]);
System.out.println();
}
}
System.out.println(manhattanDistanceSum);
}
}
}
*the b doesn't matter, it just means this is going to be a square array, so ignore it. It has nothing to do with this.
This is all I got, and need help with anything that is wrong in my code.
Thankyou
I've just cobbled together this example and tested that it works with positive and negative numbers. It might not do exactly what you want (for example, is the data in your array organised row-by-column or column-by-row) and it might not exactly format the output the way you want, but it should show you how to iterate through the array and analyse and then extract the data to produce a String which can be printed out.
Be sure to conduct your own testing (create unit tests for all cases which your application will need) as I have thrown this together in a few minutes in the hope that it would get you started. It should not be considered a finished product by any means.
public static void main(String[] args) {
int[][] data = {{0, -10734, 2}, {3, 437, 5}, {6, 733838, 8}};
System.out.println("Table:\n" + formatAsTable(data));
}
public static String formatAsTable(int[][] squareNumericArray) {
int cellSpacing = 2;
StringBuilder sb = new StringBuilder();
int squareSide = squareNumericArray.length;
int cellSize = findLargestNumericString(squareNumericArray)
+ cellSpacing;
for (int firstIndex = 0; firstIndex < squareSide; ++firstIndex) {
if (squareNumericArray[firstIndex].length != squareSide) {
throw new IllegalArgumentException(
"Array must have same size in both dimensions.");
}
for (int secondIndex = 0; secondIndex < squareSide; ++secondIndex) {
sb.append(String.format("%-" + cellSize + "d",
squareNumericArray[firstIndex][secondIndex]));
}
sb.append("\n");
}
return sb.toString();
}
private static int findLargestNumericString(int[][] squareNumericArray) {
int maxLength = 0;
for (int firstIndex = 0; firstIndex < squareNumericArray.length;
++firstIndex) {
for (int secondIndex = 0; secondIndex
< squareNumericArray[firstIndex].length; ++secondIndex) {
String numberAsString = Integer.toString(
squareNumericArray[firstIndex][secondIndex]);
if (numberAsString.length() > maxLength) {
maxLength = numberAsString.length();
}
}
}
return maxLength;
}
This code will output the following to the console:
Table:
0 -10734 6
3 437 5
6 733838 19

I'm getting strange output from java program

I've some strange situation here and i thought that you may help me. I have an int array populated with numbers from 1 to 10. I want to generate random number from this array and save it to another int array. I used class Random to pick any number and since random throws 0 also i modify it like that ( so it throws numbers from 1 to 10 )
randNum = rand.nextInt(numbers.length-min+1)+min;
Following code makes sure that if it generates same random number, it skips it. Program is actually working and i'm getting in another array randomly positioned numbers from 1 to 10. That's what i wanted. But sometimes i'm missing one number from 1 - 10 AND iam Getting ZERO instead. Why??
int[] numbers = {1,2,3,4,5,6,7,8,9,10};
int[] usednum = new int[10];
Random rand = new Random();
int randNum;
int min = 1;
for (int x = 0; x<numbers.length; x++) {
for (int i = 0; i<usednum.length; i++) {
randNum = rand.nextInt(numbers.length-min+1) + min;
for (int f = 0; f<usednum.length; f++) {
if (usednum[f] == randNum) {
break;
} else if (usednum[f] == 0) {
usednum[x] = randNum;
}
}
}
}
for (int c = 0; c<usednum.length; c++) {
System.out.println(usednum[c]);
}
You're inner-most for loop only checks if the current random number is in the usednum[] array. And the for loop immediately outer of that only checks 10 times total. It gives up too quickly because it only tries 10 random numbers. If all 10 are already used, nothing will get stored in that slot of usednum[] (thus it will be 0), try adding a while loop around that and get rid of the extraneous outer-most for loop:
for(int i = 0; i<usednum.length; i++) {
while(usednum[i]==0) {
randNum = rand.nextInt(numbers.length-min+1)+min;
for(int f = 0; f<usednum.length; f++) {
if(usednum[f] == randNum) {
break;
} //if
else if (usednum[f] == 0) {
usednum[i] = randNum;
}
}
}
}
Also note that the assignment is for usednum[i] = randNum;.
This is essentially replacing the middle for loop (the one that goes from i=0 to 9) with the while loop.
If your goal is simply to shuffle an array of numbers, try this instead:
Integer[] numbers = {1,2,3,4,5,6,7,8,9,10};
Collections.shuffle(Arrays.asList(numbers));
It will have the same effect. Unless you are completing a homework assignment that forces you to solve the issue in a more manual fashion, just make use of the standard Java libraries.
The shuffle method writes changes through to the underlying Integer array, thanks to the special type of List returned by Arrays.asList(...). Note you have to use an array of Integer not int (see Why does Collections.shuffle() fail for my array?).
You are generating used numbers through an entire pass, so it doesn't generate a zero is just fails to generate a value it should.
you have one for loop too much.
remove the loop with the i iterator and the program should do what you want.
Oh and remove the -min+1 from the random generator, -1+1=0
Your array usednum is consisted of zeros at the beginning. In some cases, your program doesn't change that initial value, but breaks before at the line:
if(usednum[f] == randNum)
and does that during all iterations with same value x. X increments and there goes your chance to change the zero value.
Edit - followed it and re-wrote it:
List<Integer> numbers = new LinkedList<Integer>(Arrays.asList(new Integer[]{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }));
int[] usednum = new int[10];
Random rand = new Random();
int n = numbers.size();
for (int i = 0; i < n; i++) {
int randNum = rand.nextInt(numbers.size());
usednum[i]=numbers.get(randNum);
numbers.remove(randNum);
}
for (int c:usednum) {
System.out.println(c);
}
Actually, you are never using the content of the array numbers. Try changing the array to something like int[] numbers = { 10, 22, 23, 42, 53, 18, 7, 8, 93, 10 };. You will get similar output.
Jon Lin's answer describe why your code is not working but does not address this issue. I think you will want to change your code to something like:
int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int[] usednum = new int[10];
Random rand = new Random();
int selectedCount = 0;
while (selectedCount < numbers.length) {
int randNum = numbers[rand.nextInt(numbers.length)];
boolean contains = false;
for (int x = 0; x < selectedCount; x++) {
if (usednum[x] == randNum) {
contains = true;
break;
}
}
if (!contains) {
usednum[selectedCount] = randNum;
selectedCount++;
}
}
for (int c = 0; c < usednum.length; c++) {
System.out.println(usednum[c]);
}

How to perform a sum of an int[] array [duplicate]

This question already has answers here:
How do you find the sum of all the numbers in an array in Java?
(28 answers)
Closed 5 years ago.
Given an array A of 10 ints, initialize a local variable called sum and use a loop to find the sum of all numbers in the array A.
This was my answer that I submitted:
sum = 0;
while( A, < 10) {
sum = sum += A;
}
I didn't get any points on this question. What did I do wrong?
Once java-8 is out (March 2014) you'll be able to use streams:
int sum = IntStream.of(a).sum();
or even
int sum = IntStream.of(a).parallel().sum();
Your syntax and logic are incorrect in a number of ways. You need to create an index variable and use it to access the array's elements, like so:
int i = 0; // Create a separate integer to serve as your array indexer.
while(i < 10) { // The indexer needs to be less than 10, not A itself.
sum += A[i]; // either sum = sum + ... or sum += ..., but not both
i++; // You need to increment the index at the end of the loop.
}
The above example uses a while loop, since that's the approach you took. A more appropriate construct would be a for loop, as in Bogdan's answer.
int sum=0;
for(int i:A)
sum+=i;
int sum = 0;
for(int i = 0; i < A.length; i++){
sum += A[i];
}
When you declare a variable, you need to declare its type - in this case: int. Also you've put a random comma in the while loop. It probably worth looking up the syntax for Java and consider using a IDE that picks up on these kind of mistakes. You probably want something like this:
int [] numbers = { 1, 2, 3, 4, 5 ,6, 7, 8, 9 , 10 };
int sum = 0;
for(int i = 0; i < numbers.length; i++){
sum += numbers[i];
}
System.out.println("The sum is: " + sum);
Here is an efficient way to solve this question using For loops in Java
public static void main(String[] args) {
int [] numbers = { 1, 2, 3, 4 };
int size = numbers.length;
int sum = 0;
for (int i = 0; i < size; i++) {
sum += numbers[i];
}
System.out.println(sum);
}

How can I locate and print the index of a max value in an array?

For my project, I need to make a program that takes 10 numbers as input and displays the mode of these numbers. The program should use two arrays and a method that takes array of numbers as parameter and returns max value in array.
Basically, what I've done so far is used a second array to keep track of how many times a number appears. Looking at the initial array, you will see that the mode is 4. (Number that appears most). In the second array, the index 4 will have a value of 2, and thus 2 will be the maximum value in the second array. I need to locate this max value in my second array, and print the index. My output should be '4'.
My program is good up until I attempt to produce the '4', and I've tried a few different things but can't seem to get it to work properly.
Thank you for your time!
public class arrayProject {
public static void main(String[] args) {
int[] arraytwo = {0, 1, 2, 3, 4, 4, 6, 7, 8, 9};
projecttwo(arraytwo);
}
public static void projecttwo(int[]array){
/*Program that takes 10 numbers as input and displays the mode of these numbers. Program should use parallel
arrays and a method that takes array of numbers as parameter and returns max value in array*/
int modetracker[] = new int[10];
int max = 0; int number = 0;
for (int i = 0; i < array.length; i++){
modetracker[array[i]] += 1; //Add one to each index of modetracker where the element of array[i] appears.
}
int index = 0;
for (int i = 1; i < modetracker.length; i++){
int newnumber = modetracker[i];
if ((newnumber > modetracker[i-1]) == true){
index = i;
}
} System.out.println(+index);
}
}
Your mistake is in comparing if ((newnumber > modetracker[i-1]). You should check if the newnumber is bigger then the already found max. That is if ((newnumber > modetracker[maxIndex])
You should change your last rows to:
int maxIndex = 0;
for (int i = 1; i < modetracker.length; i++) {
int newnumber = modetracker[i];
if ((newnumber > modetracker[maxIndex])) {
maxIndex = i;
}
}
System.out.println(maxIndex);
You could change last part to:
int maxIndex = 0;
for (int i = 0; i < modetracker.length; i++) {
if (modetracker[i] > max) {
max = modetracker[i];
maxIndex = i;
}
}
System.out.println(maxIndex);

Categories

Resources