Stopwatch Lap Comparison - javascript

I have created a stopwatch web app with HTML, CSS, and Vanilla JS. It counts and stops just fine, with a lap function that prints a separate lap timer running under the main timer.
Now, my issue comes up when I'm trying to get the highest and lowest lap times. I am able to get those values to a certain degree but it's not completely accurate in some time cases. For instance, when you lap 00:02:03 and 00:00:42 respectively, my code picks the first time as the lowest lap time because '03 is lower than '42. The same situation happens when selecting the highest lap.
I'm trying to store the indexes of specific lap times to then proceed to check for the lowest millisecond, in a bigger amount of lap times than just two for example. I have a function for that but it returns only one index number when there are meant to be more.
// code to select minimum lap so far
const minimumLap = {
minimumLapsecond: function() { return lapsecarray.reduce(
(min, currentValue) => Math.min(min, currentValue),
lapsecarray[0]
)},
minimumLapmillisecond: function(){ return lapmilliarray.reduce(
(min, currentValue) => Math.min(min, currentValue),
lapmilliarray[0]
)},
}
lapsecarray.reverse();
lapmilliarray.reverse();
function lapComparison() {
let lapRow = lapTableBody.querySelectorAll("tr");
lapRow.forEach((tr) => tr.classList.remove("min"));
//minimum lap
if (countInArray(lapsecarray)(minimumLap) === 1) {
miniLapindex = lapsecarray.indexOf(minimumLap);
console.log(miniLapindex);
lapRow.item(minLapIndex).classList.add("min");
}
else if (countInArray(lapsecarray)(minimumLapsecond()) > 1) {
minLapIndex = lapmilliarray.indexOf(minimumLapmillisecond());
lapRow.item(minLapIndex).classList.add("min");
}
// counting for multiple seconds or milliseconds in the array to determine which lap time to search
const countInArray = (array) => (value) => {
let count = 0;
for (let i = 0; i <= array.length; i++) {
if (array[i] === value) {
count++;
}
}
return count;
}
// the indexing function that doesn't work as expected 👇
function indexesOf(array) {
let indexes = new Array();
for (let i = 0; i <= array.length; i++) {
if (array.indexOf(i, 0) === value) {
indexes.push(i);
}
}
return indexes;
}

Instead of messing with your code, I have an example idea that you could implement.
First, I strip the colons from the laps. Then I just use Math.min and Math.max to find the min/max from the array.
It might seem like a strange workaround, but without the colons, they just become normal numbers.
laps = ["00:02:03","00:00:42"]; //an array of saved lap times
lap_times = {}; //an empty object that will hold the Numerical Lap time as a key and the string version as the value ie: lap_times[42] = "00:00:42" that way we can grab the original time after determining min/max
laps = laps.map(function(lapTime){//loops through the array and returns a modified value back in each values place
lap = Number(lapTime.replace(/:/g,"")); //replaces the colons and converts to a Number
lap_times[lap] = lapTime //sets the converted time as the key and original time as the value
return lap;
});
/* ... is called spread/rest syntax https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax
Without using lap_times[], min/max would return the numerical representation of the time. So by adding it, it will pull back the previously created full string value
*/
slowest = lap_times[Math.max(...laps)];
fastest = lap_times[Math.min(...laps)];
console.log("slowest", slowest,"fastest" , fastest)

Related

Best way to calculate and append the next unique number to some text in a treeview

I have Implemented a treeview that allows a user to drag and drop a node from one tree to another. The user can also reorder the node they just dropped to some other location in the tree as well as duplicate and remove existing nodes.
What I want to do next is so that every time a node is added or duplicated, it adds an incremented number to the end of the text if the text with that number doesn't exists.
Take this treeview for example.
Hello
Hello (2)
World (2)
World
Test
If I were to add a child node containing the text World to the node with the text Test, this is how the treeview should look like then.
Hello
Hello (2)
World (2)
World
Test
World (3)
If I were to remove the node containing the text World, and add a node containing the text World. The treeview should look like this.
Hello
Hello (2)
World (2)
Test
World (3)
World
Note that it didn't add an incremented number because it found that the text World didn't exist.
Right now I simply have an object containing the text as its key and storing the number of times it has encounter that text. Every time a node is added or duplicated, it increments the number of times it has seen that text.
The harder part is that when a node gets removed and the user adds a node with the same text, I need to somehow calculate which nodes got removed, update the dictionary appropriately and add the next unique number to each node.
Note - Only a single node can be added at a time but when it comes to duplicating or removing a node, not only is the node in question duplicated or removed but also its children. So you can imagine that when a node gets duplicated and the node has children, the algorithm that calculate the next unique number has to run not only for the node but also its children.
My question is, what data structure or technique can I employ to accomplish this?
I like this question. I’ll try to come back with code samples when I’m not on mobile.
You could go crazy with data structures trying to pre-compute the numeric value that should be assigned to the next inserted node, but like you pointed out, you’d have to remember to update when items were removed.
The DOM is already a tree. You have access to a node’s parent and children through parentNode and childNodes respectively.
I suspect that, for most cases, recursively searching the tree for the lowest number you can append will be faster than maintaining a list. The logic could be something like this:
given a node, some target text, and the current number
if the node contains the target text,
and the node contains the current number (or no number if the current number is 0),
increment the number
if the node has children,
for each child,
recurse using the child node, search text, and current number
return the current number
Passing in the root node, the search text, and 0 would recursively search the tree and return the lowest number still available.
If the number returned was 0 then either no matching nodes were found or all the matching nodes had a number (the original node with no number was deleted) and we are safe to insert a numberless node.
If a number greater than 0 was returned, then we are guaranteed that it is the lowest number we can use since, if it already existed in a matching node, it would have been incremented.
This approach also has the advantage of eliminating the work required when removing a node. Even if gaps are left in the numbers used for each match, the recursive function above will find the lowest gap and plug it. Once the gap is filled, it will increment to the next available gap or back to a number larger than all the numbers currently in use.
The last case is when a node is copied. What I would do is use another recursive function to incrementally clone the copied tree into the destination node’s children. Each node that was added would use the same addNode function used to insert a new node, and would therefore use the same recursive function above to assign a number.
The assumption this approach makes is that we are okay to number cloned nodes in the order in which we encounter them. If this is not acceptable and they must stay in the order in which the source subtree’s nodes were numbered, you have some additional work to do before insertion.
Here is solution that I was able to come up with. The solution has as its time complexity O(N) and space complexity O(1) (Not sure about the latter)
First I created a number array containing all the counts found so far.
const counts: number[] = [];
First, we need a recursive function that accepts as a callback the node that it has currently traverse. In that callback, we will search for the target text and if it is found, we will parse the text, calculate the sorted index using binary search and then push the value at that specific index.
// Assumes that there are only one set of parenthesis. Adjust this function for
// your use case.
const extractNumberFromParenthesis = (text: string): number => {
const start = text.indexOf('(');
const end = text.indexOf(')');
const number = text.substr(start + 1, end - start - 1);
// The value 1 in this case represents the target text with no parenthesis
return number ? parseInt(number) : 1;
}
const getSortedIndex = (value: number): number => {
let low = 0;
let high = counts.length;
while (low < high) {
// Prevent overflow and use bitwise operator for small performance gains.
const mid = low + ((high - low) >> 1);
if (counts[mid] < value) {
low = mid + 1;
} else {
high = mid;
}
}
return low;
};
// Recurse through the whole tree starting from the root node.
this._tree.recurseDown((node) => {
if (!node.text.includes(text)) {
return;
}
const count = extractCountFromParenthesis(node.text);
const index = getSortedIndex(count);
counts.splice(index, 0, count);
});
Finally we can calculate the next unique number by searching for the first occurrence where counts[i] !== i + 1
const getNextUniqueCount = () => {
let nextUniqueCount = 0;
while (
nextUniqueCount < counts.length &&
counts[nextUniqueCount] === nextUniqueCount + 1
) {
nextUniqueCount += 1;
}
return nextUniqueCount;
};
Here is the whole code for reference.
getTextWithNextUniqueCount(text: string): string {
const counts: number[] = [];
const extractCountFromParenthesis = (text: string): number => {
const start = text.indexOf("(");
const end = text.indexOf(")");
const count = text.substr(start + 1, end - start - 1);
return count ? parseInt(count) : 1;
};
const getSortedIndex = (value: number): number => {
let low = 0;
let high = counts.length;
while (low < high) {
const mid = low + ((high - low) >> 1);
if (counts[mid] < value) {
low = mid + 1;
} else {
high = mid;
}
}
return low;
};
this._tree.recurseDown((node) => {
if (!node.text.includes(text)) {
return;
}
const count = extractCountFromParenthesis(node.text);
const index = getSortedIndex(count);
counts.splice(index, 0, count);
});
const getNextUniqueCount = (): number => {
let nextUniqueCount = 0;
while (
nextUniqueCount < counts.length &&
counts[nextUniqueCount] === nextUniqueCount + 1
) {
nextUniqueCount += 1;
}
return nextUniqueCount;
};
const addCountToText = (): string => {
const count = getNextUniqueCount();
return count > 0 ? `${text} (${count + 1})` : text;
};
return addCountToText();
}
This entire code will run each time we add a new node or duplicate it. No need to call this function when the node is removed.

How to remove mathematically cancelling values from array of numbers?

My application is collecting a series of adjustments to budget values to try to reach a goal. So far, I'm collecting the adjustments into an array and totaling their values to show how much more needs to be cut to reach the goal:
const goal = 25;
let cutTotal = 0;
let remaining = 0;
let cuts = [];
function update (value) {
// Values are numbers: -1, 1, 0.1, -0.1. This function gets called
// when any update is made to a budget value.
cuts.push(value);
cutTotal = 0;
cuts.forEach(function (value) {
cutTotal += value;
});
remaining = goal - cutTotal;
}
This is working as expected, but I'm thinking there has to be a reasonably performant way to manage the length of the cuts array by removing values that are redundant. (Adding and subtracting 1 from the total doesn't change the total, so why store the values?)

Finding a hamiltonian path with Javascript. How to improve efficiency?

I'm trying to solve this kata:
Given an integer N (<1000), return an array of integers 1..N where the sum of each 2 consecutive numbers is a perfect square. If that's not possible, return false.
For example, if N=15, the result should be this array: [9, 7, 2, 14, 11, 5, 4, 12, 13, 3, 6, 10, 15, 1, 8]. Below N=14, there's no answer, so the function should return false.
I thought 'how hard can this be?' and it's been long days in the rabbit hole. I've been programming for just a few months and don't have a background of CS so I'll write what I understand so far of the problem trying to use the proper concepts but please feel free to tell me if any expression is not correct.
Apparently, the problem is very similar to a known problem in graph theory called TSP. In this case, the vertices are connected if the sum of them is a perfect square. Also, I don't have to look for a cycle, just find one Hamiltonian Path, not all.
I understand that what I'm using is backtracking. I build an object that represents the graph and then try to find the path recursively. This is how I build the object:
function buildAdjacentsObject (limit) {
const potentialSquares = getPotentialSquares(limit)
const adjacents = {}
for (let i = 0; i < (limit + 1); i++) {
adjacents[i] = {}
for (let j = 0; j < potentialSquares.length; j++) {
if (potentialSquares[j] > i) {
const dif = potentialSquares[j] - i
if (dif <= limit) {
adjacents[i][dif] = 1
} else {
break
}
}
}
}
return adjacents
}
function getPotentialSquares (limit) {
const maxSum = limit * 2 - 1
let square = 4
let i = 3
const potentialSquares = []
while (square <= maxSum) {
potentialSquares.push(square)
square = i * i
i++
}
return potentialSquares
}
At first I was using a hash table with an array of adjacent nodes on each key. But when my algorithm had to delete vertices from the object, it had to look for elements in arrays several times, which took linear time every time. I made the adjacent vertices hashable and that improved my execution time. Then I look for the path with this function:
function findSquarePathInRange (limit) {
// Build the graph object
const adjacents = buildAdjacentsObject(limit)
// Deep copy the object before making any changes
const adjacentsCopy = JSON.parse(JSON.stringify(adjacents))
// Create empty path
const solution = []
// Recursively complete the path
function getSolution (currentCandidates) {
if (solution.length === limit) {
return solution
}
// Sort the candidate vertices to start with the ones with less adjacent vert
currentCandidates = currentCandidates.sort((a, b) => {
return Object.keys(adjacentsCopy[a]).length -
Object.keys(adjacentsCopy[b]).length
})
for (const candidate of currentCandidates) {
// Add the candidate to the path
solution.push(candidate)
// and delete it from the object
for (const candidateAdjacent in adjacents[candidate]) {
delete adjacentsCopy[candidateAdjacent][candidate]
}
if (getSolution(Object.keys(adjacentsCopy[candidate]))) {
return solution
}
// If not solution was found, delete the element from the path
solution.pop()
// and add it back to the object
for (const candidateAdjacent in adjacents[candidate]) {
adjacentsCopy[candidateAdjacent][candidate] = 1
}
}
return false
}
const endSolution = getSolution(
Array.from(Array(limit).keys()).slice(1)
)
// The elements of the path can't be strings
return (endSolution) ? endSolution.map(x => parseInt(x, 10)) : false
}
My solution works 'fast' but it's not fast enough. I need to pass more than 200 tests in less than 12 seconds and so far it's only passing 150. Probably both my algorithm and my usage of JS can be improved, so, my questions:
Can you see a bottleneck in the code? The sorting step should be the one taking more time but it also gets me to the solution faster. Also, I'm not sure if I'm using the best data structure for this kind of problem. I tried classic looping instead of using for..in and for..of but it didn't change the performance.
Do you see any place where I can save previous calculations to look for them later?
Regarding the last question, I read that there is a dynamic solution to the problem but everywhere I found one, it looks for minimum distance, number of paths or existence of path, not the path itself. I read this everywhere but I'm unable to apply it:
Also, a dynamic programming algorithm of Bellman, Held, and Karp can be used to solve the problem in time O(n2 2n). In this method, one determines, for each set S of vertices and each vertex v in S, whether there is a path that covers exactly the vertices in S and ends at v. For each choice of S and v, a path exists for (S,v) if and only if v has a neighbor w such that a path exists for (S − v,w), which can be looked up from already-computed information in the dynamic program.
I just can't get the idea on how to implement that if I'm not looking for all the paths. I found this implementation of a similar problem in python that uses a cache and some binary but again, I could translate it from py but I'm not sure how to apply those concepts to my algorithm.
I'm currently out of ideas so any hint of something to try would be super helpful.
EDIT 1:
After Photon comment, I tried going back to using a hash table for the graph, storing adjacent vertices as arrays. Also added a separate array of bools to keep track of the remaining vertices.
That improved my efficiency a lot. With these changes I avoided the need to convert object keys to arrays all the time, no need to copy the graph object as it was not going to be modified and no need to loop after adding one node to the path. The bad thing is that then I needed to check that separate object when sorting, to check which adjacent vertices were still available. Also, I had to filter the arrays before passing them to the next recursion.
Yosef approach from the first answer of using an array to store the adjacent vertices and access them by index prove even more efficient. My code so far (no changes to the square finding function):
function square_sums_row (limit) {
const adjacents = buildAdjacentsObject(limit)
const adjacentsCopy = JSON.parse(JSON.stringify(adjacents))
const solution = []
function getSolution (currentCandidates) {
if (solution.length === limit) {
return solution
}
currentCandidates = currentCandidates.sort((a, b) => {
return adjacentsCopy[a].length - adjacentsCopy[b].length
})
for (const candidate of currentCandidates) {
solution.push(candidate)
for (const candidateAdjacent of adjacents[candidate]) {
adjacentsCopy[candidateAdjacent] = adjacentsCopy[candidateAdjacent]
.filter(t => t !== candidate)
}
if (getSolution(adjacentsCopy[candidate])) {
return solution
}
solution.pop()
for (const candidateAdjacent of adjacents[candidate]) {
adjacentsCopy[candidateAdjacent].push(candidate)
}
}
return false
}
return getSolution(Array.from(Array(limit + 1).keys()).slice(1))
}
function buildAdjacentsObject (limit) {
const potentialSquares = getPotentialSquares(limit)
const squaresLength = potentialSquares.length
const adjacents = []
for (let i = 1; i < (limit + 1); i++) {
adjacents[i] = []
for (let j = 0; j < squaresLength; j++) {
if (potentialSquares[j] > i) {
const dif = potentialSquares[j] - i
if (dif <= limit) {
adjacents[i].push(dif)
} else {
break
}
}
}
}
return adjacents
}
EDIT 2:
The code performs fine in most of the cases, but my worst case scenarios suck:
// time for 51: 30138.229ms
// time for 77: 145214.155ms
// time for 182: 22964.025ms
EDIT 3:
I accepted Yosef answer as it was super useful to improve the efficiency of my JS code. Found a way to tweak the algorithm to avoid paths with dead ends using some of the restrictions from this paper A Search Procedure for Hamilton Paths and Circuits..
Basically, before calling another recursion, I check 2 things:
If there is any node with no edges that's not part of the path till now and the path is missing more than 1 node
If there were more than 2 nodes with 1 edge (one can be following node, that had 2 edges before deleting the edge to the current node, and other can be the last node)
Both situations make it impossible to find a Hamiltonian path with the remaining nodes and edges (if you draw the graph it'll be clear why). Following that logic, there's another improvement if you check nodes with only 2 edges (1 way to get in and other to go out). I think you can use that to delete other edges in advance but it was not necessary at least for me.
Now, the algorithm performs worse in most cases, where just sorting by remaining edges was good enough to predict the next node and extra work was added, but it's able to solve the worst cases in a much better time. For example, limit = 77 it's solved in 15ms but limit=1000 went from 30ms to 100ms.
This is a really long post, if you have any edit suggestions, let me know. I don't think posting the final code it's the best idea taking into account that you can't check the solutions in the platform before solving the kata. But the accepted answer and this final edit should be good advice to think about this last part while still learning something. Hope it's useful.
By replacing the object by an array you save yourself from convert the object to an array every time you want to find the length (which you do a lot - in any step of the sort algorithm), or when you want to get the keys for the next candidates. in my tests the code below has been a lot more effective in terms of execution time
(0.102s vs 1.078s for limit=4500 on my machine)
function buildAdjacentsObject (limit) {
const potentialSquares = getPotentialSquares(limit)
const adjacents = [];
for (let i = 0; i < (limit + 1); i++) {
adjacents[i] = [];
for (let j = 0; j < potentialSquares.length; j++) {
if (potentialSquares[j] > i) {
const dif = potentialSquares[j] - i
if (dif <= limit) {
adjacents[i].push(dif)
} else {
break
}
}
}
}
return adjacents
}
function getPotentialSquares (limit) {
const maxSum = limit * 2 - 1
let square = 4
let i = 3
const potentialSquares = []
while (square <= maxSum) {
potentialSquares.push(square)
square = i * i
i++
}
return potentialSquares
}
function findSquarePathInRange (limit) {
// Build the graph object
const adjacents = buildAdjacentsObject(limit)
// Deep copy the object before making any changes
const adjacentsCopy = JSON.parse(JSON.stringify(adjacents))
// Create empty path
const solution = [];
// Recursively complete the path
function getSolution (currentCandidates) {
if (solution.length === limit) {
return solution
}
// Sort the candidate vertices to start with the ones with less adjacent vert
currentCandidates = currentCandidates.sort((a, b) => {
return adjacentsCopy[a].length - adjacentsCopy[b].length
});
for (const candidate of currentCandidates) {
// Add the candidate to the path
solution.push(candidate)
// and delete it from the object
for (const candidateAdjacent of adjacents[candidate]) {
adjacentsCopy[candidateAdjacent] = adjacentsCopy[candidateAdjacent].filter(t=>t!== candidate)
}
if (getSolution(adjacentsCopy[candidate])) {
return solution
}
// If not solution was found, delete the element from the path
solution.pop()
// and add it back to the object
for (const candidateAdjacent of adjacents[candidate]) {
adjacentsCopy[candidateAdjacent].push(candidate);
}
}
return false
}
const endSolution = getSolution(
Array.from(Array(limit).keys()).slice(1)
)
// The elements of the path can't be strings
return endSolution
}
var t = new Date().getTime();
var res = findSquarePathInRange(4500);
var t2 = new Date().getTime();
console.log(res, ((t2-t)/1000).toFixed(4)+'s');

Compute every combination of 6 numbers

I'm more of a media developer and not the best coder, but I find myself needing to learn javascript better. I'm creating a math card game where the human player and the automated player are each dealt 6 cards. Each player must combine (concatenate) three of the cards to make a top number and the other three for the bottom number. Those two numbers are then subtracted. For the automated player, I have to go through ever possible combination of the six cards, so when the two numbers are subtracted, it gets as close as possible to a target number. I'm not very good with arrays, so I started testing every possible combination and then comparing which one was closer (See example below). This is a very inefficient way of coding this, but I'm just not sure how to do it otherwise. Any help would be greatly appreciated.
The variables have already been declared.
alienTopNum = "" + alienNum1 + alienNum2 + alienNum3;
alienBottomNum = "" + alienNum4 + alienNum5 + alienNum6;
oldDiff = targetNum - (alienTopNum - alienBottomNum);
player.SetVar("AC1R1", alienNum1);
player.SetVar("AC2R1", alienNum2);
player.SetVar("AC3R1", alienNum3);
player.SetVar("AC4R1", alienNum4);
player.SetVar("AC4R1", alienNum5);
player.SetVar("AC4R1", alienNum6);
player.SetVar("ATR1", alienTopNum - alienBottomNum);
alienTopNum = "" + alienNum1 + alienNum2 + alienNum3;
alienBottomNum = "" + alienNum4 + alienNum6 + alienNum5;
newDiff = targetNum - (alienTopNum - alienBottomNum);
if (Math.abs(newDiff) < Math.abs(oldDiff)) {
oldDiff = newDiff;
player.SetVar("AC1R1", alienNum1);
player.SetVar("AC2R1", alienNum2);
player.SetVar("AC3R1", alienNum3);
player.SetVar("AC4R1", alienNum4);
player.SetVar("AC4R1", alienNum6);
player.SetVar("AC4R1", alienNum5);
player.SetVar("ATR1", alienTopNum - alienBottomNum);
}
etc....
Store the dealt cards in an array rather than in individual variables, because that makes them a lot easier to handle when generating permutations. You don't say what values the cards can have, but as an example, given a "hand" of [1,2,3,4,5,6] if you get the permutations as an array of arrays:
[ [1,2,3,4,5,6], [1,2,3,4,6,5], [1,2,3,5,4,6], ...etc. ]
Then you can loop through that to process each permutation to take the first three "cards" and last three to get the current iteration's two numbers, subtract them, and see if the result is closer to the target than previous iterations' results.
The following does that, making use of the array permutation function that I found in this answer to another question. I'm not going to explain that algorithm because you can easily google up various permutation algorithms for yourself, but I have put comments in my bestPlay() function to explain how I process the permutations to figure out which is the best score for a hand.
I haven't tried to use your player or player.SetVar() method, but hopefully if you study this you can adapt it to use with your objects.
You didn't say what values the cards could have, so I've assumed a deck of twenty cards that repeats the numbers 0-9 twice.
function bestPlay(hand, target) {
var perms = permutator(hand); // Get all permutations for hand
var best = perms[0]; // Use the first as initial best
var bestDiff = difference(best);
for (var i = 1; i < perms.length; i++) { // Loop over the rest of the permutations
var diff = difference(perms[i]); // Get diff for current permutation
if (Math.abs(target - diff) < Math.abs(target - bestDiff)) { // Check if
best = perms[i]; // current beats previous best
bestDiff = diff; // and if so make it new best
}
}
// Output the results for this hand:
console.log(`Hand: ${hand.join(" ")}`);
console.log(`Best Numbers: ${best.slice(0,3).join("")} ${best.slice(3).join("")}`);
console.log(`Difference: ${bestDiff}`);
}
var hands = deal();
var target = 112;
console.log(`Target: ${target}`);
bestPlay(hands[1], target);
bestPlay(hands[2], target);
function difference(cards) {
return Math.abs(cards.slice(0,3).join("") - cards.slice(3).join(""));
}
function deal() {
var cards = [1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0];
// shuffle
cards.sort(function() { return Math.random() - 0.5; });
// first hand is first six cards, second hand is next six
return {
1: cards.slice(0,6),
2: cards.slice(6, 12)
};
}
function permutator(inputArr) {
var results = [];
function permute(arr, memo) {
var cur, memo = memo || [];
for (var i = 0; i < arr.length; i++) {
cur = arr.splice(i, 1);
if (arr.length === 0) {
results.push(memo.concat(cur));
}
permute(arr.slice(), memo.concat(cur));
arr.splice(i, 0, cur[0]);
}
return results;
}
return permute(inputArr);
}
If you click the "Run Code Snippet" button several times you'll see that sometimes a given hand has a combination of numbers that exactly matches the target, sometimes it doesn't.

how to create a loop in a function with another function?

I'm new to Java and I'm doing a uni course. I've been asked to design three functions.I have to find the difference between each adjacent numbers in an array, another to total the array and the last one to calculate the difference using the other functions then write a programme. I'm totally lost on the last function and my tutor has gone away on hols. Here is the code I have done so far. I don't want people doing the code for me but if anyone can advice me what I need to do I would appreciate your advice. I'm not sure how to loop the difference function into the array and store it into the new array I have made. If anyone could explain where I am going wrong I would love to hear from you!
var numberArray = [10,9,3,12];
// function difference will find the highest value of the two numbers,find the difference between them and return the value.
function difference(firstNumber, secondNumber)
{
if (firstNumber > secondNumber)
{
return (firstNumber - secondNumber);
}
else
{
return (secondNumber - firstNumber);
}
}
// function sum will add the total numbers in the array and return the sum of numbers.
function sum(numberArray)
{
numberTotal = 0
for (var total = 0; total < numberArray.length; total = total + 1)
{
numberTotal = numberTotal + numberArray[total]
}
{
return numberTotal
}
/*code the process that calculates a new array containing the differences between all the pairs
of adjacent numbers, using the difference() function you have already written.
This function should be named calculateDifferences() and should accept an array numberArray.
The function should first create a new empty array of the same size as numberArray
It should then calculate the differences between the pairs of adjacent numbers,
using the difference() function, and store them in the new array. Finally, the function should return the new array.
The calculation of the differences should be done in a loop, at each step finding the difference between each
array element and the next one along in the array, all except for the last difference,
which must be dealt with as a special case, because after the last element we have to wrap round to the start again.
So the final difference is between the last and first elements in the array.*/
function calculateDifferences()
var createArray = new Array (numberArray.length);
{
createArray = 0;
for (var c = 0; c < numberArray.length; c = c + 1)
{
createArray = difference(numberArray[c]);
}
{
return createArray
}
}
your implementation of function "calculateDifferences" is not correct.
this function should look like this:
function calculateDifferences()
{
var createArray = new Array (numberArray.length);
for (var c = 0; c < numberArray.length - 1 ; c = c + 1)
{
/*
because of the function "difference" has two parameters (firstNumber, secondNumber) in its declaration, we should give two arguments. (that are adjacent elements in array)
*/
createArray[c] = difference(numberArray[c],numberArray[c+1]);
}
/ *
calculating difference of first and last element of array and
assign it to returning array's last element.
*/
createArray[numberArray.length - 1] = difference(numberArray[0],numberArray[numberArray.length - 1]);
return createArray;
}
You should index createArray the same way you already do with numberArray[c].

Categories

Resources