I am very new to Java and I am trying to iterate over an array of integers and get all multiples of 10. What I get with my code is the elements in the array printed 100 times since that is the length of the array. I know it is very basic but I just can't figure the problem out. This is what I have:
import java.util.Arrays;
public class ArrayThings {
public static void main(String[] args) {
int[] myFirstArray = new int[100];
for (int i = 0; i < myFirstArray.length; i++) {
myFirstArray[i] = i;
}
for (int i : myFirstArray) {
if (i % 10 == 0) {
myFirstArray[i] = i;
} else {
i++;
}
System.out.println(Arrays.toString(myFirstArray));
}
}
}
I think that is what you want to do :
public class ArrayThings {
public static void main(String[] args) {
int[] myFirstArray = new int[100];
// array generation
for (int i = 0; i < myFirstArray.length; i++) {
myFirstArray[i] = i;
}
// printing multiples of 10
for (int i = 0; i < myFirstArray.length; i++) {
if (i % 10 == 0 && i != 0) {
System.out.println(myFirstArray[i]);
}
}
}
}
In Java-8 you can do it like below:
int result[] = IntStream.range(1, 100).filter(e -> e%10==0).toArray();
System.out.println(Arrays.toString(result));
Why do you need an array for printing multiples of 10? You could simply do:
public class ArrayThings{
public static void main(String[]args){
for(int i=0; i<101; i++) {
if(i%10==0 && i != 0){
System.out.println(i);
}
}
}}
P.S. you are printing whole array and not that particular element, that's why you are getting a wrong output.
You should move your print statement outside of the for loop, that is what is causing it to print 100 times.
Also your current code seems to do absolutely nothing. You are checking the modulo of i, then setting the value of myFirstArray to that value of i. The current value of myFirstArray at i, is already equal to i, as initialized in the first loop.
This should work
import java.util.Arrays;
public class ArrayThings {
public static void main(String[] args) {
int[] myFirstArray = new int[100];
int[] myMultiplesArray = new int[9];
for (int i = 0; i < myFirstArray.length; i++) {
myFirstArray[i] = i;
}
int j = 0;
for (int i : myFirstArray) {
if (i % 10 == 0) {
myMultiplesArray[j] = i;
j++;
}
}
System.out.println(Arrays.toString(myMultiplesArray));
}
}
Related
my intend is to use simplest java (array and loops) to generate random numbers without duplicate...but the output turns out to be 10 repeating numbers, and I cannot figure out why.
Here is my code:
int[] number = new int[10];
int count = 0;
int num;
while (count < number.length) {
num = r.nextInt(21);
boolean repeat = false;
do {
for (int i=0; i<number.length; i++) {
if (num == number[i]) {
repeat = true;
} else if (num != number[i] && i == count) {
number[count] = num;
count++;
repeat = true;
}
}
} while (!repeat);
}
for (int j = 0; j < number.length; j++) {
System.out.print(number[j] + " ");
}
How about you use a Set instead? If you also want to keep track of the order of insertion you can use a LinkedHashSet.
Random r = new Random();
Set<Integer> uniqueNumbers = new HashSet<>();
while (uniqueNumbers.size()<10){
uniqueNumbers.add(r.nextInt(21));
}
for (Integer i : uniqueNumbers){
System.out.print(i+" ");
}
A Set in java is like an Array or an ArrayList except it handles duplicates for you. It will only add the Integer to the set if it doesn't already exist in the set. The class Set has similar methods to the Array that you can utilize. For example Set.size() is equivalent to the Array.length and Set.add(Integer) is semi-equivalent to Array[index] = value. Sets do not keep track of insertion order so they do not have an index. It is a very powerful tool in Java once you learn about it. ;)
Hope this helps!
You need to break out of the for loop if either of the conditions are met.
int[] number = new int[10];
int count=0;
int num;
Random r = new Random();
while(count<number.length){
num = r.nextInt(21);
boolean repeat=false;
do{
for(int i=0; i<number.length; i++){
if(num==number[i]){
repeat=true;
break;
}
else if(i==count){
number[count]=num;
count++;
repeat=true;
break;
}
}
}while(!repeat);
}
for(int j=0;j<number.length;j++){
System.out.print(number[j]+" ");
}
This will make YOUR code work but #gonzo proposed a better solution.
Your code will break the while loop under the condition: num == number[i].
This means that if the pseudo-generated number is equal to that positions value (the default int in java is 0), then the code will end execution.
On the second conditional, the expression num != number[i] is always true (otherwise the code would have entered the previous if), but, on the first run, when i == count (or i=0, and count=0) the repeat=true breaks the loop, and nothing else would happen, rendering the output something such as
0 0 0 0 0 0...
Try this:
int[] number = new int[10];
java.util.Random r = new java.util.Random();
for(int i=0; i<number.length; i++){
boolean repeat=false;
do{
repeat=false;
int num = r.nextInt(21);
for(int j=0; j<number.length; j++){
if(number[j]==num){
repeat=true;
}
}
if(!repeat) number[i]=num;
}while(repeat);
}
for (int k = 0; k < number.length; k++) {
System.out.print(number[k] + " ");
}
System.out.println();
Test it here.
I believe the problem is much easier to solve. You could use a List to check if the number has been generated or not (uniqueness). Here is a working block of code.
int count=0;
int num;
Random r = new Random();
List<Integer> numbers = new ArrayList<Integer>();
while (count<10) {
num = r.nextInt(21);
if(!numbers.contains(num) ) {
numbers.add(num);
count++;
}
}
for(int j=0;j<10;j++){
System.out.print(numbers.get(j)+" ");
}
}
Let's start with the most simple approach, putting 10 random - potentially duplicated - numbers into an array:
public class NonUniqueRandoms
{
public static void main(String[] args)
{
int[] number = new int[10];
int count = 0;
while (count < number.length) {
// Use ThreadLocalRandom so this is a contained compilable unit
number[count++] = ThreadLocalRandom.current().nextInt(21);
}
for (int j = 0; j < number.length; j++) {
System.out.println(number[j]);
}
}
}
So that gets you most of the way there, the only thing you know have to do is pick a number and check your array:
public class UniqueRandoms
{
public static void main(String[] args)
{
int[] number = new int[10];
int count = 0;
while (count < number.length) {
// Use ThreadLocalRandom so this is a contained compilable unit
int candidate = ThreadLocalRandom.current().nextInt(21);
// Is candidate in our array already?
boolean exists = false;
for (int i = 0; i < count; i++) {
if (number[i] == candidate) {
exists = true;
break;
}
}
// We didn't find it, so we're good to add it to the array
if (!exists) {
number[count++] = candidate;
}
}
for (int j = 0; j < number.length; j++) {
System.out.println(number[j]);
}
}
}
The problem is with your inner 'for' loop. Once the program finds a unique integer, it adds the integer to the array and then increments the count. On the next loop iteration, the new integer will be added again because (num != number[i] && i == count), eventually filling up the array with the same integer. The for loop needs to exit after adding the unique integer the first time.
But if we look at the construction more deeply, we see that the inner for loop is entirely unnecessary.
See the code below.
import java.util.*;
public class RandomDemo {
public static void main( String args[] ){
// create random object
Random r = new Random();
int[] number = new int[10];
int count = 0;
int num;
while (count < number.length) {
num = r.nextInt(21);
boolean repeat = false;
int i=0;
do {
if (num == number[i]) {
repeat = true;
} else if (num != number[i] && i == count) {
number[count] = num;
count++;
repeat = true;
}
i++;
} while (!repeat && i < number.length);
}
for (int j = 0; j < number.length; j++) {
System.out.print(number[j] + " ");
}
}
}
This would be my approach.
import java.util.Random;
public class uniquerandom {
public static void main(String[] args) {
Random rnd = new Random();
int qask[]=new int[10];
int it,i,t=0,in,flag;
for(it=0;;it++)
{
i=rnd.nextInt(11);
flag=0;
for(in=0;in<qask.length;in++)
{
if(i==qask[in])
{
flag=1;
break;
}
}
if(flag!=1)
{
qask[t++]=i;
}
if(t==10)
break;
}
for(it=0;it<qask.length;it++)
System.out.println(qask[it]);
}}
public String pickStringElement(ArrayList list, int... howMany) {
int counter = howMany.length > 0 ? howMany[0] : 1;
String returnString = "";
ArrayList previousVal = new ArrayList()
for (int i = 1; i <= counter; i++) {
Random rand = new Random()
for(int j=1; j <=list.size(); j++){
int newRand = rand.nextInt(list.size())
if (!previousVal.contains(newRand)){
previousVal.add(newRand)
returnString = returnString + (i>1 ? ", " + list.get(newRand) :list.get(newRand))
break
}
}
}
return returnString;
}
Create simple method and call it where you require-
private List<Integer> q_list = new ArrayList<>(); //declare list integer type
private void checkList(int size)
{
position = getRandom(list.size()); //generating random value less than size
if(q_list.contains(position)) { // check if list contains position
checkList(size); /// if it contains call checkList method again
}
else
{
q_list.add(position); // else add the position in the list
playAnimation(tv_questions, 0, list.get(position).getQuestion()); // task you want to perform after getting value
}
}
for getting random value this method is being called-
public static int getRandom(int max){
return (int) (Math.random()*max);
}
Hi I'm trying to figure out an efficient way to get all permutations of a string but also allowing repetition of characters. (for example for string "ab" the output would be "aa, bb, ba, ab")
I have my code working correctly without repetition but I'm not sure how to go about modifying it to allow repetition of characters and only seem to find ways of doing this without repetition of characters.
Here is the code that I have:
public static ArrayList<String> permutationsUnique(String word) {
ArrayList<String> result = new ArrayList<String>();
if (word.length() == 0) {
result.add(word);
return result;
} else {
for (int i = 0; i < word.length(); i++) {
String shorter = word.substring(0, i) + word.substring(i + 1);
ArrayList<String> shorterPermutations = permutationsUnique(shorter);
for (String s : shorterPermutations) {
result.add(word.charAt(i) + s);
}
}
return result;
}
}
I would really appreciate if some one can guide me in the right direction.
Thank you
I know this question was asked long back, but I just worked on one java program to have permutation of integers with repetitions allowed. I am putting my code here, in case if someone needs it.
This program can generate permutations for specified length. i.e.
For integers 1,2 and lengthOfSinglePermutation = 2, output should be
11
21
12
22
For integers 1,2 and lengthOfSinglePermutation = 3, output should be
111
211
121
221
112
212
122
222
Hope this helps.
public class PermutationsWithRepetitions {
public static void main(String[] args) {
int[] input = { 1, 2 };
int lengthOfSinglePermutation = 3;
// we need to check number of unique values in array
Set<Integer> arrValues = new HashSet<Integer>();
for (int i : input) {
arrValues.add(i);
}
int noOfUniqueValues = arrValues.size();
int[] indexes = new int[lengthOfSinglePermutation];
int totalPermutations = (int) Math.pow(noOfUniqueValues, lengthOfSinglePermutation);
for (int i = 0; i < totalPermutations; i++) {
for (int j = 0; j < lengthOfSinglePermutation; j++) {
System.out.print(input[indexes[j]]);
}
System.out.println();
for (int j = 0; j < lengthOfSinglePermutation; j++) {
if (indexes[j] >= noOfUniqueValues - 1) {
indexes[j] = 0;
}
else {
indexes[j]++;
break;
}
}
}
}
}
Sorry, my previous answer was somewhat unrelated. DELETED. This will definitely work :-
static void Recur(String prefix, String str)
{
if(prefix.length()==str.length())
{
System.out.println(prefix); return;
}
for(int i=0; i<str.length(); i++)
Recur(prefix+str.charAt(i),str);
}
public static void main (String[] args)
{
String str = "AB";
}
The output is
AA
AB
BA
BB
I have another solution with a char array, but it works for any kind of array. Here, instead of print the characters (or whatever data type you want to), you can add your list and append the elements to it.
static void permuteAll(char [] a)
{
permuteArray(a, new char[a.length], 0);
}
static void permuteArray(char [] a, char [] s, int j)
{
if(j == a.length)
{
System.out.println(new String(s));
return;
}
for(int i = 0; i < a.length; i++)
{
s[j] = a[i];
permuteArray(a, s, j+1);
}
}
public static void main(String args[]){
String str="ABC";
int maxSize =3;
char[] chars = str.toCharArray();
getCombination(chars, maxSize);
}
static void getCombination(char[]chars, int maxSize){
for(int i=0; i<chars.length; i++){
combination(String.valueOf(chars[i]),chars,maxSize);
}
}
static void combination(String prefix,char[] chars, int maxSize) {
if(prefix.length()>=maxSize){
System.out.println(prefix);
}
else {
for(int j= 0; j<chars.length;j++)
{
String newPrefix =prefix.concat(String.valueOf(chars[j]));
combination(newPrefix,chars, maxSize);
}
}
}
I'm trying to write a program that displays all prime numbers below the one entered by the user. The only requirement is that it must be multi threaded. This is my first time using Java and multiple threads. Can you help? It compiles, but the output is strange. Maybe it's an address?
import java.util.Scanner;
import java.util.Arrays;
public class prime {
public static void main(String[] args){
// get number from user
System.out.println("Enter a number: ");
Scanner keyboard = new Scanner(System.in);
int num = keyboard.nextInt();
RunPrime runprime1 = new RunPrime (num);
runprime1.start();
Thread.yield();
runprime1.SmallerPrimeNumbers();
}
}
class RunPrime extends Thread {
private int given_number;
RunPrime (int n) {
given_number = n;
}
public void SmallerPrimeNumbers() {
int count = 0;
for (int i = 0; i <= given_number; i++) {
if (CheckPrime(i)) {
count++;
}
}
for (int i = 0; i < count; i++) {
for (int j = 2; j <= given_number; j++) {
if (CheckPrime(j)) {
number[i] = j;
}
}
}
System.out.println(number);
}
public static boolean CheckPrime (int n) {
for (int i=2 ; i<n ; i++) {
if (n%i == 0)
return false;
}
return true;
}
}
Your SmallerPrimeNumbers() function has a second for-loop that doesn't look necessary. You're also assigning and printing the variable number that wasn't declared anywhere (this is probably what's causing you trouble). Since you're only printing them and not saving them, you can simplify the function like this:
public void SmallerPrimeNumbers() {
int count = 0;
for (int i = 0; i <= given_number; i++) {
if (CheckPrime(i)) {
System.out.println(i);
}
}
}
This question already has answers here:
Algorithm to find next greater permutation of a given string
(14 answers)
Closed 8 years ago.
I am currently making a Permutation class for java. One of my methods for this class, is advance(), where the computer will take the array, and then display all permutations of the array.
So, for example, if I give the array {0,1,2,3,4,5}, or the number 6, it should give me from 012345.....543210.
Here is the code I have so far:
import java.util.*;
public class Permutation extends java.lang.Object {
public static int[] permutation;
public static int[] firstPerm;
public static int[] lastPerm;
public static int length;
public static int count;
public static void main(String[] args) {
// TODO Auto-generated method stub
}
public Permutation(int n) {
length = n;
permutation = new int[length];
for (int i = 0; i < length; i++) {
permutation[i] = i;
}
}
public Permutation(int[] perm) {
length = perm.length;
permutation = new int[length];
boolean[] t = new boolean[length];
for (int i = 0; i < length; i++) {
if (perm[i] < 0 || perm[i] >= length) {
throw new IllegalArgumentException("INVALID ELEMENT");
}
if (t[perm[i]]) {
throw new IllegalArgumentException("DUPLICATE VALUES");
}
t[perm[i]] = true;
permutation[i] = perm[i];
}
}
public void advance() {
}
public int getElement(int i) {
return permutation[i];
}
public boolean isFirstPerm() {
firstPerm = new int[permutation.length];
for (int i = 0; i < permutation.length; i++) {
firstPerm[i] = permutation[i];
}
Arrays.sort(firstPerm);
if (Arrays.equals(firstPerm, permutation)) {
return true;
} else {
return false;
}
}
public boolean isLastPerm() {
lastPerm = new int[firstPerm.length];
for (int i = 0; i < firstPerm.length; i++) {
lastPerm[i] = firstPerm[firstPerm.length - 1 - i];
}
if (Arrays.equals(permutation, lastPerm)) {
return true;
} else {
return false;
}
}
public static Permutation randomPermutation(int n) {
if (n <= 0) {
throw new IllegalArgumentException("INVALID NUMBER");
} else {
length = n;
permutation = new int[length];
for (int i = 0; i < length; i++) {
permutation[i] = i;
}
Collections.shuffle(Arrays.asList(permutation));
return new Permutation(permutation);
}
}
public void reset() {
Arrays.sort(permutation);
}
public boolean isValid(int[] perm) {
boolean[] t = new boolean[length];
for (int i = 0; i < length; i++) {
if (perm[i] < 0 || perm[i] >= length) {
return false;
}
if (t[perm[i]]) {
return false;
}
}
return true;
}
public int[] toArray() {
return permutation;
}
public String toString() {
StringBuffer result = new StringBuffer();
for (int i = 0; i < permutation.length; i++) {
result.append(permutation[i]);
}
String perms = result.toString();
return perms;
}
public static long totalPermutations(int n) {
count = 1;
for (int i = 1; i <= n; i++) {
count = count * i;
}
return count;
}
}
As you can see, the advance() method is the last thing I need to do, but I can't figure it out. Any help will be grand.
One of methods you can employ is:
Fix the first element and recursively find all permutations of rest of the array.
Then change the first elements by trying each of the remaining elements.
Base case for recursion is when you travel the entire length to get 0 element array. Then, either print it or add it to a List which you can return at the end.
public void advance() {
int[] temp = Arrays.copyOf(arr, arr.length);
printAll(0,temp);
}
private void printAll(int index,int[] temp) {
if(index==n) { //base case..the end of array
//print array temp here
}
else {
for(int i=index;i<n;i++) {//change the first element stepwise
swap(temp,index,i);//swap to change
printAll(index+1, temp);//call recursively
swap(temp,index,i);//swap again to backtrack
}
}
}
private void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
The way your code looks right now, it sounds like you want to be able to control the permutation class externally, rather than only supporting the one operation of printing all the permutations in order.
Here's an example of how to calculate a permutation.
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Test {
public static int factorial(int x) {
int f = 1;
while (x > 1) {
f = f * x;
x--;
}
return f;
}
public static List<Integer> permute(List<Integer> list, int iteration) {
if (list.size() <= 1) return list;
int fact = factorial(list.size() - 1);
int first = iteration / fact;
List<Integer> copy = new ArrayList<Integer>(list);
Integer head = copy.remove(first);
int remainder = iteration % fact;
List<Integer> tail = permute(copy, remainder);
tail.add(0, head);
return tail;
}
public static void main(String[] args) throws IOException {
List<Integer> list = Arrays.asList(4, 5, 6, 7);
for (int i = 0; i < 24; i++) {
System.out.println(permute(list, i));
}
}
}
Just to elaborate, the idea behind the code is to map an integer (iteration) to a particular permutation (ordering of the list). We're treating it as a base-n representation of the permutation where each digit represents which element of the set goes in that position of the resulting permutation.
For example, if we're permuting (1, 2, 3, 4) then we know there are 4! permutations, and that "1" will be the first element in 3! of them, and it will be followed by all permutations of (2, 3, 4). Of those 3! permutations of the new set (2, 3, 4), "2" will be the first element in 2! of them, etc.
That's why we're using / and % to calculate which element goes into each position of the resulting permutation.
This should work, and it's pretty compact, only drawback is that it is recursive:
private static permutation(int x) {
if (x < 1) {
throw new IllegalArgumentException(x);
}
LinkedList<Integer> numbers = new LinkedList<>();
for (int i = 0; i < x; i++) {
numbers.add(i);
}
printPermutations(numbers, new LinkedList<>());
}
private static void printPermutations(
LinkedList<Integer> numbers, LinkedList<Integer> heads) {
int size = numbers.size();
for (int i = 0; i < size; i++) {
int n = numbers.getFirst();
numbers.removeFirst();
heads.add(n);
printPermutations(numbers, heads);
numbers.add(n);
heads.removeLast();
}
if (numbers.isEmpty()) {
String sep = "";
for (int n : heads) {
System.out.print(sep + n);
sep = " ";
}
System.out.println("");
}
}
hey guys,
right i have an array of 50 random integers and i have to check if any of them are the same,
here is my code so far it only checks ajacent indexs
for (int i =0; i < 50; i++)
{
System.out.print("Student" + i + ": " );
customers[i] = (int)((Math.random()*10000)%10+1);
System.out.print(" " +customers[i]+ "\n");
if( duplicate == customers[i])
{
System.out.println("yup");
}
duplicate = customers[i];
}
Sort the array first. Then you can check just the next index. If it's ever the same, break.
Okay, I hate ridiculous limitations. If you want, you can do it like this without using a sort:
import java.util.ArrayList;
import java.lang.Math;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<Integer>();
Integer currentValue = 0;
int i = 0;
int limit = 20;
for(i = 0; i < limit; i++) {
list.add((int)(Math.random() * 100));
}
for(i = 0; i < limit; i++) {
currentValue = list.get(i);
list.set(i, -1);
if(list.contains(currentValue)) {
System.out.println("yup:" + currentValue);
return;
} else {
list.set(i, currentValue);
}
}
System.out.println("No duplicates!");
return;
}
}
Is it efficient? No.
Does it work? Yes.
I think, if you have to just use if/for functions, you have to make two loops:
for (int i =0; i < 50; i++)
{
customers[i] = (int)((Math.random()*10000)%10+1);
for ( int j = 0; j < i; j++)
{
if( customers[j] == customers[i])
{
// duplicated entry. do what you want
System.out.println("yup");
}
}
}
You could use Arrays.sort (see more at http://www.exampledepot.com/egs/java.util/coll_SortArray.html) to sort your data, and then check for duplicates.
You use value 0-10 so you can save your value in boolean array and it that way verify if this is duplicate or not:
boolean[] checker = new boolean[11];
for (int i =0; i < 50; i++) {
customers[i] = (int)((Math.random()*10000)%10+1);
if (checker[customers[i]]) {
System.out.println("yup"); //duplication
} else {
checker[customers[i]] = true;
}
}
You can use the below code if you are working with Integer array:
public class DuplicateInteger {
private static int countDuplicate;
public static int[] getDuplicateIntegers(int[] integerArray){
int duplicateIntegers[] = new int[integerArray.length];
countDuplicate = 0;
for(int i=0;i<integerArray.length;i++){
for(int j=i+1;j<integerArray.length;j++){
int replicaTest = 0;
if(integerArray[i]==integerArray[j]){
for(int k=0;k<countDuplicate;k++){
if(duplicateIntegers[k]==integerArray[i]){
replicaTest = 1;
}
}
if(replicaTest==0){
duplicateIntegers[countDuplicate] = integerArray[i];
countDuplicate++;
}
}
}
}
return duplicateIntegers;
}
public static void printDuplicateIntegers(int[] duplicateIntegers){
System.out.println("Duplicate Integers:");
System.out.println("-------------------");
for(int i=0;i<countDuplicate;i++){
System.out.println(duplicateIntegers[i]);
}
}
public static void main(String[] args){
int numberArray[] = {1, 2, 3, 4, 5, 6, 7, 1, 3, 5, 7};
printDuplicateIntegers(getDuplicateIntegers(numberArray));
}
}