Different ways to create this String in Ruby? - ruby

Disclaimer: Yes, this is homework and yes, I have already solved it.
Task: Create the String "0 10 20 30 40 50 60 70 80 90 100" <- Note, no whitespace
Obviously not using direct assignment, but using tools such as loops, ranges, splitting and such. I already finished this using a 10-increment loop, and I am pretty sure there are way more intelligent ways to solve it and I am curious about the alternatives.How would you build a String like this?

Yes there is using Range#step and Array#*:
(0..100).step(10).to_a * " "
# => "0 10 20 30 40 50 60 70 80 90 100"

Second version using Range#step:
(0..100).step(10).to_a.join(' ')
# "0 10 20 30 40 50 60 70 80 90 100"

Just to be different and not use #step:
(0..10).map{|x| x * 10}.join(' ')

Numeric#step would work, too (here with a Ruby 2.1 style hash argument)
0.step(by: 10).take(11).join(' ')
#=> "0 10 20 30 40 50 60 70 80 90 100"

Just to be contrary, here are some using times with map, with_object and inject:
10.times.map{ |i| "#{ 10 * (i + 1) }" }.join(' ') # => "10 20 30 40 50 60 70 80 90 100"
10.times.with_object([]) { |i, o| o << "#{ 10 * (i + 1) }" }.join(' ') # => "10 20 30 40 50 60 70 80 90 100"
10.times.inject([]) { |o, i| o << "#{ 10 * (i + 1) }" }.join(' ') # => "10 20 30 40 50 60 70 80 90 100"

Related

Cumulative Count in Power BI/DAX

I have seen many different questions that are similar but nothing that I can find that will work.
I am trying to calculate a "running" total for the amount of support tickets that I had on any given day prior to today. I have a current (today) total queue size, and know for each day whether I added to or removed from that queue.
For example:
Date
Created < Known
Completed < Known
Growth < Known
Total Size < Unknown
10-Jan
100
09-Jan
79
77
+2
102
08-Jan
97
92
+5
107
07-Jan
64
67
-3
104
06-Jan
70
66
-4
100
05-Jan
78
80
+2
102
04-Jan
90
82
-8
94
03-Jan
74
68
+6
100
02-Jan
83
87
-4
106
01-Jan
80
70
+10
116
10-Jan is the only known Total value. The remainder total values are being calculated.
In Excel, this would be a simple formula D3 = D2 + C3.
(Calculated column on 'Table' table)
RecursionWithoutIFAndNoFilter_AlsoThisIsWhatIcouldUnderstandFromYourPost_Sorry =
--RunningGrowth
VAR CurrentDate = 'Table'[Date]
VAR RunningGrowth = CALCULATE(SUM('Table'[Growth < Known]), REMOVEFILTERS('Table'), 'Table'[Date]>=CurrentDate)
--MAXDateInTable (I suppose this means TODAY)
--A change in level (because of SELECTEDVALUE) would mean there are more than one row with 01/10
VAR MaxDate = CALCULATE(MAX('Table'[Date]),REMOVEFILTERS('Table'))
VAR TotalSizeInMaxDate = CALCULATE(SELECTEDVALUE('Table'[Total Size < Unknown]),REMOVEFILTERS('Table'),'Table'[Date] = MaxDate)
--Result
VAR Result = TotalSizeInMaxDate + RunningGrowth
RETURN Result

Nested for/while loop python triangle

Code
num = int(input(“Enter the number of lines: “))
for i in range(10):
for j in range(1,i):
print(num, the end='')
num = num+1
print()
I am writing a program which is should be like this.
Enter the number of lines: 10
11 12 13 14 15 16 17 18 19 20
21 22 23 24 25 26 27 28 29
30 31 32 33 34 35 36 37
38 39 40 41 42 43 44
45 46 47 48 49 50
51 52 53 54 55
56 57 58 59
60 61 62
63 64
65
I don’t have any example from the lecturer, i just following the step from website, but the output of my code is like this: i am confused where i made the mistake, don’t get any clue to wear for or while. Please help me, thank you.
10
11 12
13 14 15
16 17 18 19
20 21 22 23 24
25 26 27 28 29 30
31 32 33 34 35 36 37
38 39 40 41 42 43 44 45
Try this:
input_data = input('Enter number of lines: ')
num = int(input_data)
# how many items to print in the first line?
items_to_print = num
# what's the starting number?
print_number = 11
for i in range(0, num):
# don't decrease num
# decrease items_to_print
# each line will reduce 1 item to print
for j in range(0, items_to_print):
print(print_number, end = ' ')
print_number += 1
print()
items_to_print -= 1
Result:
Enter number of lines: 10
11 12 13 14 15 16 17 18 19 20
21 22 23 24 25 26 27 28 29
30 31 32 33 34 35 36 37
38 39 40 41 42 43 44
45 46 47 48 49 50
51 52 53 54 55
56 57 58 59
60 61 62
63 64
65
Explanation
Start small and make your way up.
First just do this:
input_data = input('Enter number of lines: ')
num = int(input_data)
print(num)
That'll print 10 if you entered 10. Great.
Second, add the first for loop and test whether it will print 10 rows.
input_data = input('Enter number of lines: ')
num = int(input_data)
for i in range(0, num):
print(f'Printing line {i}')
Third, try to print a block of 10 x 10. So, you add another variable called items_to_print. Set it to num. If you enter 10 as input, you will get 10 rows and 10 columns.
input_data = input('Enter number of lines: ')
num = int(input_data)
print_number = 0
items_to_print = num
for i in range(0, num):
print(f'Printing line {i}')
for j in range(0, items_to_print):
print(print_number, end = ' ')
Fourth step is to reduce the number of zeros printed before restarting the i loop. So, you decrement items_to_print.
input_data = input('Enter number of lines: ')
num = int(input_data)
print_number = 0
items_to_print = num
for i in range(0, num):
print(f'Printing line {i}')
for j in range(0, items_to_print):
print(print_number, end = ' ')
items_to_print -= 1
Now that your printing is working great, let's set print_number to start with 11 and each time a print happens in j loop, increment print_number. Then you will have same code I published at the top of this answer.
Well you have three little problems so let's address them one at a time.
First: default range function starts at 0 so when your j starts at one you are missing one iteration of the cicle. That explains missing one column and row but not two so let's keep going.
Second: the range function is non inclusive meaning you're I goes from 0 to 9 then in the inner loop you go from 1 to a maximum of 8. There's your missing second iteration.
Third: you are looping from 1 to an encreasing value what you want is the opposite so you need a decreasing range.
This is how you're code should look like.
num = 11
for i in range(10, 0, - 1):
for j in range(i):
print(num, end = " ")
num += 1
print()
Good luck and happy coding

How to write a program in gwbasic for adding the natural numbers for 1 to 100?

I am trying to write a program for adding the natural numbers from 1 to n (1 + 2 + 3 + ... + n). However, the sum appears 1 when I use if statement. And when I use for-next statement there is a syntax error that I don't understand.
if:
30 let s = 0
40 let i = 1
50 s = s + i
60 i = i + 1
70 if i<=n, then goto 50
80 print s
for-next:
30 let i, s
40 s = 0
50 for i = 1 to n
60 s = s + i
70 next i
80 print n
When I take n = 10, the if statement code gives a result of 1, but it should be 55.
When I try to use the for-next statement, it gives no result saying that there is a syntax error in 30.
Why is this happening?
The following code works in this online Basic interpreter.
10 let n = 100
30 let s = 0
40 let i = 1
50 s = s + i
60 i = i + 1
70 if i <= n then goto 50 endif
80 print s
I initialised n on the line labelled 10, removed the comma on the line labelled 70 and added an endif on the same line.
This is the for-next version:
30 let n = 100
40 let s = 0
50 for i = 1 to n
60 s = s + i
70 next i
80 print s
(btw, the sum of the first n natural numbers is n(n+1)/2:
10 let n = 100
20 let s = n * (n + 1) / 2
30 print s
)
Why is this happening? Where am I mistaking?
30 let s = 0
40 let i = 1
50 s = s + i
60 i = i + 1
70 if i<=n, then goto 50
80 print s
Fix #1: Initialize variable 'n':
20 let n = 10
Fix #2: Remove comma from line 70:
70 if i<=n then goto 50
30 let i, s
40 s = 0
50 for i = 1 to n
60 s = s + i
70 next i
80 print n
Fix #1: Initialize variable 'n':
30 let n = 10
Fix #2: Print 's' instead of 'n':
80 print s
10 cls
20 let x=1
30 for x=1 to 100
40 print x
50 next x
60 end

Why a simple calculation returns different result in ruby

I'm not an expert in maths but the following operation gives a different result in ruby than in any other language or calculator I've tried:
Ruby:
(289 / 30 * 30) - (149 / 30 * 30)
=> 150
Rest of the world:
(289 / 30 * 30) - (149 / 30 * 30)
140
An explanation is greatly appreciated
That's because of the data type ruby uses for dividing, int is missing the fractional part of the result.
In Ruby :
289 / 30
=> 9
9 * 30
=> 270
289.0 / 30
=> 9.633333333333333
In Python (for example):
>>> 289 / 30
9.633333333333333
>>> 9.63333 * 30
288.9999
This is integer math for you. 289/30 is equal to 9. By the way, same is in Python if you use // for integer division.
(289//30*30) - (149//30*30) = 150

Generating random points to build a procedural line

I want to randomly generate points. Well at least there should be a limitation on the y-axis. Later I connect the points to a line which should proceed in a simple animation. You can imagine this as a random walk of a drunken person, going uphill and downhill.
This sounds very simple. I searched around the web and found that this could be accomplished using the markov chain. I think this idea is really interesting.
You can create the first state of your scene by yourself and pass this state as input to the markov chain algorithm. The algorithm randomly changes this state and creates a walk.
However I cannot find any example of that algorithm and no source code. I just found an applet that demonstrates the markov chain algorithm: http://www.probability.ca/jeff/java/unif.html
Please suggest some code. Any other ideas how to accomplish this are appreciated too.
I painted an example
So I want the line to proceed in a similar way. There are valleys, slopes ... they are random but the randomness still apply to the initial state of the line. This is why I found makrov chain so interesting here: http://www.suite101.com/content/implementing-markov-chains-a24146
Here's some code in Lua:
absstepmax = 25
ymin = -100
ymax = 100
x = 0
y = 5
for i = 1, 20 do
y = y + (math.random(2*absstepmax) - absstepmax - 1)
y = math.max(ymin, math.min(ymax, y))
x = x + 5
print (x,y)
end
absstepmax limits the size of a y step per iteration
ymin and ymax limit the extent of y
There is no bias in the example, i.e., y can change symmetrically up or down. If you want your "drunk" tending more "downhill" you can change the offset after the call to random from absstepmax - 1 to absstepmax - 5 or whatever bias you like.
In this example, the x step is fixed. You may make this random as well using the same mechanisms.
Here are some sample runs:
> absstepmax = 25
> ymin = -100
> ymax = 100
> x = 0
> y = 5
> for i = 1, 20 do
>> y = y + (math.random(2*absstepmax) - absstepmax - 1)
>> y = math.max(ymin, math.min(ymax, y))
>> x = x + 5
>> print (x,y)
>> end
5 4
10 22
15 37
20 39
25 50
30 40
35 21
40 22
45 12
50 16
55 16
60 12
65 -1
70 -8
75 -14
80 -17
85 -19
90 -25
95 -37
100 -59
> absstepmax = 25
> ymin = -100
> ymax = 100
> x = 0
> y = 5
> for i = 1, 20 do
>> y = y + (math.random(2*absstepmax) - absstepmax - 1)
>> y = math.max(ymin, math.min(ymax, y))
>> x = x + 5
>> print (x,y)
>> end
5 -2
10 -15
15 -7
20 1
25 1
30 12
35 23
40 45
45 43
50 65
55 56
60 54
65 54
70 62
75 57
80 62
85 86
90 68
95 76
100 68
>
Painted result added from OP:

Resources