Simple programming tasks #1

Here's to all the new programmers! I, too, am quite new to programming and want to help you guys be better at programming. I will post programming tasks from time to time and ask you guys to try and code something that can solve this. If you manage to, congratulations! If you don't, I will post the answer (mostly in C++ cause that's my dominant language) after a few days so you can analyze it.

For this task:

Plarry the Dinosaur needs to write a composition of nn lines. Being an evil teacher, even after Plarry has written his composition, now the teacher wants Plarry to output every third word! Being a lazy dinosaur, he wants you to help him. Make a code that given, nn and Plarry's composition, will output every 33rd word.

Sample input:

77

This

Is

Seven

Words

Or

More

Than

Sample Output:

Seven

More

Congratz to those who have solved it, i'll post the answer 2 days later ^.^

Feel free to look at the answers below for reference, mine is quite similar to Daniel's but I feel that taking a look at the other languages would have benefits too!

#ComputerScience

Note by Charlton Teo
6 years, 10 months ago

No vote yet
1 vote

  Easy Math Editor

This discussion board is a place to discuss our Daily Challenges and the math and science related to those challenges. Explanations are more than just a solution — they should explain the steps and thinking strategies that you used to obtain the solution. Comments should further the discussion of math and science.

When posting on Brilliant:

  • Use the emojis to react to an explanation, whether you're congratulating a job well done , or just really confused .
  • Ask specific questions about the challenge or the steps in somebody's explanation. Well-posed questions can add a lot to the discussion, but posting "I don't understand!" doesn't help anyone.
  • Try to contribute something new to the discussion, whether it is an extension, generalization or other idea related to the challenge.
  • Stay on topic — we're all here to learn more about math and science, not to hear about your favorite get-rich-quick scheme or current world events.

MarkdownAppears as
*italics* or _italics_ italics
**bold** or __bold__ bold

- bulleted
- list

  • bulleted
  • list

1. numbered
2. list

  1. numbered
  2. list
Note: you must add a full line of space before and after lists for them to show up correctly
paragraph 1

paragraph 2

paragraph 1

paragraph 2

[example link](https://brilliant.org)example link
> This is a quote
This is a quote
    # I indented these lines
    # 4 spaces, and now they show
    # up as a code block.

    print "hello world"
# I indented these lines
# 4 spaces, and now they show
# up as a code block.

print "hello world"
MathAppears as
Remember to wrap math in \( ... \) or \[ ... \] to ensure proper formatting.
2 \times 3 2×3 2 \times 3
2^{34} 234 2^{34}
a_{i-1} ai1 a_{i-1}
\frac{2}{3} 23 \frac{2}{3}
\sqrt{2} 2 \sqrt{2}
\sum_{i=1}^3 i=13 \sum_{i=1}^3
\sin \theta sinθ \sin \theta
\boxed{123} 123 \boxed{123}

Comments

Here is a python2 solution below:

1
2
3
4
5
6
7
8
9
num = input() # number of words 
printable = []
for i in xrange(1, num+1):
    if i%3 == 0:
        printable.append(raw_input()) # Only inserting the needed words that we'll print
    else:
        raw_input() # simply rejecting this input
for word in printable:
    print word 

Sudip Maji - 6 years, 10 months ago

In C:

#include <stdio.h>

int main() {
    int N;
    scanf("%d\n", &N);
    for(int i = 1; i <= N; i++) {
        char *str = malloc(100 * sizeof(str));
        scanf("%s\n", str);
        if(i % 3 == 0) printf("%s\n", str);
        // to avoid memory leak
        free(str);
   }
   return 0;
}

Ruhan Habib - 6 years, 10 months ago

C++

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
#include <iostream>
#include <string>
using namespace std;

int main() {

    int TC; cin >> TC;
    for(int i = 1; i <= TC; i++){
        string str; cin >> str;
        if(i%3==0)
        cout << str << endl;
    }

    return 0;
}

Daniel Lim - 6 years, 10 months ago

Log in to reply

I don't really think the string library was required but the code pretty much works :D

Charlton Teo - 6 years, 10 months ago

Log in to reply

yes, the string library is required or else cin and cout won't work, based on my experience

Daniel Lim - 6 years, 10 months ago

Log in to reply

@Daniel Lim yeaa, I'm sure you can find a way of doing the same thing without using the classes, (therefore using C instead of C++), you could just set up a row counter, read the first parameter to know where to end your loop, and then read the following lines one by one, and when your counter got to a multiple of three you just replicate all the characters you read from input to output and break the line. The coolest way to do it is use the less resources, haha :D

Lucas Franceschi - 6 years, 10 months ago

@Daniel Lim The cin and cout streams are defined in the iostream header and using namespace std is required for their correct interpretation. string header was used for the string data type used which makes the task easier. You can try any of the string ( /character array) input methods like getline, scanf, etc to get the input depending on the type u have defined.

Aditya Raj - 6 years, 10 months ago

Log in to reply

@Aditya Raj yes I can, but I don't really like scanf and I like the syntax of cin more than getline

Daniel Lim - 6 years, 10 months ago

Log in to reply

@Daniel Lim why don't you like?

Riaz Ahmad Baboojee - 6 years, 10 months ago

@Daniel Lim Sure everyone has there own choices but just for fun, once study the scanf features. Its much faster than cin (unless u link cin to scanf). For the part where you dont want to use classes(which I forgot to mention in the previous post :|) Lucas' answer is great as long as you dont want to store the string for future use. 2 simple implementations include creating a char pointer which stores the present string if u need to print it or else if you don't want to store it then just output it during reading only which can be terminated with the delimitter mentioned according to the constraints mentioned or the general delimitter '\0' of strings in c++.

Aditya Raj - 6 years, 10 months ago

Log in to reply

@Aditya Raj yes it is faster indeed, but sometimes it does not work, i dont know

Daniel Lim - 6 years, 10 months ago

1
print("\n".join([input() for _ in range(int(input()))][2::3]))

One-liner Python, but clearly isn't readable. Basically, range(int(input())) makes a loop of n iterations where n is the number in the input, then [input() for _ in ...] creates a list of the words, iterating n times, then ...[2::3] means taking from the 2nd item (0-based, so 1-based means from the 3rd item) and taking every third item afterwards, then "\n".join(...) means joining all the items, inserting a newline character (\n) between items, and print(...) displays the resulting string.

Let's play code golf! Can you make a program (in any language, but not one specifically designed to solve this particular problem) that solves this in as few characters as possible? The above is 62 characters (61 if you count \n as one character).

Ivan Koswara - 6 years, 10 months ago

Here is a pascal solution below: var n,i,j:longint; arr:array [1..1000] of string; begin readln(n); for i:=1 to n do begin readln(arr[i]); end; for j:=1 to n do begin if (j mod 3)=0 then writeln(arr[j]); end; end.

Roihan Munajih - 6 years, 10 months ago

Log in to reply

I tried running this code and they gave me "Error - Program name is missing in main file". Could you be missing something? (Sorry not that familiar with pascal)

Charlton Teo - 6 years, 10 months ago

You can practice here Hackerrank

Daniel Lim - 6 years, 10 months ago

JavaScript

function everyThirdLine(input) {
    return input
        .split('\n')
        .reduce(function(memo, n, i) {
            if ((i + 1) % 3 === 0) {
                memo += n + '\n';
            }
            return memo;
        }, '')
        .trim();
}

J H - 6 years, 10 months ago

here is the answer:

 1
 2
 3
 4
 5
 6
 7
 8
 9
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
#include "stdafx.h"
#include <iostream>
#include <string>
#include <string.h>
#include "stdio.h"
#include "string.h"
#include "string"
class Parry
{
    private:
        int n;
        std::string line[100];
    public:
        void getline();
        void code();
};
void Parry::getline()
{
    std::cout<<"Enter the number of lines"<<std::endl;
    std::cin>>n;
    std::cout<<"Enter the lines"<<std::endl;
    for(int i=0;i<n;i++)
    {
        std::cin>>line[i];
    }
}
void Parry::code()
{
    int j=n/3;
    for(int i=1;i<=j;i++)
    {
        std::cout<<line[(3*i)-1]<<std::endl;
    }
}


int _tmain(int argc, _TCHAR* argv[])
{
    Parry p;
    p.getline();
    p.code();
    getchar();
} 

vaibhav zambad - 6 years, 10 months ago

Ruby solution: lines = ["7","This", "Is", "Seven","Words", "Or", "More] 0.step(lines.length-1,2) {|index| puts lines [index]}

Viktoriya Forrest - 6 years, 10 months ago

python, using the standard library

1
output = [x for i, x in enumerate(input_line.split(' ')) if i % 3 is 2]

Josh Silverman Staff - 6 years, 10 months ago

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
words=[]
num=int(input("How many words: "))
print("Enter ",num," words..")
while num>0:
        words.append(input())
        num=num-1
num=1
print(words)
for word in words:
    if num == 3:
        print(word)
        num=0
    num=num+1

Not effective Python solution but works.

Shubham Gaikwad - 6 years, 10 months ago

Log in to reply

Incorrect, because the problem doesn't ask you to output "How many words:", "Enter x words..", and the list of words. Your output must be precisely as required.

Ivan Koswara - 6 years, 10 months ago

In JAVA :

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
import java.util.Scanner;

public class Sample {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner s = new Scanner(System.in);
        int a = s.nextInt();
        String str[] = new String[a];
        for(int i=0;i<a;i++){
            str[i] = s.nextLine();
        }
        for(int i=0;i<a;i++){
            if((i+1)%3==0){
                System.out.println(""+str[i]);
            }
        }
    }

} 

Roopesh H - 6 years, 10 months ago

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <string>
using namespace std;

int main() {

    int TC; cin >> TC;
    string str[10]; 
    for(int i = 1; i <= TC; i++)
    {

        cin >> str[i];
    }
      for(int i = 1; i <= TC; i++)
        {
        if(i%3==0)
        cout << str[i] << endl;
          }

    return 0;
} 

Tanmay Sentiya - 6 years, 10 months ago

MATLAB

num = inputdlg('Input Number: ','Input');
num = str2num(num);
out =  [];
for x = 1:num
        str = inputdlg('Input Number: ','Input');
        switch _mod(x,3)
              case 0
                    out = [out str '\r\n'];
         end
end
fprintf('%s', out);

Roi Vinson Abrazaldo - 6 years, 10 months ago

Log in to reply

the 2nd Input Number should have been Input Word. copy/paste mistake

Roi Vinson Abrazaldo - 6 years, 10 months ago

This is in Microsoft Small Basic :)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
count = 0

n = TextWindow.Read()

For i = 1 to n
    word = TextWindow.Read()
    count = count + 1
    If count = 3 Then
        TextWindow.WriteLine(word)
        count = 0
    EndIf
EndFor

dana chiueh - 6 years, 10 months ago

Haskell solution:

-- with IO
main = getLine >> lines <$> getContents >>= \xs -> putStr . unlines $ map (xs !!) [3,6..length xs]
-- without IO (pure)
\xs->map (xs!!)[3,6..length xs]

-- 31 characters. I win!

Why are people learning C++ when Haskell is obviously more awesome? :D

Magnetic Duck - 6 years, 9 months ago

PHP:

<?PHP
function everyThirdWord($string) {
    $word = explode(" ",$string);
    for($i = 1; $i < str_word_count($string, 0); $i++ ) {
        if($i%3 == 0){
            echo $word[$i-1]."<br>";
        }
    }
}
?>

Danilo Azevedo - 6 years, 8 months ago

Thanks to everyone who tried, anyway here was my solution:

Language: C++

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
#include<iostream>
using namespace std;
int main(){
string p[1000000];
cin>>x;
for(int i = 1; i <= x; i++){
getline (cin,p[i]);
getline (cin,p[i]);
}
for(int i = 0; i <= x/3; i+=3){
cout<<p[i];
}
}

But i feel that Iamsudip and Daniel's answers were better to please refer to theirs (for mine i didnt need string library i think i use a diff version)

Charlton Teo - 6 years, 10 months ago

Python 3 solution. (Note: this will ONLY work in Python 3 because print is treated as a function and NOT a keyword as Python 2 does):

line_list = [] #List that will store all the lines

input_size = int(input()) #Get all the lines
for i in range(input_size):
    line_list.append(input())

print("") #Adds a new line for readability (optional)

list(map(print, line_list[2::3])) #Print the result

Sample output:

Input:

7
This
Is
Seven
Words
Or
More
Than

Prints:

Seven
More

L N - 6 years, 10 months ago

Void main() { Int I,n; Char ch[10][10]; Cout<<"enter no of lines"; Cin>>n; For(I=0;I<n;I++) {Cin>>ch[I]; } For(I=0;I<n;I++) { If((i%3==0)&&(I!=0)) Cout<<ch [I]; } Getch (); }

Ashish Kapil - 6 years, 10 months ago
×

Problem Loading...

Note Loading...

Set Loading...