How to re-arrange the number [duplicate] - java

This question already has answers here:
Maximum number that can be formed from the given digits
(2 answers)
Closed 7 years ago.
I have a number which I need to re-arrange to find the largest number. As an example input number is 355 so for this number I need to find the largest number which can be formed by re-arranging the digits. So for 355, various combination can be possible after re-arranging -
355, 535 and 553
So here 553 is the largest number and that's what I need to return. Basically given an input, I need to find the largest number which can be formed by re-arranging the numbers.
How should I go ahead and solve this problem?
So far I am able to do shuffle the numbers like this:
public static void main(String[] args) {
//generate random number
int number = 355;
//put each digit in an element of a list
List<Character> numberList = new ArrayList<Character>();
for (char c : String.valueOf(number).toCharArray()) {
numberList.add(c);
}
//shuffle
Collections.shuffle(numberList);
//output
String shuffledNumber = "";
for (Character c : numberList) {
shuffledNumber += c;
}
System.out.println(shuffledNumber);
}
But I am confuse how can I find the largest number given an input after rearranging the numbers.

If you need to rearrange the numbers so that, if we read it from left to write, it should be largest number among all the arrangements,
then it's simple, you just need to sort the number in descending order.
Try this code :
public static void main(String args[]) {
//generate random number
int number = 355;
String numStr = number + "";
char[] numCharArr = numStr.toCharArray();
int[] numArr = new int[numStr.length()];
for(int i = 0 ; i < numCharArr.length ; i ++) {
numArr[i] = Integer.parseInt(numCharArr[i] + "");
}
// Sort in descending order
for(int i = 0 ; i < numArr.length ; i ++) {
for(int j = 0 ; j < i ; j ++) {
if(numArr[i] > numArr[j]) {
// swap
int temp = numArr[i];
numArr[i] = numArr[j];
numArr[j] = temp;
}
}
}
String largestNumber = "";
for(int i : numArr) {
largestNumber += i;
}
System.out.println("The largest number is : " + largestNumber);
}

Unless you actually need to create all the combinations, I wouldn't bother.
You can actually do it using arithmetic, but in this case it's probably easier in terms of strings
naive algorithm:
source number = number.toString()
target number = ""
While source number is not empty
d = remove biggest number from source number
target number += d
You can then convert target number back to an int if required.
Another approach would be count the number of 9s and append that many 9s to the result. Repeat for 8s, then 7s, then 6s...

Related

Finding a missing number in an array that uses a random generator

I'm trying to make it so the random generator doesn't produce the same number in the array. I also don't know how to find the missing number. I tried the if statement, and it works, but it repeats.
The question problem "find the missing number in an array. The array consists of numbers from 1 to 10 in random sequence. One of the numbers in the array is absent and you must find it. Use one loop. An example {5,6,9,4,1,2,8,3,10} – the result will be: 7
import java.util.Random;
public class questionThree
{
public static void main(String[] args)
{
int [] numbers = new int [10];
Random rand = new Random();
int numArr = 1;
for (int i = 1; i < 9; i++)
{
int n = rand.nextInt(10) + 1;
numbers[i] = n;
if (numbers[i] == numArr)
numArr++;
else
System.out.println("The missing num is " +numArr);
}
for(int val : numbers)
{
System.out.println("The next value is " +
val);
}
}
}
Assumption:
Numbers are unique
Only one entry is missing
number ranges from [1, 10] inclusive.
Solution
return 55 - Arrays.stream(yourArr).sum();
This is with O(n) runtime and O(1) space complexity.
If we break assumptions.
You will need O(N) space to figure out which entries are missing. To hold the marker either you can use List or BitSet or 2 bytes and manage it by hand. N is here the random number generation width.
There seems to be no mention on using a temporary data structure.
You can either sort the array and find the missing number, OR use a temporary sorted data structure.
You are conflating two things: the generator algorithm for a problem case and the solution to the problem itself. You shouldn't be interested in how the "random array" is generated at all (unless you want to test your solution). What you certainly shouldn't do is try to write the code that solves the problem in the method that generates the sample array.
If you want a randomly sorted list, Collections.shuffle will handle that for you. If you want a list without a single element, just generate a list of all elements 1..n and then remove the randomly selected number (then shuffle). So much for the generator. As for the solution, there are many methods to do it, someone already suggested using the sum, that's a perfectly valid solution.
It seems you are looking for this code.
import java.util.Random;
public class questionThree
{
public static void main(String[] args)
{
int [] numbers = new int [9];
Random rand = new Random();
int numArr = 1;
numbers[0] = rand.nextInt(10) + 1;
for (int i = 1; i < 9; i++)
{
int n = rand.nextInt(10) + 1;
numbers[i] = n;
int x =0;
while(x<i){
if(numbers[x] == n){
i = i-1;
break;
}
x++;
}
}
int sum = 0;
for (int val : numbers) {
sum = sum + val;
System.out.println("The next value is " +
val);
}
System.out.println("Missing number is " + (55 - sum));
}
}
Output is -
The next value is 6
The next value is 2
The next value is 8
The next value is 1
The next value is 4
The next value is 3
The next value is 9
The next value is 10
The next value is 7
Missing number is 5
I am generating 9 Numbers between(1 to 10) randomly and then printing which number is missing among them.
You have two options:
The way I did it in the code below: setting the random array without repeating the same number. And then a for loop from 1 to 10 and check if that number exist in the array.
You know that 1 + 2 + 3 + 2 + 3 + 4 + 5 + 6 + 8 + 9 + 10 = 55. So if you get the sum of all ints in the array you will have 55 - (the missing number). So now the missing number = 55 - sum.
This is the code I did (first method):
import java.util.Random;
public class questionThree
{
public static void main(String[] args)
{
int [] numbers = new int [9];
Random rand = new Random();
for (int i = 0; i <9; i++)
{
//setting random numbers in array without repeating
numbers[i] = checkForANumber(rand, numbers, i);
}
//print all nums
for(int val: numbers) System.out.println("The next value is " +
val);
for (int i = 1; i <= 10; i++)
{
boolean exist = false;
for(int val : numbers)
{
if(val == i){
exist = true;
}
}
if (!exist) System.out.println("The missing number is " + i);
}
}
private static int checkForANumber(Random rand, int[] numbers, int i){
int n = rand.nextInt(10) + 1;
boolean NumAlreadyExist = false;
for(int j = 0; j < i; j++)
{
if(numbers[j] == n){
NumAlreadyExist = true;
}
}
if(NumAlreadyExist) return checkForANumber(rand, numbers, i);
else return n;
}
}
Output:
The next value is 9
The next value is 3
The next value is 8
The next value is 6
The next value is 7
The next value is 10
The next value is 4
The next value is 2
The next value is 1
The missing number is 5

Trouble printing out pattern in array

I am trying to get the number of pattern to printout from the array but under my number of pattern no pairs were printed out this is an example of what i am trying to get
(Array: 2 7 2 3 1 5 7 4 3 6
Number of patterns: 3)
but I do not know what to write from beyond number of patterns
The code:
public class FindIt {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
int Sum = 0;
int[] InsertNumbers = new int[10];
System.out.println("Sample output #1:");
System.out.print("Array: ");
for(int i = 0; i < 10; i++)
{
InsertNumbers[i]=(int)(Math.random()*10)+1;
System.out.print(InsertNumbers[i] + " ");
}
System.out.println("");
System.out.print("Array: ");
for(int i = 0; i < 5; i++)
{
ComputePattern(InsertNumbers, Sum);
System.out.print(InsertNumbers[i] + " ");
}
System.out.println("");
System.out.print("Number of patterns: ");
}
public static void ComputePattern(int[] InsertNumbers, int Sum)
{
for(int i = 0; i < 2; i++)
{
InsertNumbers[i] = Sum;
Sum = Sum + Sum;
}
}
}
It is quite hard to understand your code but here is what I can tell you.
You have managed to get to ask the user input but I feel that the following would be better.
Instead, try having two arrays, one which the user can input 10 integers, and the other array with the sum of the pairs, hence an array containing 5 integers.
With the help of a For Loop and a formula, you can use it to get the 2 consecutive values. The first formula being x*2, the second being (x*2)+1.
With x being 0 in the for loop, and loop it for 5 times.
Afterwards, you get the values of the x*2 and the (x*2)+1 in the array, and sum them together.
Then with the sum, you can then use it to calculate the count of patterns.
Suggestion : Try to be consistent with your println and print. It is quite confusing and I am not quite sure as to why you have set println for certain text and print for the rest.
No patterns were printed because you have no print statements after you print Number of patterns.

find all possible sums of a list without target

im trying to find all possible sums from a list.
The list consist of ints that are user inputed, and the number of inputs are decided by the user aswell( see code).
What i want is to check all possible sums without having a target.
The reason i dont want a target is because the program is then later suposed to chose one of these sums which is closest to 1000.
So if i was to pick 1000 as target i wouldnt be able to get say 1001.
Example input from user:
5 // user chose 5 numbers.
500,400,300,50,60 // numbers chosen by user.
Output would then be:
1010 // because 500+400+60+50= 1010 and closest to 1000.
Next example could be:
3 // user chose 3 numbers.
1,2,3 // numbers chosen by user.
Output would then be:
6 // because 1+2+3 = 6.
So back to my original question, how do is this done? Everytime i search "all possible sums of a list of ints" or simular i get with a target and it dosent work in this example.
public static void main(String[] args) throws Exception {
int bästaVikt;
int räknare = 0;
Scanner sc = new Scanner(System.in);
ArrayList<Integer> mylist = new ArrayList<Integer>();
int s;
s = sc.nextInt();
int ans = 0;
for(int i = 1; i <= s; i++) {
mylist.add(sc.nextInt());
}
for(int i = 0; i < mylist.size(); i++) {
Collections.sort(mylist);
System.out.print(mylist.get(i));
System.out.print(" ");
}
}
Half actual code half pseudo code, hope it helps.
input // the array that holds all numbers than the user input
int n = input.length();
ArrayList<Integer> combinations = new ArrayList<Integer>();
int totalSum = input.sum(); // sum of all the values the user input
ArrayList<Integer> allSums = new ArrayList<Ingeter>();
for(int i = 0; i < n; i++){
combinations = combine(i) // find all possible combinations of i integers in the input array; you can surely find code for retrieving combinations in another thread
foreach combination in combinations{
allSums.add(totalSum - combination.sum())
}
combinations = new ArrayList<Integer>(); // clear the combinations arraylist
}
return allSums; //all possible sums
minDistanceToNumber = absolute(allSums.get(0) - 1000); // define a function "int absolute(int value)" which will multiply value by -1 if it is less than 0 and return it or just return it if it is bigger than 0
minNumber = allSums.get(0); // this will hold the number which has the minimum distance to 1000, as in the example above
for each sum in allSums
if(absolute(sum - 1000) < minDistanceToNumber){
minDistanceToNumber = absolute(sum - 1000);
minNumber = sum;
}
}
return minNumber;

Create all possible binary permutations with a given number of ones in Java

I want to find all possible binary permutations with a given number of ones in Java:
x is the desired number of ones in each sequence
n is the desired length of each sequence
For an example:
x=2, n=4
Output: 1100, 0011, 1010, 1001, 0101, 0110
I'm searching for an elegant and fast way to do this. Can you help me?
I've tested eboix solution in Print list of binary permutations but it is unfortunately too slow because the algorithm in this example is searching for all 2^n binary permutations.
I want to find sequences with a length of 50 or 100.
First of all, you're missing 0110 as an output case.
It's fairly intuitive that there are n choose x possibilities. You're finding all valid arrangements of x identical items among n total slots. So you can find the total number of sequences in O(1).
As a hint, try simply finding all permutations of the bitstring consisting of x ones followed n - x zeros.
To specifically address the problem, try creating a recursive algorithm that decides at every ith iteration to either include 1 or 0. If 1 is included, you need to decrement the count of 1's available for the rest of the string.
Actually, there may be an elegant way, but no fast way to do this. The number of string permutations is given by the binomial coefficient (see https://en.wikipedia.org/wiki/Binomial_coefficient). For example, x=10, n= 50 gives over 10 million different strings.
Here is just a basic version that will generate your desired output. Please work on it to make it more accurate/efficient -
This will not generate all the combinations, but you will get the idea of how to do it. Off course, for all the possible combinations generated by this, you will have to generate all the other possible combinations.
public class Test {
static int iter = 0;
public static void main(String args[]){
int n = 50;
int x = 5;
byte[] perms = new byte[n];
for(int i=0; i<x; i++){
perms[i] = 1;
}
print(perms);
for(int j=x-1; j>=0; j--){
for(int i=1; i<(n/2-j); i++){
iter++;
swap(perms, j, i);
}
}
}
public static void swap(byte[] perms, int pos, int by){
byte val = perms[pos+by];
perms[pos+by] = perms[pos];
perms[pos] = val;
print(perms);
val = perms[pos+by];
perms[pos+by] = perms[pos];
perms[pos] = val;
}
public static void print(byte[] perms){
System.out.println("iter = "+iter);
for(int i=0; i<perms.length; i++){
System.out.print(perms[i]);
}
System.out.println();
for(int i=perms.length-1; i>=0; i--){
System.out.print(perms[i]);
}
System.out.println();
}
}
Another inspiration for you. A dirty version which works. It allocates extra array space (you should adjust size) and uses String Set at the end to remove duplicates.
public static void main(String[] args) {
int x = 2;
int n = 4;
Set<BigInteger> result = new LinkedHashSet<>();
for (int j = x; j > 0; j--) {
Set<BigInteger> a = new LinkedHashSet<>();
for (int i = 0; i < n - j + 1; i++) {
if (j == x) {
a.add(BigInteger.ZERO.flipBit(i));
} else {
for (BigInteger num : result) {
if (num != null && !num.testBit(i) && (i >= (n - j) || num.getLowestSetBit() >= i-1))
a.add(num.setBit(i));
}
}
}
result = a;
}
String zeros = new String(new char[n]).replace("\0", "0");
for (BigInteger i : result) {
String binary = i.toString(2);
System.out.println(zeros.substring(0, n - binary.length()) + binary);
}
}
EDIT: changed the primitives version to use BigInteger instead to support larger n,x values.

Finding specific number in prime number array

I'm trying to find prime numbers with a specific condition in Java.
The challenge is to show all the prime numbers (under 100.000) which contain a '3' four times.
I already have a code which shows all the prime numbers under 100.000, but I can't seem to figure out how to count the ones that contain the number '3' four times.
I can however count all the prime numbers.
Can someone help me with this?
Here's the code I have, where am I going to put the numbers into strings?
package Proeftentamen;
import java.util.regex.*;
/**
*
* #author Stefan
*/
public class Vraag_6 {
/// priemgetallen waar 4x een 3 in voor komt???? wtf...
public static void main(String[] args) {
boolean[] lijst = new boolean[1000000]; // hoeveelheid getallen
vularray(lijst);
lijst = zeef(lijst);
drukaf(lijst);
}
public static void vularray(boolean[] lijst) {
for (int i = 2; i < lijst.length; i++) {
lijst[i] = true;
}
}
public static boolean[] zeef(boolean[] lijst) {
for (int i = 2; i < lijst.length / 2; i++) {
if (lijst[i]) {
for (int j = 2 * i; j < lijst.length; j += i) {
lijst[j] = false;
}
}
}
return lijst;
}
public static void drukaf(boolean[] lijst) {
int count = 0;
for (int i = 2; i < lijst.length; i++) {
if (lijst[i] == true) {
System.out.println(i + " " + lijst[i]);
count++;
}
}
System.out.println("Aantal priemgetallen: " + count);
}
}
This question really sounds like a homework, so you should write down what you have come up with and what you tried so far.
There are a lot of ways to count numbers. Just to give you a clue, you can use the reminder operation (in Java - %):
56 % 10 = 6
25 % 5 = 0
So, when you divide by 10 and use a reminder operation you can get the last digit of your number. Now use a loop and counter and you'll be fine.
Another option (very ugly, so don't really use it :) ) - to turn your number into a String and iterate (loop) over its characters.
Hope this helps and good luck!
This code generate 50 permutation of numbers that has four '3' in it's digits
so check each number that is prime or not
public void generateNumbers() {
StringBuilder s = new StringBuilder();
s.append("3333");
for (int i = 0; i < 5; i++) {
for (int j = 0; j <= 9; j++) {
if (j%3==0) continue;
s.insert(i,String.valueOf(j));
int number=Integer.parseInt(s.toString());
System.out.println(number);
s.delete(i,i+1);
}
}
}
Iterate across each prime number.
For each prime number, convert it to a string using the Integer.toString(int) static method.
With this string, iterate over every character (use a for loop and the non-static method String.charAt(int index)) and count the number of times that method returns '3'. (The character '3', not the String "3").
Unless you have some other purpose for an array of prime-number Strings, don't bother to store them anywhere outside the loop.
Please refer below code to validate all such prime numbers.
void getPrimes(int num ,int frequency,char digit) {
int count = 0;
String number=Integer.toString(num);
for (int i = 0; i < number.length(); i++) {
if (count < frequency) {
if (number.charAt(i) == digit)
count++;
}
if (count == frequency)
{
System.out.println(number);
return ;
}
}
}
Using the primes function from an exercise on the Sieve of Eratosthenes, as well as the digits and filter functions from the Standard Prelude, this Scheme expression finds the seven solutions:
(filter
(lambda (n)
(= (length
(filter
(lambda (d) (= d 3))
(digits n)))
4))
(primes 100000))
The outer filter runs over all the primes less than 100000 and applies the test of the outer lambda to each. The inner filter computes the digits of each prime number and keeps only the 3s, then the length function counts them and the equality predicate keeps only those that have 4 3s. You can run the program and see the solution at http://codepad.org/e98fow2u.
you only have at most five digits, four of which must be 3. So what can you say about the remaining digit?
It's not hard to just write out the resulting numbers by hand, and then test each one for primality. Since there are no more than 50 numbers to test, even the simplest trial division by odds will do.
But if you want to generate the numbers programmatically, just do it with 5 loops: add 10,000 to 03333 9 times; add 1,000 to 30333 9 times; add 100 to 33033 9 times; etc. In C++:
int results[50];
int n_res = 0;
int a[5] = {13333, 31333, 33133, 33313, 33331};
for( int i=0, d=10000; i<5; ++i, d/=10)
for( int j=1; j<9; ++j, a[i]+=d )
if( is_prime(a[i]) )
results[n_res++] = a[i];

Categories