Iterate through a PlatonScript array - for-loop

I am developing on the top of the jPlaton platform and I want to declare a 10-element array of integers in PlatonScript.
Then, I want to assign a number to each array position, lets say numbers 1 to 10.
Finally, I want to iterate through this array and calculate and print the double of each array element.
Array
|1|2|3|4|5|6|7|8|9|10|
Output
|2|4|6|8|10|12|14|16|18|20|
How do I do those "for" loops?
Thanks

#ind:INTEGER
#arr:INTEGER[]
#ind=1
LOOP
setIndex arr #ind
IF (#ind>10)
BREAK
#arr = #ind
#ind=#ind+1
ENDLOOP
#dint:INTEGER
#dint=0
#ind=1
LOOP
setIndex arr #ind
IF (#ind>10)
BREAK
#dint=2*#arr
#ind=#ind+1
HTML
<p>#dint</p>
ENDHTML
ENDLOOP
Useful array methods
setIndex ObjectName IndexValue
Used in variable of array type
Set the current index of the variable
If index set to -1 then method returns the element count
of the array If index set to 0 then current index set to the last plus one (next empty). If index set to a number smaller or equal to the element count the currennt index is set to the specified number First position index is 1, next is 2 and so on. After we set the current array index we are able to access the current array element using the name of the variable as it was a simple (elementary) one
clear ObjectName
Clear the value of the variable. For arrays all the elements of the array are cleared and the array size is set to 0.
sort ObjectName
Sort the elements of an array type variable

Related

How to 'array push' a string into a list in TI-Nspire?

As homework, I must swap letters in a given string. I already figured out how to do this, but not how to display them at once. it involves a for loop. so if I include disp x in the for loop, it displays them between parentheses and a space, but I want them all together, so instead of
"a"
"b"
"c"
I want "abc". Is there a way to do this? Should I push the variable into an array and then display the array after the for loop? How to push variables in to an array?
This is in TI-Nspire CX Cas btw.
To add an element x to an array A use augment(A, {x}).
For your specific case, I would use a string variable (call it string) to which I concatenate the next letter at each iteration of the for loop. So if the next letter to be added is in the variable letter, you would put the following line of code at the end of your for loop: string := string & letter.
here is also way:
Local array
array[dim(array)+1] := value
I would answer you by an example covering your scenario. Let's say we are aiming to have a array listing the elements of binaries when we construct an integer into the base2 (binary).
Define LibPub develope(a,b)=
Func
Local mi,m,q
mi:=mod(a,b)
q:=((a-mi)/(b))
Disp mi
While q≥b
a:=q
m:=mod(a,b)
q:=((a-m)/(b))
Disp m
EndWhile
EndFunc
The above small program develops an integer in decimal base into the binary base; however each binary is shown in a separate line as you mentioned:
ex:
develope(222,2)
0
1
1
1
1
0
1
enter image description here
but this is not what you want, you want is in a single line. IMPORTANCE IS THAT YOU SHOULD LIKELIHOOD WANT EACH ELEMENT BE ACCESSIBLE AS A SEPARATE INTEGER, RIGHT? LIKE AS AN ELEMENT IN A ARRAY LIST, THAT'S WHAT YOU LOOKING FOR RIGHT?
There we Go:
Define LibPub develope(n,b)=
Func
Local q,k,seti,set,valid
valid:=b
If valid>1 Then
q:=n
k:=0
set:={}
While q≠0
seti:=mod(q,b)
q:=int(((q)/(b)))
k:=k+1
seti→set[k]
EndWhile
Else
Disp "Erreur, La base doit être plus grand que 1."
EndIf
Return set
EndFunc
Basically, because we do not know how many elements are going to be added in the array list, the set:={} declares an array with an undefined dim (typically length) in order that dynamically be augmented.
The command seti→set[k] will add the value of the seti whatever it is, into the k position of the array list.
and the return set simply returns the array.
if you need to get access to a specific element, you know how to to that: elementNumber5:=set[5]
I wish it helps.

how to print a dictionary sorted by a value of a subdictionary?

I have a dictionary inside a dictionary and I wish to print the whole dictionary but sorted around a value in the sub dictionary
Lesson = {Name:{'Rating':Rating, 'Desc':Desc, 'TimeLeftTask':Timeleft}}
or
Lesson = {'Math':{'Rating':11, 'Desc':'Exercises 14 and 19 page 157', 'TimeLeftTask':7}, 'English':{'Rating':23, 'Desc':'Exercise 5 page 204', 'TimeLeftTask':2}}
I want to print this dict for example but sorted by 'Rating' (high numbers at the top)
I have read this post but i don't fully understand it.
If you could keep it simple it would be great.
And yes i'm making a program to sort and deal with my homework
Thanks in advance
def sort_by_subdict(dictionary, subdict_key):
return sorted(dictionary.items(), key=lambda k_v: k_v[1][subdict_key])
Lesson = {'Math':{'Rating':11, 'Desc':'Exercises 14 and 19 page 157', 'TimeLeftTask':7}, 'English':{'Rating':23, 'Desc':'Exercise 5 page 204', 'TimeLeftTask':2}}
print(sort_by_subdict(Lesson, 'Rating'))
As there is no notion of order in dictionary, we need to represent the dictionary as a list of key, value pair tuples to preserve the sorted order.
The so question you mention sorts the dictionary using the sorted function such that it returns a list of (k, v) tuples (here k means key & v means value) of top level dictionary, sorting by the desired value of sub dictionary v.

Passing array of integers to loop, modify the array, and store results in new array. Project Euler #8 in Ruby

I'm working through problem 8 on project Euler and have looked through a bunch of resources. Here is the problem:
"#8 - Find the greatest product of five consecutive digits in the 1000-digit number."
I split the 1000-digt number into an array of strings and converted that to an array of integers.
number = "73167176531330624919225119674426574742355349194934
96983520312774506326239578318016984801869478851843
85861560789112949495459501737958331952853208805511
12540698747158523863050715693290963295227443043557
66896648950445244523161731856403098711121722383113
62229893423380308135336276614282806444486645238749
30358907296290491560440772390713810515859307960866
70172427121883998797908792274921901699720888093776
65727333001053367881220235421809751254540594752243
52584907711670556013604839586446706324415722155397
53697817977846174064955149290862569321978468622482
83972241375657056057490261407972968652414535100474
82166370484403199890008895243450658541227588666881
16427171479924442928230863465674813919123162824586
17866458359124566529476545682848912883142607690042
24219022671055626321111109370544217506941658960408
07198403850962455444362981230987879927244284909188
84580156166097919133875499200524063689912560717606
05886116467109405077541002256983155200055935729725
71636269561882670428252483600823257530420752963450"
digits = number.split('').reject!{|i| (i=="\n")}
integer_digits = digits.map {|i| i.to_i}
From here, I want to take the first five values, multiple them, and take the resulting value and add it to a new array named "products". I'm trying to remove the first value of the integer_digit array with the .shift method, start the loop over with the second value of the array, and storing the next product of values [1..5] in the integer_digits array...and so on...
getproduct=1
products=[]
loop do
products << integer_digits[0..4].map {|x| (getproduct*=x) }.max
integer_digits.shift
break if integer_digits.length < 5
end
puts products.max
Once the loop went through all the digits, I hoped that I could display the greatest value using the .max method. The code I have returns an empty array...
My question: How do I keep adding the resulting value of the loop to the product array until there are less than five integer_digit values left? And will the .max method work once this is done?
This line:
products << integer_digits[0..4].map {|x| (getproduct*=x) }.max
makes very little sense. What you need is:
products << integer_digits.first(5).inject(:*)
However you shouldn't store all the results, you only need the biggest one:
max = 0
while integer_digits.length >= 5
product = integer_digits.first(5).inject(:*)
max = product if product > max
integer_digits.shift
end
puts max #=> 40824
UPDATE:
The reason why you are getting an empty string is most likely caused by running the loop twice without regenerating integer_digits array (which has 4 elements after the loop)
Also as suggested by #MarkThomas, you can use each_cons method:
integer_digits.each_cons(5).inject(0) {|max, ary| [max, ary.inject(:*)].max }
This has this advantage that it will not modify integer_digits, so you can run it mutliple times over the same set of digits.

Count frequency of items in array - without two for loops

Need to know is there a way to count the frequency of items in a array without using two loops. This is without knowing the size of the array. If I know the size of the array I can use switch without looping. But I need more versatile than that. I think modifying the quicksort may give better results.
Array[n];
TwoDArray[n][2];
First loop will go on Array[], while second loop is to find the element and increase it count in two-d array.
max = 0;
for(int i=0;i<Array.length;i++){
found= false;
for(int j=0;j<TwoDArray[max].length;j++){
if(TwoDArray[j][0]==Array[i]){
TwoDArray[j][1]+=;
found = true;
break;
}
}
if(found==false){
TwoDArray[max+1][0]=Array[i];
TwoDArray[max+1][1]=1;
max+=;
}
If you can comment or provide better solution would be very helpful.
Use map or hash table to implement this. Insert key as the array item and value as the frequency.
Alternatively you can use array too if the range of array elements are not too large. Increase the count of value at indexes corresponding to the array element.
I would build a map keyed by the item in the array and with a value that is the count of that item. One pass over the array to build the map that contains the counts. For each item, look it's count up in the map, increment the count, and put the new count back into the map.
The map put and get operations can be constant time (e.g., if you use a hash map implementation with a good hash function and properly sized backing store). This means you can compute the frequencies in time proportional to the number of elements in your array.
I'm not saying this is better than using a map or hash table (especially not when there are lots of duplicates, though in that case you can get close to O(n) sorting with certain techniques, so this is not too bad either), it's just an alternative.
Sort the array
Use a (single) for-loop to iterate through the sorted array
If you find the same element as the previous one, increment the current count
If you find a different element, store the previous element and its count and set the count to 1
At the end of the loop, store the previous element and its count

Sorting array using Javascript function - Understanding

I decided to get shuffled values from array. for that i used this function, i got it from net, it works fine. But i don't know, how it's works...
any one can help me to understand this?
my code is :
function rand(ar){
return 0.5-Math.random();
}
var ar = [5,10,15,20,25]
ar.sort(rand);
console.log(ar)
I am using this function for getting new shuffled array values from the declared one.
This code is using the supplied rand function as the comparison operator for the Array.Sort method (http://msdn.microsoft.com/en-us/library/4b4fbfhk(VS.85).aspx). Since the Math.random (http://msdn.microsoft.com/en-us/library/41336409.aspx) function returns a value from 0 (inclusive) to 1 (exclusive), the rand function will return a value from 0.5 (inclusive) to -0.5 (exclusive).
Normally the sortFunction supplied to the Sort method takes 2 arguments that are compared. The sortFunction compares them and returns a value that means:
Negative - The first item is less than the second
Zero - The items are equal
Positive - The first item is greater than the second
As the sort method runs, it uses this comparison to determine which array values should go before the others.
In the case of your code, the rand function's return value is random and has no correlation to the data. This means that, whenever the sort function tries to compare two values in the array, half of the time it will say the first item is less than the second and half the second item will be less than the first. As this is done over the entire length of the array, items are swapped randomly and the whole array becomes randomized.
array.sort() has an optional parameter that is a sorting function, you can pass a function reference to change the order of the array.
Maybe this page can be helpful http://www.javascriptkit.com/javatutors/arraysort.shtml

Resources