Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Challenges completed #5

Open
wants to merge 17 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -36,4 +36,7 @@ build/
.vscode/

### Mac OS ###
.DS_Store
.DS_Store

# Json file
src/main/resources/weather.json
7 changes: 7 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,13 @@
<version>5.11.0-M2</version>
</dependency>

<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.18.1</version>
</dependency>

</dependencies>


Expand Down
118 changes: 99 additions & 19 deletions src/main/java/ChallengeStream.java
Original file line number Diff line number Diff line change
@@ -1,28 +1,24 @@
/* (C)2024 */
import java.util.List;
import java.util.Objects;

import mocks.CallCostObject;
import mocks.CallSummary;
import mocks.CardWinner;
import mocks.TotalSummary;

public class ChallengeStream {

/**
* One stack containing five numbered cards from 0-9 are given to both players. Calculate which hand has winning number.
* The winning number is calculated by which hard produces the highest two-digit number.
*
* calculateWinningHand([2, 5, 2, 6, 9], [3, 7, 3, 1, 2]) ➞ true
* P1 can make the number 96
* P2 can make the number 73
* P1 win the round since 96 > 73
*
* The function must return which player hand is the winner and the two-digit number produced. The solution must contain streams.
*
* @param player1 hand, player2 hand
*/
public CardWinner calculateWinningHand(List<Integer> player1, List<Integer> player2) {
// YOUR CODE HERE...
return new CardWinner();
}
private static final double INTERNATIONAL_FIRST_3_MIN = 7.56;
private static final double INTERNATIONAL_ADDITIONAL_MIN = 3.03;
private static final double NATIONAL_FIRST_3_MIN = 1.20;
private static final double NATIONAL_ADDITIONAL_MIN = 0.48;
private static final double LOCAL_PER_MIN = 0.2;
private static final int BASE_MINUTES = 3;

private static final String INTERNATIONAL = "International";
private static final String NATIONAL = "National";
private static final String LOCAL = "Local";

/**
* Design a solution to calculate what to pay for a set of phone calls. The function must receive an
Expand All @@ -43,7 +39,91 @@ public CardWinner calculateWinningHand(List<Integer> player1, List<Integer> play
* @returns {CallsResponse} - Processed information
*/
public TotalSummary calculateCost(List<CallCostObject> costObjectList) {
// YOUR CODE HERE...
return new TotalSummary();
List<CallSummary> callSummaries = costObjectList.stream()
.map(call -> new CallSummary(call, calculateCallCost(call)))
.toList();

// get the total cost of all calls
double totalCost = callSummaries.stream()
.mapToDouble(CallSummary::getTotalCost)
.sum();

// Validate the type of the call to get the size if it is not National, International or Local dont count it
long totalCalls = callSummaries.stream()
.filter(call -> call.getCallCostObject().getType().equals("National") ||
call.getCallCostObject().getType().equals("International") ||
call.getCallCostObject().getType().equals("Local"))
.count();

return new TotalSummary(
callSummaries,
(int) totalCalls,
totalCost);
}

private Double calculateCallCost(CallCostObject call) {
double first3MinRate;
double additionalMinRate;
int duration = call.getDuration();

switch (call.getType()) {
case INTERNATIONAL -> {
first3MinRate = INTERNATIONAL_FIRST_3_MIN;
additionalMinRate = INTERNATIONAL_ADDITIONAL_MIN;
}
case NATIONAL -> {
first3MinRate = NATIONAL_FIRST_3_MIN;
additionalMinRate = NATIONAL_ADDITIONAL_MIN;
}
case LOCAL -> {
return duration * LOCAL_PER_MIN;
}
default -> {
return 0.0;
}
Comment on lines +78 to +83
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: Code smell here, part of the switch doesn't return and part of it returns, this divergent behavior and could be confusing when reading the code

}

if (duration <= BASE_MINUTES) {
return first3MinRate * duration;
} else {
return (additionalMinRate * (duration - BASE_MINUTES)) + (BASE_MINUTES * first3MinRate);
}
}

/**
* One stack containing five numbered cards from 0-9 are given to both players. Calculate which hand has winning number.
* The winning number is calculated by which hard produces the highest two-digit number.
*
* calculateWinningHand([2, 5, 2, 6, 9], [3, 7, 3, 1, 2]) ➞ true
* P1 can make the number 96
* P2 can make the number 73
* P1 win the round since 96 > 73
*
* The function must return which player hand is the winner and the two-digit number produced. The solution must contain streams.
*
* @param player1 hand, player2 hand
*/
public CardWinner calculateWinningHand(List<Integer> player1, List<Integer> player2) {

int player1Max = player1.stream()
// create a stream of all possible two-digit numbers
.flatMap(d1 -> player1.stream()
.filter(d2 -> !d2.equals(d1)) // ensure that the two digits are different
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Digits don't need to be different, a player could win with 11,22,...,99
Same for L122

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What Sebastian said, please send a fix

.map(d2 -> d1 * 10 + d2)) // combine the two digits to form a two-digit number
.max(Integer::compareTo)// get the highest two-digit number
.orElse(0);

int player2Max = player2.stream()
.flatMap(d1 -> player2.stream()
.filter(d2 -> !d2.equals(d1))
.map(d2 -> d1 * 10 + d2))
.max(Integer::compareTo)
.orElse(0);

// return the winner and the winning number and if bot players have the same number return TIE
return new CardWinner(player1Max > player2Max
? "P1" : player1Max == player2Max
? "TIE" : "P2",
Math.max(player1Max, player2Max));
}
}
86 changes: 76 additions & 10 deletions src/main/java/Challenges.java
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
/* (C)2024 */
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

Expand All @@ -21,7 +23,15 @@ public class Challenges {

public String readableTime(Integer seconds) {
// YOUR CODE HERE...
return "";

if (seconds < 0) {
return "";
}

int hours = seconds / 3600;
int minutes = (seconds % 3600) / 60;
int sec = seconds % 60;
return String.format("%02d:%02d:%02d", hours, minutes, sec);
}
;

Expand All @@ -44,8 +54,19 @@ public String readableTime(Integer seconds) {

public String[] circularArray(int index) {
String[] COUNTRY_NAMES = {"Germany", "Norway", "Island", "Japan", "Israel"};

// Validate the index should be a positive number
if (index < 0) {
return new String[]{};
}

// YOUR CODE HERE...
return COUNTRY_NAMES;
String[] result = new String[COUNTRY_NAMES.length];
for (int i = 0; i < COUNTRY_NAMES.length; i++) {
// Using the modulo operator ensure that if the index is greater than the length of the array, it will wrap around
result[i] = COUNTRY_NAMES[(index + i) % COUNTRY_NAMES.length];
}
return result;
}
;

Expand All @@ -68,10 +89,19 @@ public String[] circularArray(int index) {
because 1^1 + 2^2 + 3^3 + 4^4 + 5^5 + 6^6 + 7^7 + 8^8 + 9^9 + 10^10 = 10405071317
The last 3 digits for the sum of powers from 1 to 10 is "317"
***** */

public String ownPower(int number, int lastDigits) {
// YOUR CODE HERE...
return "";
BigInteger sum = BigInteger.ZERO;

for (int i = 1; i <= number; i++) {
// Calculate the power of the number and add it to the sum
BigInteger power = BigInteger.valueOf(i).pow(i);
sum = sum.add(power);
}

return sum
.toString()
.substring(sum.toString().length() - lastDigits);
}
;

Expand All @@ -93,8 +123,21 @@ A factorial (x!) means x! * (x - 1)... * 3 * 2 * 1.
***** */

public Integer digitSum(int n) {
// YOUR CODE HERE...
return 1;
// BigInteger can represent integers of any magnitude, limited only by the available memory on the system.
BigInteger factorial = BigInteger.ONE;

for (int i = 1; i <= n; i++) {
factorial = factorial.multiply(BigInteger.valueOf(i));
}

// Convert the factorial to a string and sum the digits
int sum = 0;
String factorialString = factorial.toString();
for (int i = 0; i < factorialString.length(); i++) {
sum += Character.getNumericValue(factorialString.charAt(i));
}

return sum;
}

/**
Expand All @@ -107,13 +150,26 @@ public Integer digitSum(int n) {
* @param ascivalues hand, player2 hand
*/
public String decrypt(List<Integer> ascivalues) {
// YOUR CODE HERE...
return "";
StringBuilder decryptedString = new StringBuilder();
int prevValue = 0;

for (int asciiValue : ascivalues) {
// sum the previous value with the current value
int decryptedValue = prevValue + asciiValue;

// update the previous value
prevValue = decryptedValue;

// append the decrypted value to the string
decryptedString.append((char) decryptedValue);
}

return decryptedString.toString();
}

/**
* Encryption Function.
* Create am encryption function that takes a string and converts into an array of ASCII character values.
* Create an encryption function that takes a string and converts into an array of ASCII character values.
* encrypt("Hello") ➞ [72, 29, 7, 0, 3]
* // H = 72, the difference between the H and e is 29
* The function must return an array of integer ascii values.
Expand All @@ -122,6 +178,16 @@ public String decrypt(List<Integer> ascivalues) {
*/
public List<Integer> encrypt(String text) {
// YOUR CODE HERE...
return Collections.emptyList();
List<Integer> asciiValues = new ArrayList<>();

for (int i = 0; i < text.length(); i++) {

int asciiValue = text.charAt(i);
int difference = asciiValue - (i == 0 ? 0 : text.charAt(i - 1));

asciiValues.add(difference);
}

return asciiValues;
}
}
30 changes: 30 additions & 0 deletions src/main/java/extraChallenge/Location.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package extraChallenge;

public class Location {

private double lon;
private double lat;

public Location() {}

public Location(double lon, double lat) {
this.lon = lon;
this.lat = lat;
}

public double getLon() {
return lon;
}

public void setLon(double lon) {
this.lon = lon;
}

public double getLat() {
return lat;
}

public void setLat(double lat) {
this.lat = lat;
}
}
Loading