I have a string array
"Ben", "Jim", "Ken"
how can I print the above array 3 times to look like this:
"Ben", "Jim", "Ken"
"Jim", "Ben", "Ken"
"Ken", "Jim", "Ben"
I just want each item in the initial array to appear as the first element. The order the other items appear does not matter.
more examples
Input
"a","b","c","d"
output
"a","b","c","d"
"b","a","c","d"
"c","b","a","d"
"d","a","c","d"
Method signature
public void printArray(String[] s){
}
Rather than give you straight-up code, I'm going to try and explain the theory/mathematics for this problem.
The two easiest ways I can come up with to solve this problem is to either
Cycle through all the elements
Pick an element and list the rest
The first method would require you to iterate through the indices and then iterate through all the elements in the array and loop back to the beginning when necessary, terminating when you return to the original element.
The second method would require you to iterate through the indices, print original element, then proceed to iterate through the array from the beginning, skipping the original element.
As you can see, both these methods require two loops (as you are iterating through the array twice)
In pseudo code, the first method could be written as:
for (i = array_start; i < array_end; i++) {
print array_element[i]
for (j = i + 1; j != i; j++) {
if (j is_larger_than array_end) {
set j equal to array_start
}
print array_element[j]
}
}
In pseudo code, the second method could be written as:
for (i = array_start; i < array_end; i++) {
print array_element[i]
for (j = array_start; j < array_end; j++) {
if (j is_not_equal_to i) {
print array_element[j]
}
}
}
public void printArray(String[] s){
for (int i = 0; i < s.length; i++) {
System.out.print("\"" + s[i] + "\",");
for (int j = 0; j < s.length; j++) {
if (j != i) {
System.out.print("\"" + s[j] + "\",");
}
}
System.out.println();
}
}
This sounds like a homework question so while I feel I shouldn't answer it, I'll give a simple hint. You are looking for an algorithm which will give all permutations (combinations) of the "for loop index" of the elements not the elements themselves. so if you have three elements a,b,c them the index is 0,1,2 and all we need is a way to generate permutations of 0,1,2 so this leads to a common math problem with a very simple math formula.
See here: https://cbpowell.wordpress.com/2009/11/14/permutations-vs-combinations-how-to-calculate-arrangements/
for(int i=0;i<s.length;i++){
for(int j=i;j<s.length+i;j++) {
System.out.print(s[j%(s.length)]);
}
System.out.println();
}
Using mod is approppiate for this question. The indexes of the printed values for your first example are like this;
0 1 2
1 2 0
2 0 1
so if you write them like the following and take mod of length of the array (3 in this case) you will reach solution.
0 1 2
1 2 3
2 3 4
Related
I'm tasked with a perplexing problem. I'm attempting to turn an unsorted array with duplicates into a sorted array without duplicates. I used the selection sort to accomplish the first part:
public static void SelectionSort(int [] list) {
int i = 0;
int j = 0;
int indexSmallest = 0;
int temp = 0;
for (i = 0; i < list.length - 1; i++) {
indexSmallest = i;
for (j = i + 1; j < list.length; j++) {
if (list[j] < list[indexSmallest]) {
indexSmallest = j;
}
}
temp = list[i];
list[i] = list[indexSmallest];
list[indexSmallest] = temp;
}
}
The sorting isn't the issue - I'm having a hard time removing the duplicates from the array. The solution that I have in my head is to create a secondary array, and iterate through the input to check if that element exists in the second array, if not, add it to the array. I'm stuck because I'm not able to create another array. So, what gives? How do I solve this problem if I can't create an array to cross-reference and check if I have unique values? I'm not able to use any built-in Java functions.
There is no need of second array ... think about it this way ...
The easiest way is to convert it to set / hashset and then sort it in an array.
But if the sets are forbidden, the only possibility is to put the duplicates at the end, cut them out and then sort the rest.
[1,8,1,2,3,5,3] in this array, you need to remove elements that are duplicates ... okay ... so what if we did something like this ... we will "split" this array into "sorted", "unsorted and duplicates" and "duplicates". Now what we will do is that we will go through the array using 2 pointers. One at the first element (lets call it "i") and at the last element (lets call it "j") ... now we will go while i < j and we will swap everytime, when we will find a duplicate. This way, you will get everything not duplicate before "i" and everything that is dupicate after "i" ... now you will sort the array from index 0 do index i and you should have sorted array and you will just cut out the duplicates ...
ofc., this will require the time complexity, to be able to handle O(n*logn) / O(n^2) ...
There is a way how to do it in a O(n), and that can be done by that .. you will use 2 pointers ...
one will be pointing at current sorted array, where you have no duplicates and toher will be pointing to a place, where are yet unswapped integers ... (you need to remember the highest number found)
to be more specific:
[1,2,2,3,3,4,5]
i = 0, j = 1
- fine
i = 1, j = 2
- duplicate ... soo ..
jumping to duplicate position
i = 2, j = 3 (array[3] != 2, so we will swap)
current array -> [1,2,3,2,3,4,5]
^ ^
i j
i = 3, j = 4
- highest_number > 3 is not true (2 < 3), so skipping
i = 3, j = 5
- highest_number > 3 is not true (3 < 3), so skipping
i = 3, j = 6
- swapping
... etc
and you should end up with something like this
[1,2,3,4,5,2,3]
^ ^
i j
now you can cut the array at i, so you will get `[1,2,3,4,5,\0]` (in C syntax) ... so basically `[1,2,3,4,5]`
So I'm currently stuck on one of my programs. I have to use a for loop to remove all elements in the ArrayList that's greater than 4. I have no idea how to do this. Someone help?
Here is my code:
import java.util.ArrayList;
public class P4E
{
public static void main( String args[] )
{
ArrayList<String> universities = new ArrayList<String>();
universities.add("Princeton");
universities.add("UCSD");
universities.add("UCLA");
universities.add("SDSU");
universities.add("UCI");
int size = universities.size();
System.out.println( "The size of the ArrayList is: " + size);
System.out.println("");
System.out.println("Now using a for-each loop");
System.out.println("");
for (String a : universities)
{
System.out.println( a );
}//end for-each
System.out.println( "" );
System.out.println( "Now using a for loop" );
System.out.println( "" );
for (int i = 0; i < universities.size(); i++)
{
if (universities.get(i) > 4 )
{
universities.remove(i);
}//end if-statement
}//end for loop
}//end main
}
Use the Java 8 removeIf default method on List:
universities.removeIf(u -> u.length() > 4);
If you're trying to remove elements that are larger than 4 characters, this will work:
for (int i = 0; i < universities.size(); i++)
{
System.out.println("checking "+universities.get(i));
if (universities.get(i).length() > 4 )
{
universities.remove(i);
i--;
}//end if-statement
}//end for loop
The .length() is necessary because you're interested in the size of the string, you can't compare a string to an int directly. The i--; ensures that you don't skip over elements as the size of the list changes.
The System.out.println is to show you what elements it is checking, so you can see that you're walking through the list correctly.
Instead of if(universities.get(i) > 4)
Do this:
for (int i = size; i >= 0; i--)
{
if (i > 4 )
universities.remove(i); // Shorten to only 1 line instead of brackets
}//end for loop
Reason
You want to remove the university at point i in this case, not get the university object. When you call universities.get(i) it returns the Object in the universities ArrayList
With current code problem is in the fact that you increasing i every time, while sometimes you remove element which cause indexes for elements to the left to be shifted. This results in the fact that you skip check for some elements. Example:
Initial array: [5,6,7], index i = 0.
You removed element at index 0 - array became [6,7], then you increase i and it became 1 - so index for next element to check is 1 and this reffer to 7, not to 6. Result - you didn't check 6.
Solutions:
1) Add i--; immediately after universities.remove(i);
2) Iterate in descending order: for (int i = 0; i < universities.size(); i++) -> for (int i = universities.size() - 1; i >= 0; i--)
3) Use java streams:
universities = universities.stream()
.filter(e -> e > 4)
.collect(Collectors.toList());
The problem with your code is that i advances to the next value even after a remove() call, meaning that your code will skip some items.
Here is what's happening: let's say you want to delete all numbers 4 and above from this list: {9 5 7 4 3}. When i is zero, your algorithm will find 9 and remove it. Now i is 1, but your list is {5 7 4 3}, so 5 at index zero will never be checked again.
One solution is to iterate in reverse order:
for (int i = universities.size() - 1; i >= 0 ; i--) {
if (universities.get(i).length() > 4 ) {
universities.remove(i);
}//end if-statement
}//end for loop
Now that i goes down instead of going up it does not matter whether the list shrinks or not.
What exactly do you mean by greater than 4? If you meant length of the String greater than 4, then here is the solution. Replace the 2nd for loop with the code below.
int i = 0;
while(i<universities.size()) {
if (universities.get(i).length() > 4 ) {
universities.remove(i);
} else {
i++;
}
}
I am trying to figure out how to print the elements of an array with 10 elements per line. Every time I think I have come up with a solution there is some part of the code that we haven't studied yet. So I hit a dead end. I thought about passing the element of my one dimensional array to a two-dimensional array with 10 elements per row then printing the individual rows. But I dont' know how to pass the elements form the one dimensional array to the two dimensional array.
import java.util.*;
public class myFirstArray
{
public static void main(String[] args)
{
double alpha[] = new double[50];
for (int i = 0; i < alpha.length; i++)
if (i < 25)
alpha[i] = i * i;
else
alpha[i] = i * 3;
for (int i = 0; i < alpha.length; i++)
// prints all 50 elements on one line
System.out.print (alpha[i] + ", ");
}
}
You don't need a two-dimensional array for this. Simply print a new line when i = 0 (mod 10) to split up the output into lines of 10 numbers each.
You might need to modify the way you deal with commas a bit, depending on your output specifications, but in general the code will look like:
for (int i = 0; i < alpha.length; i++) {
if(i != 0 && i % 10 == 0) {
System.out.println();
}
System.out.print(alpha[i] + ", ");
}
I have most of my program done, but it's not working as I need it to and I've stared at it for a while and I just can't figure it out. Can someone help me notice what I am doing wrong? I'm not asking for someone to just fix it, but explain it.
Create a class called CustomerLister1 with a main method that instantiates an array of String objects called customerName. The
array should have room for seven String objects. Assign each of the
following Strings to sequential locations in the array beginning at
array index 0.
Chris
Lois
Meg
Peter
Stewie
Write an enhanced for loop to display the array of names. What is displayed for the last two array elements? Why is it that value?
Add the Strings “Meg” and “Brian” into index 3, and 4, respectively, so that the array contains the following elements:
Chris
Lois
Meg
Meg
Brian
Peter
Stewie
Write an enhanced for loop to display the array of names.
Write a second, traditional for loop that checks each element for the String “Meg”, if found in the array, remove it, shift the
remaining elements, and display the array of names. Are both
instances of “Meg” removed correctly from the array?
Modify the code you wrote part #1 for a second class called CustomerLister2 so that you are using an ArrayList instead of an array
to store the names as String objects.
Add the five names as done previously, and then add “Brian” so that it
is the 4th name in the ArrayList. Now add “Meg” into the third
position in the list (there will be two identical strings “Meg” in the
list).
Use an enhanced for loop for displaying all the String objects, as in
part #1 and use a traditional for loop to remove “Meg” and show the
revised ArrayList. Once again, was “Meg” removed completely from the
list?
public class CustomerLister1
{
public static void main(String[] args)
{
String[] customerName = new String[7];
customerName[0] = "Chris";
customerName[1] = "Lois";
customerName[2] = "Meg";
customerName[3] = "Peter";
customerName[4] = "Stewie";
for (int i = customerName.length-1; i > 3; i--)
{
customerName[i] = customerName[i - 2];
}
customerName[3] = "Meg";
customerName[4] = "Brian";
for (int m = 0; m <= customerName.length-1; m++)
{
if (customerName[m].equals("Meg"))
{
for (int j = m; j < customerName.length; j++)
{
if (j < customerName.length-2)
{
customerName[j] = customerName[j+1];
} else {
customerName[j] = "";
}
}
m++;
}
for (String element : customerName)
{
System.out.println(element);
}
}
}
}
First, an "enhanced" loop (I think) is a for-each loop. It looks like this in java.
for (String name : customerName) {
System.out.println(name);
}
whereas a traditional for loop is iteration, which is what you were doing.
for (int i = 0; i < num; i++) {
System.out.println(customerName[i]);
}
You are printing too much output mainly because your last for loop is embedded too far. Let me increase the tab stops to make it more obvious.
for (int m = 0; m <= customerName.length-1; m++)
{
if (customerName[m].equals("Meg"))
{
for (int j = m; j < customerName.length; j++)
{
if (j < customerName.length-2)
{
customerName[j] = customerName[j+1];
} else {
customerName[j] = "";
}
}
m++;
}
for (String element : customerName)
{
System.out.println(element);
}
}
Do you see how your last for loop is embedded into your first one? This means everytime the first for loop for (int m = 0; m <= customerName.length-1; m++) runs, the last for loop is ALSO going to run. Which means the entire loop runs m times.
For a mathematical explanation, LoopA runs n times. LoopB runs m times. If LoopB is inside of LoopA then LoopB will run a total of n * m times.
The problem with many outputs is obvious as you have your printing loop inside your "enhanced" loop, whatever that means.
Other than that you should use <= in your innermost loop as you also want to move the very last element.
I have a Method that uses an array with certain numbers of localities. I ask for the user to input the number of the locality to start overwriting. My object array has other objects in the localities. I'm not sure if what I am doing with the j variable is correct. The following is my way of moving the objects in the localities.
public void overwriteArray(int number) {
for (int i=0; i<array.length ; i++) {
if (i ==(number-1) {
for(int j = i ; j<array.length ; j++) {
array[j] = array[j+1];
}
}
}
}
Is there any other way? Is there something easier than using arrays? Is correct the way of moving the objects in the array?
Thanks!
If I understand well: you want to remove the element described by the number input parameter, and shift the remaining elements to the left. Also, the element on the end stays in place with all moves. And number is the number of the element to be removed, so 1 means, the 1st element is to be removed, meaning the **index of 0 **in the array, am I right?
Then your code seems to work OK, with the exception, that you don't need the outer loop. At all:
public void overwriteArray(int number) {
for(int j = number-1 ; j<array.length ; j++) {
array[j] = array[j+1];
}
}
The outer loop didnát do anzthing, except when the loop variable was exactlz number-1 Also beware, this might address outside of the array length...
You could use System.arraycopy for this purpose too, no need for this lenghty code (the indexes might be off, and of course it would dies with improper number argument):
public void overwriteArray(int number) {
System.arraycopy(array, number, array, number-1, array.length-number);
}
It does work on the same src and dest:
If the src and dest arguments refer to the same array object, then the copying is performed as if the components at positions srcPos through srcPos+length-1 were first copied to a temporary array with length components and then the contents of the temporary array were copied into positions destPos through destPos+length-1 of the destination array.
Your outer loop iterates over the hole array and execute the inner loop only when i == (number-1) so array.length - 1 of the iterations are for free!
You could get rid of the outer for loop along with the if (i ==(number-1) { and instead write for(int j = (number-1) ; j<array.length ; j++) {
also array[j+1]; will give you an ArrayIndexOutOfBoundsException on the last iteration. Maybe you will want to go only till array.length - 1.
Also to avoid ArrayIndexOutOfBoundsException you should make sure that number is within the range [1, array.length] before iteration.
Here is how could looks like:
#Test
public void overwritearrayay() {
String[] array = {"foo", "bar", "foobar"};
log(Arrays.toString(array));
overwritearrayay(array, 1);
log(Arrays.toString(array));
}
public void overwritearrayay(String[] array, int n) {
if(n > 0 && array != null && n <= array.length) {
for(int i = n-1; i < array.length-1; i++) {
array[i] = array[i+1];
}
array[array.length-1] = null;
}
}
public static void log(String string) {
System.out.println(string);
}
Output
[foo, bar, foobar]
[bar, foobar, null]