I am trying to typecast an integer array into a long array, but I don't quite know how to go about doing this.
So far, my code looks like this:
import java.util.Random;
public class main {
public static int[] sect(){
int[] returned = new int[4];
Random rand = new Random();
returned[0] = 4;
returned[1] = rand.nextInt(8) + 1;
returned[2] = rand.nextInt(7) + 1;
returned[3] = rand.nextInt(6) + 1;
return returned;
}
public static String num(){
for (int j = 0; j < 4; j++) {
int[] ints = sect();
for(int i =0; i < ints.length; i++) {
System.out.print(ints[i]);
}
}
return null;
}
}
I have tried doing things like:
return ((long)num());
But that never works. Does anyone know how I would go about doing this?
Are you using Java 8, if so this will work:
int[] arrayOfIntegers = {1, 2, 3, 4, 5, 6};
long[] arrayOfLongs = Arrays.stream(arrayOfIntegers).mapToLong(i -> i).toArray();
You can't do that.
You simply have to create an equal sized array, and copy the int values into that array. Unfortunately System.arraycopy() can not do that for you... So you can't avoid the manual copying here.
Because an array of int isn't an array of longs. Therefore there is no such cast as from a single int into a single long.
Related
This question already has answers here:
Generating Unique Random Numbers in Java
(21 answers)
Closed 1 year ago.
I am trying to create a method that fills an array with random integers with no duplicate elements. I'm having trouble making sure each element that is put into the new array is distinct.
Ex. if numOfDigits is 5, then I'd like something like [3][8][2][6][1]. At the moment it either outputs something like [9][0][1][0][0] or infinitely loops.
private static int[] hiddenSet(int numOfDigits){
int[] numArray = new int[numOfDigits];
int temp;
for (int i = 0; i < numArray.length; i++){
do {
temp = getRandomNum(10);
numArray[i] = temp;
} while (isDigitNew(numArray, temp));
//Each random num must be unique to the array
}
return numArray;
}
private static boolean isDigitNew(int[] numArray, int index){
for (int i = 0; i < numArray.length; i++) {
if (numArray[i] == index) {
return false;
}
}
return true;
}
One easy approach is to fill the array with distinct digits then shuffle it.
public static int[] getRandomDistinct(int length) {
Random rand = new Random();
int[] array = new int[length];
// Fill with distinct digits
for (int i = 0; i < length; i++) {
array[i] = i;
}
// Swap every element with a random index
for (int i = 0; i < length - 1; i++) {
int swapWith = i + rand.nextInt(length - i);
int tmp = array[i];
array[i] = array[swapWith];
array[swapWith] = tmp;
}
return array;
}
Your algorithm takes quadratic time at best. When the choice of random numbers becomes less looping may take ages. Even infinite might be possible.
Add a positive random number + 1 to the previous generated number. The desired range of numbers needs a bit of care.
At he end shuffle. If you start with a List, you can use Collections. shuffle.
You can use IntStream like this.
private static int[] hiddenSet(int numOfDigits) {
return IntStream.iterate(getRandomNum(10), i -> getRandomNum(10))
.distinct()
.limit(numOfDigits)
.toArray();
}
and
public static void main(String[] args) {
int[] a = hiddenSet(5);
System.out.println(Arrays.toString(a));
}
output:
[7, 4, 5, 0, 1]
This question already has answers here:
Make individual array values to single number in Python [closed]
(3 answers)
Closed 6 years ago.
Here is my array, it consists of array of integers. Actually, these are the key of my HashMap which consists of some sentences or say "STRING" of a complete paragraph as a key value pair. Now I wanted to join those sentences from taking the key from the integer array one after another in given order.
int[] arr = {3, 2, 0, 5, 3};
HashMap<Integer, String> h = new HashMap<Integer, String>() {{
put(0,"This is my third sentence.");
put(3,"This is my first sentence.");
put(5,"This is my forth sentence.");
put(2,"This is my second sentence.");
}};
The final output should be all the sentences combined as mentioned order and outout should be like a paragraph as :
This is my first sentence.This is my second sentence.This is my third sentence.
This is my forth sentence.This is my first sentence.
Instead of converting the value to a character type you can perform math. For each digit in the array, the corresponding power of 10 is the array length (minus one) minus the index (because Java arrays use 0 based indexing and the last digit corresponds to 100). Something like,
int[] arr = { 3, 2, 0, 5, 3 };
int result = 0;
for (int i = 0; i < arr.length; i++) {
result += arr[i] * Math.pow(10, arr.length - i - 1);
}
System.out.println(result);
Output is (as expected)
32053
Optimization
It's possible to optimize the code further by keeping the current power of ten and dividing 10 while iterating each digit. This would also allow the use of a for-each loop like
int[] arr = { 3, 2, 0, 5, 3 };
int result = 0;
int pow = (int) Math.pow(10, arr.length - 1);
for (int digit : arr) {
result += digit * pow;
pow /= 10;
}
System.out.println(result);
Alternatively, iterate the digits from right to left and multiply pow by 10 on each iteration. That might look something like,
int result = 0;
int pow = 1;
for (int i = arr.length - 1; i >= 0; i--) {
result += arr[i] * pow;
pow *= 10;
}
And the above might also be written like
int result = 0;
for (int i = arr.length - 1, pow = 1; i >= 0; i--, pow *= 10) {
result += arr[i] * pow;
}
int number = Integer.parseInt(Arrays.stream(arr).mapToObj(String::valueOf).collect(Collectors.joining()));
Yet another way:
int[] arr = {3, 2, 0, 5, 3};
int i = Integer.parseInt(Arrays.toString(arr).replaceAll("[\\[,\\] ]", ""));
System.out.println(i); // prints 32053
Though fairly simple, you should have tried yourself.
Still providing a solution, just debug and understand it.
Working Code
public static void main(String[] args) throws Exception {
int[] arr = {3, 2, 0, 5, 3};
StringBuilder numberStr = new StringBuilder();
for (int item : arr) {
numberStr.append(item);
}
int finalInt = Integer.parseInt(numberStr.toString());
System.out.println(finalInt);
}
Output
32053
First convert the array into string by appending elements one by one and the convert string into integer. Try this code:
public class NewClass63 {
public static void main(String args[]){
int[] arr = {3, 2, 0, 5, 3};
StringBuffer s = new StringBuffer();
for(int i=0;i<arr.length;i++){
s.append(arr[i]);
}
int x = Integer.parseInt(s.toString());
System.out.println(x);
}
}
int[] array = {3,2,0,5,3};
String x = "";
for(int i = 0;i<=array.length-1;i++){
x = x + String.valueOf(array[i]);
}
System.out.println(Integer.parseInt(x));
use a loop:
int[] arr = { 3, 2, 0, 5, 3 };
String itotal = "";
for (int i = 0; i < arr.length; i++)
{
itotal=itotal + String.valueOf(arr[i]);
}
int a = Integer.parseInt(itotal);
There exist various ways.
If I am right, hidden assumption is that the higher element of integer array matches with higher digit of result integer.
int[] arr = {3, 2, 0, 5, 3};
int result = 0;
int power = (int) Math.pow(10, arr.length-1);
for(int element : arr){
result += element * power;
power /= 10;
}
Easiest solution answer is this.
Assume, each alphabet in the example is a single digit.
Empty Array {} : Expected value = 0
{a}: Expected value = a
{a,b}: Expected value = 10*a + b
{a,b,c}: Expected value = 10 * (10*a + b) + c
Code: Test this is online java compiler IDE
public class ConvertDigitArrayToNumber {
public static void main(String[] args) {
int[] arr = {3, 2, 0, 5, 3};
int value = 0;
for (int i = 0; i < arr.length; i++) {
value = (10*value) + arr[i];
}
System.out.println(value);
}
}
This is actually simpler and better solution than the other ones.
Only simple multiplication and addition (No powers).
No String conversions
I need help with creating a VeryLargeInteger class similar to the BigInteger however, as part of my assignment I am not allowed to use BigInteger. I have started off by storing large numbers as strings and then converting them to int[] to perform mathematical functions with them. The problem I am running into is working with two different sized arrays such as:
int[] a = {1, 2, 3, 4, 5} // represents 12,345
int[] b = {1, 2, 4} //represents 124
When I add them I get:
int[] c = {2, 4, 7, 4, 5}
instead of
int[] c = {1, 2, 4, 6, 9}
This is a little messy.
import java.util.Arrays;
public class VeryLargeInteger
{
int[] test, test2;
String temp, temp2;
int size;
VeryLargeInteger(int[] input)
{
int[] test = input;
System.out.println(Arrays.toString(test));
}
VeryLargeInteger(long input1)
{
long input = input1;
temp = Long.toString(input1);
test = convert(temp);
System.out.println(Arrays.toString(test));
}
VeryLargeInteger(String input1)
{
temp = input1;
test = convert(input1);
System.out.println(Arrays.toString(test));
}
public static int[] convert(String input)
{
int [] array = new int[input.length()];
for (int i = 0; i < input.length(); i++)
{
int value = input.charAt(i) - '0';
array[i] = value;
}
return array;
}
VeryLargeInteger add(VeryLargeInteger other)
{
int max = Math.max(this.temp.length(), other.temp.length());
int[] result = new int[max];
int carry = 0;
for (int i = 0; i < max; ++i)
{
int a = i < this.test[i] ? this.test[this.test[i] - i -1] : 0;
int b = i < other.test[i] ? other.test[other.test[i] - i -1] : 0;
int sum = a + b + carry;
carry = sum / 10;
sum -= carry;
result[result.length - i - 1] = sum;
}
VeryLargeInteger added = new VeryLargeInteger(result);
return added;
}
/*
VeryLargeInteger sub(VeryLargeInteger other)
{
}
VeryLargeInteger mul(VeryLargeInteger other)
{
}
VeryLargeInteger div(VeryLargeInteger other)
{
}
VeryLargeInteger mod(VeryLargeInteger other)
{
}
static String toString(VeryLargeInteger other)
{
}*/
public static void main(String[] args)
{
VeryLargeInteger a = new VeryLargeInteger(1050L);
VeryLargeInteger b = new VeryLargeInteger("121123");
VeryLargeInteger c = a.add(b);
}
}
You could pad the second array to get them to add properly:
int[] a = {1, 2, 3, 4, 5};
int[] b = {0, 0, 1, 2, 4};
Then, if your add method compares a[0] to b[0] and so forth, you will get {1, 2, 4, 6, 9}.
An important note I would like to make is this: You are not using the benefit of integers. Integers are 32 bits long, which are 32 digits in base 2. Now, you are using an integers as 1 digit in base 10. By doing this, you are only using 0.0000002% of the memory in a useful way. Use the full range that integers support. The point would be to make an array of integers, but where each integer effectively represents 32 bits of the actual number you want to hold. Adding them together then just goes component-wise, and take care of overflow by using a carry.
To fix the problem as you are facing it now: Align your arrays right. Do not add leading zeroes as Mike Koch suggests, but align them properly, by basically accessing the array elements from back to front, instead of from front to back, as you are doing now. By looking at your code, you have attempted that, but you are having trouble with ArrayIndexOutOfBoundsExceptions I guess. Access both components of the array like this:
int[] number0 = ...;
int[] number1 = ...;
int max = Math.max(number0.length + number1.length) + 1;
int[] result = new int[max];
int carry = 0;
for (int i = 0; i < max; ++i)
{
int c0 = i < number0.length ? number0[number0.length - i - 1] : 0;
int c1 = i < number1.length ? number1[number1.length - i - 1] : 0;
int sum = c0 + c1 + carry;
carry = sum / 10;
sum -= carry;
result[result.length - i - 1] = sum;
}
i have integer a = 4 and array b 7,8,9,4,3,4,4,2,1
i have to write a method that removes int ALL a from array b
desired result 7,8,9,3,2,1
This is what I have so far,
public static int[] removeTwo (int x, int[] array3)
{
int counter = 0;
boolean[] barray = new boolean [array3.length];
for (int k=0; k<array3.length; k++)
{
barray[k] = (x == array3[k]);
counter++;
}
int[] array4 = new int [array3.length - counter];
int num = 0;
for (int j=0; j<array3.length; j++)
{
if(barray[j] == false)
{
array4[num] = array3[j];
num++;
}
}
return array4;
I get this error
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at Utility.removeTwo(Utility.java:50)
at Utility.main(Utility.java:18)
Java Result: 1
Any help would be much appreciated!
The error stems from this for loop:
for (int k=0; k<array3.length; k++)
{
barray[k] = (x == array3[k]);
counter++;
}
when you create int[] array4 = new int [array3.length - counter]; you are creating an array with size 0. You should only increment the counter if the item is the desired item to remove:
for (int k=0; k<array3.length; k++)
{
boolean b = (x == array3[k]);
barray[k] = b;
if(b) {
counter++;
}
}
To answer your question in the comment, the method should be called and can be checked like this:
public static void main(String[] args) {
int[] array3 = {0,1,3,2,3,0,3,1};
int x = 3;
int[] result = removeTwo(x, array3);
for (int n : result) {
System.out.print(""+ n + " ");
}
}
On this line:
int[] array4 = new int [array3.length - counter];
You create an array with size 0, as counter is equal to array3.length at this point.
This means that you cannot access any index in that array.
You are creating
int[] array4 = new int [array3.length - counter];// 0 length array.
you can't have 0th index there. At least length should 1 to have 0th index.
BTW my suggestion, it is better to use List. Then you can do this easy.
Really an Array is the wrong tool for the job, since quite apart from anything else you will end up with stray values at the end that you cannot remove. Just use an ArrayList and that provides a removeAll() method to do what you need. If you really need arrays you can even do:
List<Integer> list = new ArrayList(Arrays.asList(array))
list.removeAll(4);
array = list.toArray();
(Exact method names/parameters may need tweaking as that is all from memory).
the simplest way is to work with a second array where you put in the correct values
something likte that
public static int[] removeTwo (int x, int[] array3)
{
int counter = 0;
int[] array4 = new int[array3.lenght];
for (int i = 0; i < array3.lenght; i ++) {
if(array3[i] == x){
array4[counter] = array3[i];
}
}
return array4;
}
anoterh way is to remove the x calue from the array3 and shift the values behind forward
The best way to remove element from array is to use List with Iterator. Try,
Integer[] array = {7, 8, 9, 4, 3, 4, 4, 2, 1};
List<Integer> list = new ArrayList(Arrays.asList(array));
for(Iterator<Integer> it=list.iterator();it.hasNext();){
if(it.next()==4){
it.remove();
}
}
I need to generate an array int[] randomNumbers of random numbers with no duplicates. To do this, I make an array with all values that can go into randomNumbers, then use a random number generator to pick one out of the list, check if it's already in randomNumbers, and if it isn't, put it in randomNumbers.
(I want numbers between 1 and max, not 0 and max-1)
To be able to use Arrays.sort(int[]), the list needs to be sorted. So I use a third array, with the same values as randomNumbers called sortedNumbers, and sort it on every iteration:
public int[] uniqueRandom(int max, int numRequired) {
if (max < numRequired) {
numRequired = max;
}
int[] randomNumbers = new int[numRequired];
int[] sortedNumbers = new int[numRequired];
int[] sequentialNumbers = new int[max];
for (int i = 1; i < max; i++) {
sequentialNumbers[i] = i;
System.out.println(sequentialNumbers[i]);
}
int p = 0;
while (p < numRequired) {
int j = r.nextInt(max) + 1;
System.out.println("J:" + j);
if (Arrays.binarySearch(sortedNumbers, j) >= 0) {
System.out.println("Number Found:" + Arrays.binarySearch(randomNumbers, j));
} else {
randomNumbers[p] = j;
sortedNumbers[p] = j;
Arrays.sort(sortedNumbers);
for (int i = 0; i < randomNumbers.length; i++) {
System.out.println("rNum[" + i + "]:" + randomNumbers[i]);
}
System.out.println("\n");
for (int i = 0; i < randomNumbers.length; i++) {
System.out.println("sNum[" + i + "]:" + sortedNumbers[i]);
}
p++;
}
}
return randomNumbers;
}
My issue is that I'm getting an output where sortedNumbers is overwriting values. For uniqueRandom(5, 5) the output is:
J:2
rNum[0]:2
rNum[1]:0
rNum[2]:0
rNum[3]:0
rNum[4]:0
sNum[0]:0
sNum[1]:0
sNum[2]:0
sNum[3]:0
sNum[4]:2
J:2 // 2 already in the list, try again
J:2
J:4
rNum[0]:2
rNum[1]:4
rNum[2]:0
rNum[3]:0
rNum[4]:0
sNum[0]:0
sNum[1]:0
sNum[2]:0
sNum[3]:2
sNum[4]:4
J:5
rNum[0]:2
rNum[1]:4
rNum[2]:5
rNum[3]:0
rNum[4]:0
sNum[0]:0
sNum[1]:0
sNum[2]:2
sNum[3]:4
sNum[4]:5
J:2
J:3
rNum[0]:2
rNum[1]:4
rNum[2]:5
rNum[3]:3
rNum[4]:0
sNum[0]:0 // Should be:
sNum[1]:0 // 2
sNum[2]:2 // 3
sNum[3]:3 // 4
sNum[4]:5 // 5
J:4
rNum[0]:2
rNum[1]:4
rNum[2]:5
rNum[3]:3
rNum[4]:4
sNum[0]:0
sNum[1]:0
sNum[2]:2
sNum[3]:3
sNum[4]:4
So you can see the issue. I'm using java 1.7, and have no idea why it's doing this!
To solve your problem I would use a Set, that assure us to have unique results.
Below snipest will generate array with required number of unique integers.
Set<Integer> uniqueNumbers = new HashSet<Integer>();
Random r = new Random();
while(uniqueNumbers.size() < numRequired) {
uniqueNumbers.add(r.nextInt(maxRandom) + 1);
}
return uniqueNumbers.toArray(new Integer[0]);
You are putting the new number into both arrays using the same index. Your rNum array is filling from top down, but the sorted array is not: Each time you sort it, the new value moves down in the array and the zeros are always at the top. I think you could fix it by always putting the new number in the first position of the sorted array:
sortedNumbers[0] = j;
When you input J=5
the sortedNUm[] is
sNum[0]:0
sNum[1]:0
sNum[2]:2
sNum[3]:4
sNum[4]:5
next when you input J=3 (your p=3)
after
sortedNumbers[p] = j;
your sNUM[3] which is 4 is replaced by 3
hence after sorting it becomes
sNum[0]:0 // Should be:
sNum[1]:0 // 2
sNum[2]:2 // 3
sNum[3]:3 // 4
sNum[4]:5 // 5
notice 4 is not present
I suggest you initialize the array to -1 or 0 and add the variables at the start of array
like
sortedNumbers[0]=j;
and after Arrays.sort(); the first position will always be empty to add more numbers
While it doesn't answer the question, here is an alternative which is O(n) and work well provided max is not large.
public static void main(String[] args) {
System.out.println(Arrays.toString(uniqueRandom(20, 10)));
}
public static int[] uniqueRandom(int max, int numRequired) {
int[] possible = new int[max];
int[] ret = new int[numRequired];
for (int i = 0; i < max; i++)
possible[i] = i + 1;
Random r = new Random();
int numLeft = max;
for (int i = 0; i < numRequired; i++) {
int idx = r.nextInt(numLeft);
ret[i] = possible[idx];
if (idx < --numLeft)
possible[idx] = possible[numLeft];
}
return ret;
}
prints
[4, 10, 12, 19, 8, 3, 15, 1, 14, 7]
What I am trying to say is that perhaps you could make it simpler.
There are a few issues with your code:
since you only increment p when the new number j doesn't already exist in the arrays, that, combined with the fact that you sort the sortedArray first leads to the value actually being placed sometimes over an existing value (which shifted position due to the sort)
I don't understand what's the use of the sequentialNumbers array...
Here's an example which should work:
private static Random r = new Random();
public static void main(String[] args) {
System.out.println(Arrays.toString(uniqueRandom(10, 10)));
}
public static int[] uniqueRandom(int max, int numRequired) {
if (max < numRequired) {
numRequired = max;
}
int[] randomNumbers = new int[numRequired];
int[] sortedNumbers = new int[numRequired];
Arrays.sort(sortedNumbers);
int p = 0;
while (p < numRequired) {
int j = r.nextInt(max) + 1;
if(Arrays.binarySearch(sortedNumbers, j)<0) {
randomNumbers[p] = j;
System.arraycopy(randomNumbers, 0, sortedNumbers, 0, randomNumbers.length);
Arrays.sort(sortedNumbers);
p++;
}
}
return randomNumbers;
}