I need to create random numbers that will run through an array without duplicates.
The problem is the duplication and I can't use any of the utils except the Scanner for input (teacher instruction) like java.util.Random or java.util.ArrayList.
I use a function called random that my teacher wrote to us and the function newNum(int num) is where I need what I have asked - random numbers.
package exercise;
import java.util.Scanner;
public class Bingo {
static int size = 10;
static int num;
static int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
private static Scanner sc;
public static void main(String[] args) {
System.out.print("Press Enter to start: ");
sc = new Scanner(System.in);
sc.nextLine();
System.out.println("");
// int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
// int[] tempArray = arr;
int num = random();
// int num = sc.nextInt();
// System.out.println(num);
while (size > 0) {
System.out.println(num);
size--;
newArray(num);
num = random();
newNum(num);
// System.out.println(num);
}
}
public static int random() {
int max = 10;
double r = Math.random();
int num = (int) (r * max + 1);
return num;
}
public static int newNum(int num) {
// Here should go the code for the function for getting only new
// random number without duplications
return num;
}
public static int newArray(int num) {
int[] tempArray = arr;
arr = new int[size];
int x = num - 1;
for (int i = 0; i < x; i++) {
if (i < size) {
arr[i] = tempArray[i];
}
}
for (int i = num; i < size; i++) {
if (i < size) {
int y = i - 1;
arr[y] = tempArray[i];
} else {
int a = size - 1;
arr[a] = tempArray[size];
}
}
return num;
}
}
First of all, you write that you can't use shuffle, but that doesn't mean that you are prohibited from implementing it. It's not that hard, actually.
If you want to do that, use the Fisher-Yates shuffle, as found on wikipedia: https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle
(by the way, since you are going to school, if you find such a wikipedia article - or any other article - to be interesting, you might propose to your teacher to hold an essay on that, easily earned additional good grade)
Of course, this assumes that you have a vector to shuffle, which is inefficient for large vectors ("random numbers within zero to one billion"). In this case you might want to go with:
To find n random numbers within 0..m
1. Initialize an empty list of already used random numbers which is ordered, called "numbers"
2. for i = 0..n-1
2a: r = random(0..m-i) (uniform distribution)
2b: for every entry in numbers
if entry <= r, r++
2c: sort r into numbers (maybe by using a single bubblesort step)
This shifts the complexity from the size of the vector as before to the amount of generated numbers.
Explanation: In every iteration, we want to find an unused number. We find the rth unused number (there is a range of 0..m-i of unused numbers in iteration i). Now we only need to find out which number is the rth unused one. This is done by the inner iteration. We need numbers to be sorted because of this example: current state: numbers = {5, 1}, r = 4. r < 5 -> do nothing. r >= 1 -> r++. End up with r = 5, got a double entry.
If sorting is not wanted for the resulting list, simply go with two lists.
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'm trying to take an array of any length of ints, and concatenate it into a single number without adding it up. For instance, if I have an array that goes as follows
[ 1, 7, 12, 16, 3, 8]
I want to have a variable that will equal 17121638, not equal 47.
I'm supposed to take a input of string and change it into an int without using Interger.parseInt() on the whole input itself.
This is my current attempt:
public static String toNum(String input) {
String [] charArray = new String [input.length()];
int [] parsedInput = new int [input.length()];
for(int i; i < input.length(); i++){
charArray[i] = input.substring(i);
}
for(int c; c < charArray.length; c++){
parsedInput[c] = Integer.parseInt(charArray[c]);
}
Try this:
int[] nums = { 1, 7, 12, 16, 3, 8 };
StringBuilder strBigNum = new StringBuilder();
for (int n : nums)
strBigNum.append(n);
long bigNum = 0;
long factor = 1;
for (int i = strBigNum.length()-1; i >= 0; i--) {
bigNum += Character.digit(strBigNum.charAt(i), 10) * factor;
factor *= 10;
}
Now the bigNum variable contains the value 17121638; in this case it was easier to work with strings. Be careful, if the input array is too big (or the numbers are too big) the resulting value won't fit in a long.
Try to think about how the index of the left most number relates to it's power of 10 in the final number that you're trying to achieve. For example: having an array of [1, 2, 3, 4] should produce the integer 1234. How does the base 10 power of 1000 relate to the length of the array and the index of 1?
I phrase this as a question because I get the sense that this is a homework problem for school .
Variant of Óscar López's solution that doesn't use any parsing (as the question requested):
public class BigNum {
public static void main(String[] args) {
int[] nums = {1, 7, 12, 16, 3, 8};
System.out.println(concatNums(nums));
}
public static long concatNums(int[] nums) {
long result = 0;
long multiplier = 1;
for (int i = nums.length; i > 0; --i) {
int num = nums[i - 1];
while (num != 0) {
result += multiplier * (num % 10);
num /= 10;
multiplier *= 10;
}
}
return result;
}
}
This won't work correctly if the array contains a 0. If that's important, let me know and I'll tweak the algorithm to accommodate it.
Add the numbers together by the join method - that will give you a string and then convert it into a number by the Number function.
you can simply run:
var arr = [ 1, 7, 12, 16, 3, 8];
var num = arr.join('');
Number(num);
First, you want to return an int -- not a String!
Second -- technically -- you could use Integer.valueOf(s); which returns an Integer object with the exact value that .parseInt() would've returned... though I suspect that this would be considered "cheating."
Thirdly, I think this will help you along your way: http://nadeausoftware.com/node/97
Particularly the section titled:
Parsing an integer from a string with custom code
You can use StringBuilder to append each int num from numbers (int[]).
StringBuilder sb = new StringBuilder();
for (int num : numbers) {
sb.append(num);
}
return sb.toString();
one line solution
String str = Arrays.toString(a).replaceAll("\\D", "");
Alright, here's another approach. Although this is similar to another answer, this one can handle some zeros. Just math, no use of Integer.parseInt:
public static int intsToInt(int[] input) {
int total = 0;
int multiplier = 1;
for (int i=input.length-1; i > -1; i--) {
if (input[i] == 0) {
multiplier *= Math.pow(10, String.valueOf(input[i]).length());
}
else {
total += input[i]*multiplier;
multiplier *= Math.pow(10, String.valueOf(input[i]).length());
}
}
return total;
}
public static void main(String[] args) {
int[] ints = {1, 7, 12, 0, 16, 3, 8};
out.println(digitsToInt(ints));
out.println(intsToInt(ints));
}
Here is a simple implementation. Correct if it's wrong please (I'm a beginner).
int concatArray(int[] array){
int sum = 0;
int len = array.length-1;
for(int i=0; i<array.length;i++){
sum += (Math.pow(10, len) * array[i]);
len--;
}
return sum;
}
I'm having a problem finding the sum of all of the integers in an array in Java. I cannot find any useful method in the Math class for this.
In java-8 you can use streams:
int[] a = {10,20,30,40,50};
int sum = IntStream.of(a).sum();
System.out.println("The sum is " + sum);
Output:
The sum is 150.
It's in the package java.util.stream
import java.util.stream.*;
If you're using Java 8, the Arrays class provides a stream(int[] array) method which returns a sequential IntStream with the specified int array. It has also been overloaded for double and long arrays.
int [] arr = {1,2,3,4};
int sum = Arrays.stream(arr).sum(); //prints 10
It also provides a method
stream(int[] array, int startInclusive, int endExclusive) which permits you to take a specified range of the array (which can be useful) :
int sum = Arrays.stream(new int []{1,2,3,4}, 0, 2).sum(); //prints 3
Finally, it can take an array of type T. So you can per example have a String which contains numbers as an input and if you want to sum them just do :
int sum = Arrays.stream("1 2 3 4".split("\\s+")).mapToInt(Integer::parseInt).sum();
This is one of those simple things that doesn't (AFAIK) exist in the standard Java API. It's easy enough to write your own.
Other answers are perfectly fine, but here's one with some for-each syntactic sugar.
int someArray[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int sum = 0;
for (int i : someArray)
sum += i;
Also, an example of array summation is even shown in the Java 7 Language Specification. The example is from Section 10.4 - Array Access.
class Gauss {
public static void main(String[] args) {
int[] ia = new int[101];
for (int i = 0; i < ia.length; i++) ia[i] = i;
int sum = 0;
for (int e : ia) sum += e;
System.out.println(sum);
}
}
You can't. Other languages have some methods for this like array_sum() in PHP, but Java doesn't.
Just..
int[] numbers = {1,2,3,4};
int sum = 0;
for( int i : numbers) {
sum += i;
}
System.out.println(sum);
In Apache Math : There is StatUtils.sum(double[] arr)
The only point I would add to previous solutions is that I would use a long to accumulate the total to avoid any overflow of value.
int[] someArray = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, Integer.MAX_VALUE};
long sum = 0;
for (int i : someArray)
sum += i;
int sum = 0;
for (int i = 0; i < yourArray.length; i++)
{
sum = sum + yourArray[i];
}
In Java 8
Code:
int[] array = new int[]{1,2,3,4,5};
int sum = IntStream.of(array).reduce( 0,(a, b) -> a + b);
System.out.println("The summation of array is " + sum);
System.out.println("Another way to find summation :" + IntStream.of(array).sum());
Output:
The summation of array is 15
Another way to find summation :15
Explanation:
In Java 8, you can use reduction concept to do your addition.
Read all about Reduction
A bit surprised to see None of the above answers considers it can be multiple times faster using a thread pool. Here, parallel uses a fork-join thread pool and automatically break the stream in multiple parts and run them parallel and then merge. If you just remember the following line of code you can use it many places.
So the award for the fastest short and sweet code goes to -
int[] nums = {1,2,3};
int sum = Arrays.stream(nums).parallel().reduce(0, (a,b)-> a+b);
Lets say you want to do sum of squares , then Arrays.stream(nums).parallel().map(x->x*x).reduce(0, (a,b)-> a+b). Idea is you can still perform reduce , without map .
int sum = 0;
for (int i = 0; i < myArray.length; i++)
sum += myArray[i];
}
IMHO a sum function would seem a good fit to extend the Arrays class where fill, sort, search, copy, & equals live. There are a lot of handy methods hiding in the javadocs so it is a fair question when porting Fortran to java to ask before rolling our own helper method. Search through the huge javadoc index for "sum", "add" and any other keyword you might think of. You might suspect certainly someone has already done this for primitive types int, float, double, Integer, Float, Double? No matter how simple, it is always good to check. Keep the code as simple as possible and don't reinvent the wheel.
It depends. How many numbers are you adding? Testing many of the above suggestions:
import java.text.NumberFormat;
import java.util.Arrays;
import java.util.Locale;
public class Main {
public static final NumberFormat FORMAT = NumberFormat.getInstance(Locale.US);
public static long sumParallel(int[] array) {
final long start = System.nanoTime();
int sum = Arrays.stream(array).parallel().reduce(0,(a,b)-> a + b);
final long end = System.nanoTime();
System.out.println(sum);
return end - start;
}
public static long sumStream(int[] array) {
final long start = System.nanoTime();
int sum = Arrays.stream(array).reduce(0,(a,b)-> a + b);
final long end = System.nanoTime();
System.out.println(sum);
return end - start;
}
public static long sumLoop(int[] array) {
final long start = System.nanoTime();
int sum = 0;
for (int v: array) {
sum += v;
}
final long end = System.nanoTime();
System.out.println(sum);
return end - start;
}
public static long sumArray(int[] array) {
final long start = System.nanoTime();
int sum = Arrays.stream(array) .sum();
final long end = System.nanoTime();
System.out.println(sum);
return end - start;
}
public static long sumStat(int[] array) {
final long start = System.nanoTime();
int sum = 0;
final long end = System.nanoTime();
System.out.println(sum);
return end - start;
}
public static void test(int[] nums) {
System.out.println("------");
System.out.println(FORMAT.format(nums.length) + " numbers");
long p = sumParallel(nums);
System.out.println("parallel " + FORMAT.format(p));
long s = sumStream(nums);
System.out.println("stream " + FORMAT.format(s));
long ar = sumArray(nums);
System.out.println("arrays " + FORMAT.format(ar));
long lp = sumLoop(nums);
System.out.println("loop " + FORMAT.format(lp));
}
public static void testNumbers(int howmany) {
int[] nums = new int[howmany];
for (int i =0; i < nums.length;i++) {
nums[i] = (i + 1)%100;
}
test(nums);
}
public static void main(String[] args) {
testNumbers(3);
testNumbers(300);
testNumbers(3000);
testNumbers(30000);
testNumbers(300000);
testNumbers(3000000);
testNumbers(30000000);
testNumbers(300000000);
}
}
I found, using an 8 core, 16 G Ubuntu18 machine, the loop was fastest for smaller values and the parallel for larger. But of course it would depend on the hardware you're running:
------
3 numbers
6
parallel 4,575,234
6
stream 209,849
6
arrays 251,173
6
loop 576
------
300 numbers
14850
parallel 671,428
14850
stream 73,469
14850
arrays 71,207
14850
loop 4,958
------
3,000 numbers
148500
parallel 393,112
148500
stream 306,240
148500
arrays 335,795
148500
loop 47,804
------
30,000 numbers
1485000
parallel 794,223
1485000
stream 1,046,927
1485000
arrays 366,400
1485000
loop 459,456
------
300,000 numbers
14850000
parallel 4,715,590
14850000
stream 1,369,509
14850000
arrays 1,296,287
14850000
loop 1,327,592
------
3,000,000 numbers
148500000
parallel 3,996,803
148500000
stream 13,426,933
148500000
arrays 13,228,364
148500000
loop 1,137,424
------
30,000,000 numbers
1485000000
parallel 32,894,414
1485000000
stream 131,924,691
1485000000
arrays 131,689,921
1485000000
loop 9,607,527
------
300,000,000 numbers
1965098112
parallel 338,552,816
1965098112
stream 1,318,649,742
1965098112
arrays 1,308,043,340
1965098112
loop 98,986,436
I like this method personally. My code style is a little weird.
public static int sumOf(int... integers) {
int total = 0;
for (int i = 0; i < integers.length; total += integers[i++]);
return total;
}
Pretty easy to use in code:
int[] numbers = { 1, 2, 3, 4, 5 };
sumOf(1);
sumOf(1, 2, 3);
sumOf(numbers);
I use this:
public static long sum(int[] i_arr)
{
long sum;
int i;
for(sum= 0, i= i_arr.length - 1; 0 <= i; sum+= i_arr[i--]);
return sum;
}
You have to roll your own.
You start with a total of 0. Then you consider for every integer in the array, add it to a total. Then when you're out of integers, you have the sum.
If there were no integers, then the total is 0.
There are two things to learn from this exercise :
You need to iterate through the elements of the array somehow - you can do this with a for loop or a while loop.
You need to store the result of the summation in an accumulator. For this, you need to create a variable.
int accumulator = 0;
for(int i = 0; i < myArray.length; i++) {
accumulator += myArray[i];
}
You can make your code look better like this:
public void someMethod(){
List<Integer> numbers = new ArrayList<Integer>();
numbers.addAll(db.findNumbers());
...
System.out.println("Result is " + sumOfNumbers(numbers));
}
private int sumOfNumbers(List<Integer> numbers){
int sum = 0;
for (Integer i : numbers){
sum += i;
}
return sum;
}
Use below logic:
static int sum()
{
int sum = 0; // initialize sum
int i;
// Iterate through all elements summing them up
for (i = 0; i < arr.length; i++)
sum += arr[i];
return sum;
}
I have the right solution for your problem if you specifically have an array of type double, then this method can be used to calculate the sum of its elements. also, it using math class
import org.apache.commons.math3.stat.StatUtils;
public class ArraySum {
public static void main(String[] args) {
double[] array = { 10, 4, 17, 33, -2, 14 };
int sum = (int)StatUtils.sum(array);
System.out.println("Sum of array elements is: " + sum);
}
}
There is a sum() method in underscore-java library.
Code example:
import com.github.underscore.U;
public class Main {
public static void main(String[] args) {
int sum = U.sum(java.util.Arrays.asList(1, 2, 3, 4));
System.out.println(sum);
// -> 10
}
}
There is no 'method in a math class' for such thing. Its not like its a square root function or something like that.
You just need to have a variable for the sum and loop through the array adding each value you find to the sum.
class Addition {
public static void main() {
int arr[]={5,10,15,20,25,30}; //Declaration and Initialization of an Array
int sum=0; //To find the sum of array elements
for(int i:arr) {
sum += i;
}
System.out.println("The sum is :"+sum);//To display the sum
}
}
We may use user defined function. At first initialize sum variable equal to zero. Then traverse the array and add element with sum . Then update the sum variable.
Code Snippet :
import java.util.*;
import java.lang.*;
import java.io.*;
class Sum
{
public static int sum(int arr[])
{
int sum=0;
for(int i=0; i<arr.length; i++)
{
sum += arr[i];
}
return sum;
}
public static void main (String[] args)
{
int arr[] = {1, 2, 3, 4, 5};
int total = sum(arr);
System.out.printf("%d", total);
}
}
/**
* Sum of all elements from 1 to 1000
*/
final int sum = Stream.iterate(1, n -> n + 1).limit(1000).mapToInt(el -> el).sum();
Most of the answers here are using inbuilt functions-
Here is my answer if you want to know the whole logic behind this ques:
import java.util.*;
public class SumOfArray {
public static void main(String[] args){
Scanner inp = new Scanner(System.in);
int n = inp.nextInt();
int[] arr = new int[n];
for(int i = 0; i < n; i++){
arr[i] = inp.nextInt();
}
System.out.println("The sum of the array is :" + sum(arr));
}
static int sum(int[] arr){
int sum = 0;
for (int a = 0; a < arr.length; a++){
sum = sum + arr[a];
}
return sum;
}
}
public class Num1
{
public static void main ()
{
//Declaration and Initialization
int a[]={10,20,30,40,50}
//To find the sum of array elements
int sum=0;
for(int i=0;i<a.length;i++)
{
sum=sum+i;
}
//To display the sum
System.out.println("The sum is :"+sum);
}
}
public class AddDemo {
public static void main(String[] args) {
ArrayList <Integer>A = new ArrayList<Integer>();
Scanner S = new Scanner(System.in);
System.out.println("Enter the Numbers: ");
for(int i=0; i<5; i++){
A.add(S.nextInt());
}
System.out.println("You have entered: "+A);
int Sum = 0;
for(int i=0; i<A.size(); i++){
Sum = Sum + A.get(i);
}
System.out.println("The Sum of Entered List is: "+Sum);
}
}
As of Java 8 The use of lambda expressions have become available.
See this:
int[] nums = /** Your Array **/;
Compact:
int sum = 0;
Arrays.asList(nums).stream().forEach(each -> {
sum += each;
});
Prefer:
int sum = 0;
ArrayList<Integer> list = new ArrayList<Integer>();
for (int each : nums) { //refer back to original array
list.add(each); //there are faster operations…
}
list.stream().forEach(each -> {
sum += each;
});
Return or print sum.