Kotlin recursively get size of a folder [closed] - file

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I have seen how to return size of a folder in Java: Get size of folder or file, but I couldn't find it in Kotlin.
How do I get the size of a folder in Kotlin?

To get the total size of files in the directory and its children, recursively, you can use the .walkTopDown() function to build a sequence that enumerates all of the files, and then sum the .lengths of its file elements.
val directory: File = ...
val totalSize =
directory.walkTopDown().filter { it.isFile }.map { it.length() }.sum()
Filtering the elements using .isFile is needed here because it is unspecified what .length returns when called on a File denoting a directory.

So here is how to do it :
private fun dirSize(dir: File): Long {
if (dir.exists()) {
var result: Long = 0
val fileList = dir.listFiles()
for (i in fileList!!.indices) {
if (fileList[i].isDirectory) {
result += dirSize(fileList[i])
} else {
result += fileList[i].length()
}
}
return result
}
return 0
}
And if you want a readable string your can do this :
private fun getStringSize(size: Long): String {
if (size <= 0)
return "0MB"
val units = arrayOf("B", "KB", "MB", "GB", "TB")
val digitGroups = (Math.log10(size.toDouble()) / Math.log10(1024.0)).toInt()
return DecimalFormat("#,##0.#").format(size / Math.pow(1024.0, digitGroups.toDouble())) + " " + units[digitGroups]
}
How to use it :
val directory = File(filesDir.absolutePath + File.separator + DIRECTORY_NAME)
println(getStringSize(dirSize(directory)))
Hope it's will help some of you.

Related

Cannot find string value in array [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I am unable to check if something is string or not.
I have this array:
ji1 = [:Districts,:Winter_Rain, :Hot_Weather_Rain, :South_West_Monsoon, :North_West_Monsoon, :Total]
I am trying to map this array using this code:
hash_data = ji1.map do |el|
{title:el, field:el, sorter:"string", editor:true}
end
This works, but when I use this array:
ji1 = ["Districts",:Winter_Rain, :Hot_Weather_Rain, :South_West_Monsoon, :North_West_Monsoon, :Total]
with this code,
hash_data = ji1.map do |el|
hash_data = ji.map do |el|
if el == "Districts"
abort(el)
else
puts el
end
{title:el, field:el, sorter:"string", editor:true}
end
When I am using code above I don't see any action I am expecting to abort the code when el == "Districts". I need to compare my first array.
While you have an array of symbols you are comparing it with string. Converting the element to string (el.to_s == "Districts") will work.
ji1 = [
:Districts, :Winter_Rain, :Hot_Weather_Rain, :South_West_Monsoon,
:North_West_Monsoon, :Total
]
hash_data = ji1.map do |el|
if el.to_s == "Districts"
abort(el)
else
puts el
end
{ title:el, field:el, sorter:"string", editor:true }
end
Note: The above code only converts el to string for comparison purpose. If you want it String in the return value you might want to change el in the loop itself
Like this:
hash_data = ji1.map do |el|
el = el.to_s
...
...
end

How to delete a word from an array if you got it 3 times in a row?

I'm doing my quiz app. I got a structured array that contains words, their translations, definitions, etc. After every answer, my app generates a random question. So, my question is how to delete a word from my array if user got it right for 3 times in a row.
How do I attach a counter to correctly answered word (that will be counting right answers for every single word in the array)?
I tried to triple my array and then delete this word, but it's a lot of coding and repetitive lines.
You can use this class to get the next question and update the array after a question has been answered correctly:
class QuestionProvider {
struct Question {
let question: String
let answer: String
var rightAnswers: Int
init(question: String, answer: String) {
self.question = question
self.answer = answer
self.rightAnswers = 0
}
}
private var questions = [Question]()
func add(question: Question) {
questions.append(question)
}
func getNextQuestion() -> Question {
let index = Int(arc4random_uniform(UInt32(questions.count)))
return questions[index]
}
func answeredCorrectly(question: Question) {
guard let index = questions.index(where: {$0.question == question.question}) else { return }
var qa = questions[index]
qa.rightAnswers += 1
if qa.rightAnswers >= 3 {
questions.remove(at: index)
} else {
questions[index] = qa
}
}
}

How to iterate throguh all possible combinations in an array using recursion? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I have started to learn recursion and I find it very confusing when I was solving a practice problem.
For example, if I have an array in sorted order [2,3,4,5,6,7,8,9] and I want to iterate through all possible combinations of d jumps starting from the first number 2 till end number 9.
Some of the valid jumps are (for d = 3 jumps):
2->3->5->9
2->3->6->9
2->3->7->9
2->3->8->9
2->4->5->9
and so on.
Please tell me how to approach such recursion problems.
This problem reduces quickly: remove both ends of the list. Now, all you have to do is choose d-1 elements from the remaining list. Finding all combinations of m elements in a list of length n > m is easily researched. You can almost certainly find a solution in your favorite language.
Does that insight get you moving?
Here is an implementation of a class that calculates possible hops:
public class HopCalculator {
private int[] input;
public HopCalculator(int[] input) {
this.input = input;
}
The input array was given in construction time. Now we can query different routes with different lengths (number of hops).
The output is a Set that contains possible routes.
Each route is an array-list that contains the number it goes through.
public Set<ArrayList<Integer>> findPossibleHops(int d) {
Set<ArrayList<Integer>> options = new HashSet<>();
ArrayList<Integer> option = new ArrayList<>();
option.add(input[0]);
findPossibleHopsRecursive(options, option, d-1, 1, input.length-2);
return options;
}
private void findPossibleHopsRecursive(Set<ArrayList<Integer>> options, ArrayList<Integer> option, int d, int begin, int end) {
if (d==0) {
option.add(input[end+1]);
options.add(option);
}
else {
if (end - begin + 1 == d) {
option.add(input[begin]);
findPossibleHopsRecursive(options, option, d - 1, begin + 1, end);
} else {
ArrayList<Integer> option1 = new ArrayList<>();
option1.addAll(option);
option1.add(input[begin]);
findPossibleHopsRecursive(options, option1, d - 1, begin + 1, end);
ArrayList<Integer> option2 = new ArrayList<>();
option2.addAll(option);
findPossibleHopsRecursive(options, option2, d, begin + 1, end);
}
}
}
}

Object doesn't support property or method 'find' - where to find suitable polyfill script? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 5 years ago.
Improve this question
I have a web app (AngularJS, WebAPI, MVC...), I use ES6 new features.
Everything works like a charm in Chrome.
The problem is with IE (we have IE 11 at work).
IE doesnt like few things, such as:
Object doesn't support property or method 'find' and other ES6 functions.
I have heard of polyfill scrips that I can add to my app so that it will work in IE as well.
I dont know what polyfill script I need and there to find it.
Can someone assist? Thanks.
for polyfill script use es6 shim:
https://github.com/paulmillr/es6-shim
if your object is array
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/find
if (!Array.prototype.find) {
Object.defineProperty(Array.prototype, 'find', {
value: function(predicate) {
// 1. Let O be ? ToObject(this value).
if (this == null) {
throw new TypeError('"this" is null or not defined');
}
var o = Object(this);
// 2. Let len be ? ToLength(? Get(O, "length")).
var len = o.length >>> 0;
// 3. If IsCallable(predicate) is false, throw a TypeError exception.
if (typeof predicate !== 'function') {
throw new TypeError('predicate must be a function');
}
// 4. If thisArg was supplied, let T be thisArg; else let T be undefined.
var thisArg = arguments[1];
// 5. Let k be 0.
var k = 0;
// 6. Repeat, while k < len
while (k < len) {
// a. Let Pk be ! ToString(k).
// b. Let kValue be ? Get(O, Pk).
// c. Let testResult be ToBoolean(? Call(predicate, T, « kValue, k, O »)).
// d. If testResult is true, return kValue.
var kValue = o[k];
if (predicate.call(thisArg, kValue, k, o)) {
return kValue;
}
// e. Increase k by 1.
k++;
}
// 7. Return undefined.
return undefined;
}
});
}

Compare two arrays for detect remove and add element [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
There is two array,
One -> ["A","B","C","D"]
Two -> ["A","E","H","D"]
I need check array details. I mentioned array one is existing data (before updating) and array two is update data ( after update the array one). I need figure out which data is come into that array (array two ) and which data is remove from that array (array one).
Look into http://underscorejs.org/#arrays functions, you need to use _.intersection and _.difference methods. It's pretty easy to code that functions by yourself if you don't want new dependencies
_.intersection(One, Two) -> not changed data
_.difference(Two, One) -> new data
_.difference(One, Two) -> removed data
jQuery(function() {
var array1 = ["A", "B", "C", "D"];
var array2 = ["A","H","J","D"];
var foo1 = [];
var foo2 = [];
var i = 0;
jQuery.grep(array2, function(el) {
if (jQuery.inArray(el, array1) == -1) foo1.push(el);
i++;
});
jQuery.grep(array1, function(e2) {
if (jQuery.inArray(e2, array2) == -1) foo2.push(e2);
i++;
});
alert(" Removed Data is " + foo2);
alert(" New Data is " + foo1);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>

Resources