boolean allLess(int[] one,int[] two) method - java

so I am trying to make this method that takes in two int Arrays and returns true if each element in the first array is less than the element at the same index in the second array if the arrays are of different lengths then it will compare up to the length of the shorter array. this is what i have so far but i keep failing two j unit tests and cant figure out what is causing it. Thank you for any help in advance.
here are the two junit tests i am failing
#Test
public void testSecondLessFirstLonger() {
int[] one = { 5, 5, 5 };
int[] two = { 4 };
boolean actual = Program1.allLess( one, two );
assertFalse( "Incorrect result",actual );
}
#Test
public void testSecondLessSecondLonger() {
int[] one = { 2 };
int[] two = { 1, 0 };
boolean actual = Program1.allLess( one, two );
assertFalse( "Incorrect result",actual );
}
import java.util.Arrays;
here is the code i have so far
public class Program1 {
public static void main(String[] args)
{
int[] one = { 2 };
int[] two = { 1, 0 };
System.out.println(allLess(one, two));
}
public static boolean allLess(int[] one,int[] two)
{
if (one.length != two.length)
{
int len = 0;
if(one.length <= two.length)
{
len = one.length;
}
if(two.length < one.length)
{
len = two.length;
}
boolean[] boo = new boolean[len];
for(int i = 0; i < len; i++)
{
if(one[i] < two[i])
{
boo[i] = true;
}
else
{
boo[i] = false;
}
}
if(Arrays.asList(boo).contains(false))
{
return false;
}
else
{
return true;
}
}
for (int i = 0; i < one.length; i++)
{
if (one[i] >= two[i])
{
return false;
}
}
return true;
}
}

Perhaps you could try something like this:
public static boolean allLess(final int[] array1, final int[] array2){
for(int i = 0; i < Math.min(array1.length, array2.length); i++)
if(array1[i] >= array2[i])
return false;
return true;
}

//this way works too. did you get program 3 done yet? Its giving me issues
import java.lang.Math.*;
public class Program1 {
public static boolean allLess(int[] one, int[] two) {
if (one == null || two == null) {
return false;
}
for (int i = 0; i < Math.min(one.length, two.length); i++) {
if (two[i] <= one[i]) {
return false;
}
}
return true;
}
public static void main(String[] args) {
System.out.println(" ");
}
}

Related

return statement in boolean method

I do not understand what I should return. My method returns false if the last time it goes
through the for-loop it is false. If the last time is true than it returns true. But I want it to return false regardless of where the false occurred.
public class test {
public static void main(String[] args) {
int number = 4;
int[] intArray = {4, 8, 12, 16};
System.out.println(allMultipleOf(intArray, number));
}
public static boolean allMultipleOf(int[] ary, int n){
boolean a = true;
for(int i = 0; i < ary.length; i++){
if(ary[i] % n == 0){
a = true;
//System.out.println(a);
break;
} else {
a = false;
}
}
}
return a; //what should I return
}
You can return false early from the method, if we reached the end without returning false, then return true:
public static boolean allMultipleOf(int[] ary, int n) {
for (int i = 0; i < ary.length; i++) {
if (ary[i] % n != 0) {
return false;
}
}
return true;
}
It should return false, the default of the boolean is print at this place.
You can make the return statement within the method. it return true.
public static boolean allMultipleOf(int[] ary, int n) {
boolean a = true;
for(int i = 0; i < ary.length; i++) {
if (ary[i] % n == 0) {
a = true;
//System.out.println(a);
break;
} else {
a = false;
}
}
return a;
}

Element of a Set randomly changing

For some reason one of the elements of Set s are changing randomly without my code altering it at any point. Not sure why the Set changes from:
[[red, green], [green, red], [red, red], [green, green]]
to
[[green, red], [green, red], [red, red], [green, green]]
for no reason.
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
public class Fermat {
public static void main(String[] args) {
Set<String> colours = new HashSet<String>();
colours.add("red");
colours.add("green");
analyse(threadings(2, colours));
}
public static Set<ArrayList<String>> threadings(int n, Set<String> s) {
Set<ArrayList<String>> combos = new HashSet<ArrayList<String>>();
if (n < 0) {
combos.add(new ArrayList<String>());
return combos;
} else {
int[] index = new int[s.size()];
do {
ArrayList<String> newCombo = new ArrayList<String>();
for (int i = 0; i < n; i++) {
newCombo.add(s.toArray(new String[s.size()])[index[i]]);
}
combos.add(newCombo);
index[index.length - 1]++;
for (int i = (index.length - 1); i > 0; i--) {
if (index[i] >= s.size()) {
index[i] = 0;
index[i - 1]++;
}
}
} while (index[0] < s.size());
return combos;
}
}
public static boolean isEquiv(ArrayList<String> a, ArrayList<String> b) {
if (a.size() != b.size()) {
return false;
} else {
for (int i = 0; i < a.size(); i++) {
if (a.equals(b)) {
return true;
}
Collections.rotate(a, 1);
}
return false;
}
}
public static void analyse(Set<ArrayList<String>> s) {
Set<ArrayList<String>> singletons = new HashSet<ArrayList<String>>();
ArrayList<ArrayList<String>> combos = new ArrayList<ArrayList<String>>();
for (ArrayList<String> combo : s) {
System.out.println(s);
if (singleton(combo, s)) {
singletons.add(combo);
}
}
System.out.println(singletons);
}
public static boolean singleton(ArrayList<String> c, ArrayList<ArrayList<String>> cs) {
for (int i = 0; i < cs.size(); i++) {
{
if (isEquiv(c, cs.get(i)) && !c.equals(cs.get(i))) {
return false;
}
}
}
return true;
}
}
You're mutating the lists with Collections.rotate(a, 1). In this case it ends up rotating that [red, green] to [green, red] at some point, and that affects every reference to that list object.
You need to create a new list and rotate that, so the original list object isn't changed. Something like this:
ArrayList<String> a2 = new ArrayList<>(a);
for (int i = 0; i < a2.size(); i++) {
if (a2.equals(b)) {
return true;
}
Collections.rotate(a2, 1);
}

Boolean To Return True or False in Method

Cannot figure out how to code my method, anything I try gives me compile errors. In short I need my method to iterate through my passed down boolean array. Find out if False appears consecutively more or if True appears consecutively more. In the array I provided False appears more consectively, thus it should return false back to main. I'm at a total loss right now any tips?
public class booleanTF
{
public static void main(String [] args)
{
boolean[] guess = {false,true,false,false,false,true,true};
}
public static boolean longerTF(boolean[] guess)
{
int variable = 0;
for(int x = 0; x < guess.length; x++)
{
if(guess[x]
}
}
You can use flags to check if the current element is true or false and what was the previous element of the array.
You can try the following approach. Ask me if you have any doubts
public class booleanTF {
public static void main(String[] args) {
boolean[] guess = { false, true, false, false, false, true, true };
boolean result = longerTF(guess);
System.out.println(result);
}
public static boolean longerTF(boolean[] guess) {
int variable = 0;
boolean trueFlag = false;
boolean falseFlag = false;
int trueCount = 0, falseCount = 0;
for (int x = 0; x < guess.length; x++) {
if (guess[x] == true) {
if (falseFlag == true) {
trueCount = 0;
}
trueFlag = true;
falseFlag=false;
trueCount++;
} else {
if (trueFlag == true) {
falseCount = 0;
}
falseFlag = true;
trueFlag=false;
falseCount++;
}
}
if (trueCount > falseCount) {
return true;
} else {
return false;
}
}
}
Obviously not the most effective way to do this, but:
public static boolean longerTF(boolean[] guess) {
return findMaxSeqLength(guess, true) > findMaxSeqLength(guess, false);
}
private static int findMaxSeqLength(boolean[] array, boolean value) {
int maxSeqLength = 0;
int counter = 0;
for (boolean b : array) {
counter = (b == value) ? ++counter : 0;
maxSeqLength = Math.max(maxSeqLength, counter);
}
return maxSeqLength;
}
Find the longest true sequence, find the longest false sequence and compare their lengths.
public static void booleanTF(){
boolean[] arr = {true,true,false,false,false};
int fIndex = 0;
int fMaxCount = 0;
int tIndex = 0;
int tMaxCount = 0;
for(boolean ar : arr){
if(ar){
tIndex++;
if(tIndex > tMaxCount){
tMaxCount = tIndex;
}
fIndex= 0;
}else{
fIndex++;
if(fIndex > fMaxCount){
fMaxCount = fIndex;
}
tIndex=0;
}
}
if(fMaxCount > tMaxCount){
System.out.println("False appers more " + fMaxCount);
}else if (tMaxCount > fMaxCount){
System.out.println("True appers more " + tMaxCount);
}else{
System.out.println("Same Count " + tMaxCount);
}
}

remove duplicate characters from a string

import java.util.Scanner;
public class StringWithoutDuplicate {
public static void stringWithoutDuplicate(String s1)
{
int n = s1.length();
int i = 0;
while(i<n)
{
if(s1.charAt(i) == s1.charAt(i+1))
{
if(s1.charAt(i) == s1.charAt(n-1))
{
System.out.println(s1.charAt(i));
}
i++;
}
else if(s1.charAt(i) != s1.charAt(i+1))
{
if(s1.charAt(i) == s1.charAt(n-1))
{
System.out.println(s1.charAt(i));
}
System.out.println(s1.charAt(i));;
i++;
}
}
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
s.useDelimiter(",");
String s1 = s.next();
System.out.println(s1);
stringWithoutDuplicate(s1);
}
}
The code is giving the output but with an exception
please tell me the error in my code and ways to correct it.
I don't want to change the logic of my code so kindly solve it using this logic only.
ERROR:
Range of your i is from 0 to (n-1) which is same as the range of index of characters in your string s1. This is correct.
But during the last iteration of your while loop, i = n-1
At this point, s1.charAt(i+1) becomes same as s1.charAt(n). This should be giving an error.
public static void stringWithoutDuplicate(String s1) {
int prev = -1;
for (int i = 0, size = s1.length(); i < size; ++i) {
char c = s1.charAt(i);
if (c != prev) {
System.out.println(c);
prev = c;
}
}
}

Insertion Sort & Binary Search insertion sort

I am having trouble implementing the insertionSort() method.
import java.util.Random;
import java.util.Arrays;
public class Lab6 {
static final int SIZE = 100;
static int[] values = new int[SIZE];
static void initValues() {
Random rand = new Random();
for(int i =0; i< SIZE;i++) {
values[i] = rand.nextInt(100);// limit to 100
}
}
static boolean isSorted() {
boolean sorted = true;
for(int i=0;i<SIZE-1;i++) {
if(values[i] > values[i+1]){
sorted = false;
}
}
return sorted;
}
static void swap(int index1, int index2) {
int temp = values[index1];
values[index1] = values[index2];
values[index2] = temp;
}
static void insertElement(int endIndex) {
// FILL IN CODE HERE
boolean finished = false;
int current = endIndex;
boolean moretoSearch = true;
while (moretoSearch && !finished){
if (values[current] < values[current-1]){
swap(current, current-1);
current--;
}
else
finished = true;
}
}
I am also not sure if this method "insertElementBinary(int endIndex)" is correctly implemented;
static void insertElementBinary(int endIndex) {
//FILL IN CODE HERE FOR BINARY SEARCH INSERTIONSORT
boolean finished = false;
int current = endIndex;
boolean moretoSearch = true;
while (moretoSearch && !finished){
if (values[current] < values[current-1]){
swap(current, current-1);
current--;
moretoSearch = (current != endIndex);
}
else
finished = true;
}
}
This is where my major problems are:
static void insertionSort() {
//FILL IN CODE HERE
for (int i =0; i < SIZE; i++){
insertElement(i);
insertElementBinary(i);
}
}
The rest of this is good:
public static void main(String[] args) {
Lab6.initValues(); // generate the random array
System.out.println(Arrays.toString(values));
System.out.println(isSorted());
insertionSort();
System.out.println(Arrays.toString(values));
System.out.println(isSorted());
}
}
You're very close to having it correct.
In your insertElement(int endIndex) method, you need to make sure your current > 0, shown below, or else you're going to have an array out of bounds error.
static void insertElement(int endIndex) {
boolean finished = false;
int current = endIndex;
boolean moretoSearch = true;
while (moretoSearch && !finished && current > 0){
if (values[current] < values[current-1]){
swap(current, current-1);
current--;
}
else
finished = true;
}
}
The same fix applies to your insertElementBinary(int endIndex) method. You can test both by commenting out insertElement(i) or insertElementBinary(i) in the insertionSort() method. Both will work fine now.

Categories

Resources