What makes this a fixed-length list in Dart? - algorithm

List<String> checkLength(List<String> input) {
if (input.length > 6) {
var tempOutput = input;
while (tempOutput.length > 6) {
var difference = (tempOutput.length/6).round() + 1;
for (int i = 0; i < tempOutput.length - 1; i + difference) {
tempOutput.removeAt(i); //Removing the value from the list
}
}
return tempOutput; //Return Updated list
} else {
return input;
}
}
I am trying to delete something out of a temporary list. Why does it not work? I do not see how it is fixed, in other problems I have solved, I used a similar approach and it worked (Even identical nearly)
Please note I am kind of new to Dart, so please forgive me this sort of question, but I couldn't figure out the solution.
Find the Code available in the Dart Link
Code in Dart

You can ensure that tempOutput is not a fixed-length list by initializing it as
var tempOutput = new List<String>.from(input);
thereby declaring tempOutput to be a mutable copy of input.
FYI it also looks like you have another bug in your program since you are doing i + difference in your for-loop update step but I think you want i += difference.

Can you please try this code and let me know is that works?
List<String> checkLength(List<String> input) {
if (input.length > 6) {
var tempOutput = input;
while (tempOutput.length > 6) {
var difference = (tempOutput.length/6).round() + 1;
for (int i = 0; i < tempOutput.length - 1; i = i + difference) {
tempOutput.removeAt(i); //Removing the value from the list
}
}
return tempOutput.toList(); //Return Updated list
} else {
return input.toList();
}
}
Note: You used "i + difference" which is same value say for example in first iteration you i=1 and difference = 1, then "tempOutput.removeAt(i)" will remove the value at "1" position, again in the second iteration you are trying to remove the same position, so the error clearly states "Cannot remove from the Fixed length"
Here the i value has to be incremented or decremented for each iteration process, in your for loop that is missing.

The answer of #harry-terkelsen was very helpful for solving the fixed-length problem.
For those who were asking about my algorithm:
The difference is for skipping the amount of characters when wanting to remove some. Also, I had to change the for-loop, as it did not quite do what I wanted it to.
The fix is here! https://github.com/luki/wordtocolor/blob/master/web/algorithms.dart
Thank you for understanding me!

Related

Answering the Longest Substring Without Repeating Characters in Kotlin

I've spend some time working on the problem and got this close
fun lengthOfLongestSubstring(s: String): Int {
var set = HashSet<Char>()
var initalChar = 0
var count = 0
s.forEach {r ->
while(!set.add(s[r]))
set.remove(s[r])
initalChar++
set.add(s[r])
count = maxOf(count, r - initialChar + 1)
}
return count
}
I understand that a HashSet is needed to answer the question since it doesn't allow for repeating characters but I keep getting a type mismatch error. I'm not above being wrong. Any assistance will be appreciated.
Your misunderstanding is that r represents a character in the string, not an index of the string, so saying s[r] doesn't make sense. You just mean r.
But you are also using r on its own, so you should be using forEachIndexed, which lets you access both the element of the sequence and the index of that element:
s.forEach { i, r ->
while(!set.add(r))
set.remove(r)
initialChar++
set.add(r)
count = maxOf(count, i - initialChar + 1)
}
Though there are still some parts of your code that doesn't quite make sense.
while(!set.add(r)) set.remove(r) is functionally the same as set.add(r). If add returns false, that means the element is already in the set, you remove it and the next iteration of the loop adds the element back into the set. If add returns true, that means the set didn't have the element and it was successfully added, so in any case, the result is you add r to the set.
And then you do set.add(r) again two lines later for some reason?
Anyway, here is a brute-force solution that you can use as a starting point to optimise:
fun lengthOfLongestSubstring(s: String): Int {
val set = mutableSetOf<Char>()
var currentMax = 0
// for each substring starting at index i...
for (i in s.indices) {
// update the current max from the previous iterations...
currentMax = maxOf(currentMax, set.size)
// clear the set to record a new substring
set.clear()
// loop through the characters in this substring
for (j in i..s.lastIndex) {
if (!set.add(s[j])) { // if the letter already exists
break // go to the next iteration of the outer for loop
}
}
}
return maxOf(currentMax, set.size)
}

How to display a list of number of words of each length - Javascript

Hi guys I am really stuck in this one situation :S I have a local .txtfile with a random sentence and my program is meant to :
I am finding it difficult to execute the third question. My code is ..
JavaScript
lengths.forEach((leng) => {
counter[leng] = counter[leng] || 0;
counter[leng]++;
});
$("#display_File_most").text(counter);
}
}
r.readAsText(f);
}
});
</script>
I have used this question for help but no luck - Using Javascript to find most common words in string?
I believe I have to store the sentence in an array and loop through it, uncertain if that is the correct step or if there is quicker way of finding the solution so I ask you guys.
Thanks for your time & I hope my question made sense :)
If you think of your solution as separated well done tasks, it would be really simple to find it. Here you have them together:
Convert the words into an array. Your guts were right about this :)
var source = "Hello world & good morning. The date is 18/09/2018";
var words = source.split(' ');
The next step is to find out the length of each word
var lengths = words.map(function(word) {
return word.length;
});
Finally the most complicated part is to get the number of occurrences for each length. One idea is to use an object to use key/value where key is the length and value is its count (source: https://stackoverflow.com/a/10541220/1505348)
Now you will see under the counter object have each word length with its repetition number on the source string.
var source = "Hello world & good morning. The date is 18/09/2018";
var words = source.split(' ');
var lengths = words.map(function(word) {
return word.length;
});
var counter = {};
lengths.forEach((leng) => {
counter[leng] = counter[leng] || 0;
counter[leng]++;
});
console.log(counter);
3.Produce a list of number of words of each length in sentence (not done).
Based on the question would this not be the solution?
var words = str.split(" ");
var count = {};
for (var i = 0; i<words.length; i++){
count[words[i].length] = (count [words[i].length] || 0) + 1
}

Difference between one pass (scan) and two pass(scan)

I had an Interview, a day before.
The Interviewer told me to , " Write a program to add a node at the end of a linked list ".
I had given him a solution. but he told me to implement it in one pass (one scan).
Can Anybody explain me, whats the meaning of one pass, and how to find the program written is in one pass or two pass?
Here is my code
public void atLast(int new_data)
{
Node new_node=new Node(new_data);
if(head==null)
{
head=new Node(new_data);
return;
}
new_node.next=null;
Node last=head;
while(last.next!=null)
{
last=last.next;
}
last.next=new_node;
return;
}
If that is the code you gave the interviewer must have misread it because it is a single pass.
In your case a "pass" would be your while loop. It could also be done with recursion, for, or any other type of loop that goes through the elements in the array (or other form of a list of items).
In your code you run through the list of Node and insert the element at the end. This is done in one loop making it a single pass.
Now to look at a case with two passes. Say for example you were asked to remove the element with the largest value and wrote something similar to this:
int index = 0;
int count = 0;
int max = 0;
while(temp_node != null)
{
if(temp_node.data > max)
{
index = count;
max = temp_node.data;
}
count++;
temp_node = temp_node.next;
}
for(int i = 0; i < count; i++)
{
if(i == index)
{
//Functionality to remove node.
}
}
The first pass (while) detects the Node which has the maximum value. The second pass (for) removes this Node by looping through all the elements again until the correct one is found.
I'd imagine "two passes" here means that you iterated through the whole list twice in your code. You shouldn't need to do that to add a new node.

Cilk_for returns wrong data in array

I am new to multi threading programming. Recently, i have a project, which i apply cilk_for into it. Here is the code:.
void myfunction(short *myarray)
{
m128i *array = (m128i*) myarray
cilk_for(int i=0; i<N_LOOP1; i++)
{
for(int z = 0; z<N_LOOP2; z+=8)
{
array[z] = _mm_and_si128(array[z],mym128i);
array[z+1] = _mm_and_si128(array[z+1],mym128i);
array[z+2] = _mm_and_si128(array[z+2],mym128i);
array[z+3] = _mm_and_si128(array[z+3],mym128i);
array[z+4] = _mm_and_si128(array[z+4],mym128i);
array[z+5] = _mm_and_si128(array[z+5],mym128i);
array[z+6] = _mm_and_si128(array[z+6],mym128i);
array[z+7] = _mm_and_si128(array[z+7],mym128i);
array+=8;
}
}
}
After the above code ran, ridiculous thing happens. The data in array isn't updated correctly. For example, if i have an array with 1000 elements, there is a chance that the array will be updated correctly (1000 elements are AND-ed). But there is also a chance that some parts of the array will be omited (first element to 300th element are AND-ed, 301st element to 505th element aren't AND-ed, 506th element to 707th element are AND-ed, etc,...). These omited parts are random in each individual run, so i think the problem here is about cache miss. Am I right? Please tell me, any help is appreciated. :)
The issue is that the array pointer is not synchronized between the threads cilk is spawning and your array variable is incremented in each loop iteration. This works only in a linear execution. In your code snippet multiple threads are accessing the same elements in your array while other parts of the array are not processed at all.
To solve this I would propose to calculate the index within the outer loop so that every thread spawned with Cilk is able to calculate the address independently. Maybe you can do something like:
void myfunction(short *myarray)
{
cilk_for (int i=0; i<N_LOOP1; i++)
{
m128i *array = (m128i*) myarray + i * N_LOOP2 * 8;
for(int z = 0; z<N_LOOP2; z+=8)
{
array[z] = _mm_and_si128(array[z],mym128i);
array[z+1] = _mm_and_si128(array[z+1],mym128i);
array[z+2] = _mm_and_si128(array[z+2],mym128i);
array[z+3] = _mm_and_si128(array[z+3],mym128i);
array[z+4] = _mm_and_si128(array[z+4],mym128i);
array[z+5] = _mm_and_si128(array[z+5],mym128i);
array[z+6] = _mm_and_si128(array[z+6],mym128i);
array[z+7] = _mm_and_si128(array[z+7],mym128i);
array+=8;
}
}
}
BTW: Why do you need to do a manual loop unrolling here? The compiler should do that automatically.

How to eliminate duplicate filename in hadoop mapreduce?

I want to eliminate duplicate filenames in my output of the hadoop mapreduce inverted index program. For example, the output is like - things : doc1,doc1,doc1,doc2 but I want it to be like
things : doc1,doc2
Well you want to remove duplicates which were mapped, i.e. you want to reduce the intermediate value list to an output list with no duplicates. My best bet would be to simply convert the Iterator<Text> in the reduce() method to a java Set and iterate over it changing:
while (values.hasNext()) {
if (!first)
toReturn.append(", ") ;
first = false;
toReturn.append(values.next().toString());
}
To something like:
Set<Text> valueSet = new HashSet<Text>();
while (values.hasNext()) {
valueSet.add(values.next());
}
for(Text value : valueSet) {
if(!first) {
toReturn.append(", ");
}
first = false;
toReturn.append(value.toString());
}
Unfortunately I do not know of any better (more concise) way of converting an Iterator to a Set.
This should have a smaller time complexity than orange's solution but a higher memory consumption.
#Edit: a bit shorter:
Set<Text> valueSet = new HashSet<Text>();
while (values.hasNext()) {
Text next = values.next();
if(!valueSet.contains(next)) {
if(!first) {
toReturn.append(", ");
}
first = false;
toReturn.append(value.toString());
valueSet.add(next);
}
}
Contains should be (just like add) constant time so it should be O(n) now.
To do this with the minimal amount of code change, just add an if-statement that checks to see if the thing you are about to append is already in toReturn:
if (!first)
toReturn.append(", ") ;
first = false;
toReturn.append(values.next().toString());
gets changed to
String v = values.next().toString()
if (toReturn.indexOf(v) == -1) { // indexOf returns -1 if it is not there
if (!first) {
toReturn.append(", ") ;
}
toReturn.append(v);
first = false
}
The above solution is a bit slow because it has to traverse the entire string every time to see if that string is there. Likely the best way to do this is to use a HashSet to collect the items, then combining the values in the HashSet into a final output string.

Resources